merge changes for seperator change
[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  * @singleton
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 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.Reader} reader 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         if(!o || success === false){
716             if(success !== false){
717                 this.fireEvent("load", this, [], options, o);
718             }
719             if(options.callback){
720                 options.callback.call(options.scope || this, [], options, false);
721             }
722             return;
723         }
724         // if data returned failure - throw an exception.
725         if (o.success === false) {
726             // show a message if no listener is registered.
727             if (!this.hasListener('loadexception') && typeof(o.raw.errorMsg) != 'undefined') {
728                     Roo.MessageBox.alert("Error loading",o.raw.errorMsg);
729             }
730             // loadmask wil be hooked into this..
731             this.fireEvent("loadexception", this, o, options, o.raw.errorMsg);
732             return;
733         }
734         var r = o.records, t = o.totalRecords || r.length;
735         
736         this.fireEvent("beforeloadadd", this, r, options, o);
737         
738         if(!options || options.add !== true){
739             if(this.pruneModifiedRecords){
740                 this.modified = [];
741             }
742             for(var i = 0, len = r.length; i < len; i++){
743                 r[i].join(this);
744             }
745             if(this.snapshot){
746                 this.data = this.snapshot;
747                 delete this.snapshot;
748             }
749             this.data.clear();
750             this.data.addAll(r);
751             this.totalLength = t;
752             this.applySort();
753             this.fireEvent("datachanged", this);
754         }else{
755             this.totalLength = Math.max(t, this.data.length+r.length);
756             this.add(r);
757         }
758         
759         if(this.parent && !Roo.isIOS && !this.useNativeIOS && this.parent.emptyTitle.length) {
760                 
761             var e = new Roo.data.Record({});
762
763             e.set(this.parent.displayField, this.parent.emptyTitle);
764             e.set(this.parent.valueField, '');
765
766             this.insert(0, e);
767         }
768             
769         this.fireEvent("load", this, r, options, o);
770         if(options.callback){
771             options.callback.call(options.scope || this, r, options, true);
772         }
773     },
774
775
776     /**
777      * Loads data from a passed data block. A Reader which understands the format of the data
778      * must have been configured in the constructor.
779      * @param {Object} data The data block from which to read the Records.  The format of the data expected
780      * is dependent on the type of Reader that is configured and should correspond to that Reader's readRecords parameter.
781      * @param {Boolean} append (Optional) True to append the new Records rather than replace the existing cache.
782      */
783     loadData : function(o, append){
784         var r = this.reader.readRecords(o);
785         this.loadRecords(r, {add: append}, true);
786     },
787     
788      /**
789      * using 'cn' the nested child reader read the child array into it's child stores.
790      * @param {Object} rec The record with a 'children array
791      */
792     loadDataFromChildren : function(rec)
793     {
794         this.loadData(this.reader.toLoadData(rec));
795     },
796     
797
798     /**
799      * Gets the number of cached records.
800      * <p>
801      * <em>If using paging, this may not be the total size of the dataset. If the data object
802      * used by the Reader contains the dataset size, then the getTotalCount() function returns
803      * the data set size</em>
804      */
805     getCount : function(){
806         return this.data.length || 0;
807     },
808
809     /**
810      * Gets the total number of records in the dataset as returned by the server.
811      * <p>
812      * <em>If using paging, for this to be accurate, the data object used by the Reader must contain
813      * the dataset size</em>
814      */
815     getTotalCount : function(){
816         return this.totalLength || 0;
817     },
818
819     /**
820      * Returns the sort state of the Store as an object with two properties:
821      * <pre><code>
822  field {String} The name of the field by which the Records are sorted
823  direction {String} The sort order, "ASC" or "DESC"
824      * </code></pre>
825      */
826     getSortState : function(){
827         return this.sortInfo;
828     },
829
830     // private
831     applySort : function(){
832         if(this.sortInfo && !this.remoteSort){
833             var s = this.sortInfo, f = s.field;
834             var st = this.fields.get(f).sortType;
835             var fn = function(r1, r2){
836                 var v1 = st(r1.data[f]), v2 = st(r2.data[f]);
837                 return v1 > v2 ? 1 : (v1 < v2 ? -1 : 0);
838             };
839             this.data.sort(s.direction, fn);
840             if(this.snapshot && this.snapshot != this.data){
841                 this.snapshot.sort(s.direction, fn);
842             }
843         }
844     },
845
846     /**
847      * Sets the default sort column and order to be used by the next load operation.
848      * @param {String} fieldName The name of the field to sort by.
849      * @param {String} dir (optional) The sort order, "ASC" or "DESC" (defaults to "ASC")
850      */
851     setDefaultSort : function(field, dir){
852         this.sortInfo = {field: field, direction: dir ? dir.toUpperCase() : "ASC"};
853     },
854
855     /**
856      * Sort the Records.
857      * If remote sorting is used, the sort is performed on the server, and the cache is
858      * reloaded. If local sorting is used, the cache is sorted internally.
859      * @param {String} fieldName The name of the field to sort by.
860      * @param {String} dir (optional) The sort order, "ASC" or "DESC" (defaults to "ASC")
861      */
862     sort : function(fieldName, dir){
863         var f = this.fields.get(fieldName);
864         if(!dir){
865             this.sortToggle[f.name] = this.sortToggle[f.name] || f.sortDir;
866             
867             if(this.multiSort || (this.sortInfo && this.sortInfo.field == f.name) ){ // toggle sort dir
868                 dir = (this.sortToggle[f.name] || "ASC").toggle("ASC", "DESC");
869             }else{
870                 dir = f.sortDir;
871             }
872         }
873         this.sortToggle[f.name] = dir;
874         this.sortInfo = {field: f.name, direction: dir};
875         if(!this.remoteSort){
876             this.applySort();
877             this.fireEvent("datachanged", this);
878         }else{
879             this.load(this.lastOptions);
880         }
881     },
882
883     /**
884      * Calls the specified function for each of the Records in the cache.
885      * @param {Function} fn The function to call. The Record is passed as the first parameter.
886      * Returning <em>false</em> aborts and exits the iteration.
887      * @param {Object} scope (optional) The scope in which to call the function (defaults to the Record).
888      */
889     each : function(fn, scope){
890         this.data.each(fn, scope);
891     },
892
893     /**
894      * Gets all records modified since the last commit.  Modified records are persisted across load operations
895      * (e.g., during paging).
896      * @return {Roo.data.Record[]} An array of Records containing outstanding modifications.
897      */
898     getModifiedRecords : function(){
899         return this.modified;
900     },
901
902     // private
903     createFilterFn : function(property, value, anyMatch){
904         if(!value.exec){ // not a regex
905             value = String(value);
906             if(value.length == 0){
907                 return false;
908             }
909             value = new RegExp((anyMatch === true ? '' : '^') + Roo.escapeRe(value), "i");
910         }
911         return function(r){
912             return value.test(r.data[property]);
913         };
914     },
915
916     /**
917      * Sums the value of <i>property</i> for each record between start and end and returns the result.
918      * @param {String} property A field on your records
919      * @param {Number} start The record index to start at (defaults to 0)
920      * @param {Number} end The last record index to include (defaults to length - 1)
921      * @return {Number} The sum
922      */
923     sum : function(property, start, end){
924         var rs = this.data.items, v = 0;
925         start = start || 0;
926         end = (end || end === 0) ? end : rs.length-1;
927
928         for(var i = start; i <= end; i++){
929             v += (rs[i].data[property] || 0);
930         }
931         return v;
932     },
933
934     /**
935      * Filter the records by a specified property.
936      * @param {String} field A field on your records
937      * @param {String/RegExp} value Either a string that the field
938      * should start with or a RegExp to test against the field
939      * @param {Boolean} anyMatch True to match any part not just the beginning
940      */
941     filter : function(property, value, anyMatch){
942         var fn = this.createFilterFn(property, value, anyMatch);
943         return fn ? this.filterBy(fn) : this.clearFilter();
944     },
945
946     /**
947      * Filter by a function. The specified function will be called with each
948      * record in this data source. If the function returns true the record is included,
949      * otherwise it is filtered.
950      * @param {Function} fn The function to be called, it will receive 2 args (record, id)
951      * @param {Object} scope (optional) The scope of the function (defaults to this)
952      */
953     filterBy : function(fn, scope){
954         this.snapshot = this.snapshot || this.data;
955         this.data = this.queryBy(fn, scope||this);
956         this.fireEvent("datachanged", this);
957     },
958
959     /**
960      * Query the records by a specified property.
961      * @param {String} field A field on your records
962      * @param {String/RegExp} value Either a string that the field
963      * should start with or a RegExp to test against the field
964      * @param {Boolean} anyMatch True to match any part not just the beginning
965      * @return {MixedCollection} Returns an Roo.util.MixedCollection of the matched records
966      */
967     query : function(property, value, anyMatch){
968         var fn = this.createFilterFn(property, value, anyMatch);
969         return fn ? this.queryBy(fn) : this.data.clone();
970     },
971
972     /**
973      * Query by a function. The specified function will be called with each
974      * record in this data source. If the function returns true the record is included
975      * in the results.
976      * @param {Function} fn The function to be called, it will receive 2 args (record, id)
977      * @param {Object} scope (optional) The scope of the function (defaults to this)
978       @return {MixedCollection} Returns an Roo.util.MixedCollection of the matched records
979      **/
980     queryBy : function(fn, scope){
981         var data = this.snapshot || this.data;
982         return data.filterBy(fn, scope||this);
983     },
984
985     /**
986      * Collects unique values for a particular dataIndex from this store.
987      * @param {String} dataIndex The property to collect
988      * @param {Boolean} allowNull (optional) Pass true to allow null, undefined or empty string values
989      * @param {Boolean} bypassFilter (optional) Pass true to collect from all records, even ones which are filtered
990      * @return {Array} An array of the unique values
991      **/
992     collect : function(dataIndex, allowNull, bypassFilter){
993         var d = (bypassFilter === true && this.snapshot) ?
994                 this.snapshot.items : this.data.items;
995         var v, sv, r = [], l = {};
996         for(var i = 0, len = d.length; i < len; i++){
997             v = d[i].data[dataIndex];
998             sv = String(v);
999             if((allowNull || !Roo.isEmpty(v)) && !l[sv]){
1000                 l[sv] = true;
1001                 r[r.length] = v;
1002             }
1003         }
1004         return r;
1005     },
1006
1007     /**
1008      * Revert to a view of the Record cache with no filtering applied.
1009      * @param {Boolean} suppressEvent If true the filter is cleared silently without notifying listeners
1010      */
1011     clearFilter : function(suppressEvent){
1012         if(this.snapshot && this.snapshot != this.data){
1013             this.data = this.snapshot;
1014             delete this.snapshot;
1015             if(suppressEvent !== true){
1016                 this.fireEvent("datachanged", this);
1017             }
1018         }
1019     },
1020
1021     // private
1022     afterEdit : function(record){
1023         if(this.modified.indexOf(record) == -1){
1024             this.modified.push(record);
1025         }
1026         this.fireEvent("update", this, record, Roo.data.Record.EDIT);
1027     },
1028     
1029     // private
1030     afterReject : function(record){
1031         this.modified.remove(record);
1032         this.fireEvent("update", this, record, Roo.data.Record.REJECT);
1033     },
1034
1035     // private
1036     afterCommit : function(record){
1037         this.modified.remove(record);
1038         this.fireEvent("update", this, record, Roo.data.Record.COMMIT);
1039     },
1040
1041     /**
1042      * Commit all Records with outstanding changes. To handle updates for changes, subscribe to the
1043      * Store's "update" event, and perform updating when the third parameter is Roo.data.Record.COMMIT.
1044      */
1045     commitChanges : function(){
1046         var m = this.modified.slice(0);
1047         this.modified = [];
1048         for(var i = 0, len = m.length; i < len; i++){
1049             m[i].commit();
1050         }
1051     },
1052
1053     /**
1054      * Cancel outstanding changes on all changed records.
1055      */
1056     rejectChanges : function(){
1057         var m = this.modified.slice(0);
1058         this.modified = [];
1059         for(var i = 0, len = m.length; i < len; i++){
1060             m[i].reject();
1061         }
1062     },
1063
1064     onMetaChange : function(meta, rtype, o){
1065         this.recordType = rtype;
1066         this.fields = rtype.prototype.fields;
1067         delete this.snapshot;
1068         this.sortInfo = meta.sortInfo || this.sortInfo;
1069         this.modified = [];
1070         this.fireEvent('metachange', this, this.reader.meta);
1071     },
1072     
1073     moveIndex : function(data, type)
1074     {
1075         var index = this.indexOf(data);
1076         
1077         var newIndex = index + type;
1078         
1079         this.remove(data);
1080         
1081         this.insert(newIndex, data);
1082         
1083     }
1084 });/*
1085  * Based on:
1086  * Ext JS Library 1.1.1
1087  * Copyright(c) 2006-2007, Ext JS, LLC.
1088  *
1089  * Originally Released Under LGPL - original licence link has changed is not relivant.
1090  *
1091  * Fork - LGPL
1092  * <script type="text/javascript">
1093  */
1094
1095 /**
1096  * @class Roo.data.SimpleStore
1097  * @extends Roo.data.Store
1098  * Small helper class to make creating Stores from Array data easier.
1099  * @cfg {Number} id The array index of the record id. Leave blank to auto generate ids.
1100  * @cfg {Array} fields An array of field definition objects, or field name strings.
1101  * @cfg {Object} an existing reader (eg. copied from another store)
1102  * @cfg {Array} data The multi-dimensional array of data
1103  * @constructor
1104  * @param {Object} config
1105  */
1106 Roo.data.SimpleStore = function(config)
1107 {
1108     Roo.data.SimpleStore.superclass.constructor.call(this, {
1109         isLocal : true,
1110         reader: typeof(config.reader) != 'undefined' ? config.reader : new Roo.data.ArrayReader({
1111                 id: config.id
1112             },
1113             Roo.data.Record.create(config.fields)
1114         ),
1115         proxy : new Roo.data.MemoryProxy(config.data)
1116     });
1117     this.load();
1118 };
1119 Roo.extend(Roo.data.SimpleStore, Roo.data.Store);/*
1120  * Based on:
1121  * Ext JS Library 1.1.1
1122  * Copyright(c) 2006-2007, Ext JS, LLC.
1123  *
1124  * Originally Released Under LGPL - original licence link has changed is not relivant.
1125  *
1126  * Fork - LGPL
1127  * <script type="text/javascript">
1128  */
1129
1130 /**
1131 /**
1132  * @extends Roo.data.Store
1133  * @class Roo.data.JsonStore
1134  * Small helper class to make creating Stores for JSON data easier. <br/>
1135 <pre><code>
1136 var store = new Roo.data.JsonStore({
1137     url: 'get-images.php',
1138     root: 'images',
1139     fields: ['name', 'url', {name:'size', type: 'float'}, {name:'lastmod', type:'date'}]
1140 });
1141 </code></pre>
1142  * <b>Note: Although they are not listed, this class inherits all of the config options of Store,
1143  * JsonReader and HttpProxy (unless inline data is provided).</b>
1144  * @cfg {Array} fields An array of field definition objects, or field name strings.
1145  * @constructor
1146  * @param {Object} config
1147  */
1148 Roo.data.JsonStore = function(c){
1149     Roo.data.JsonStore.superclass.constructor.call(this, Roo.apply(c, {
1150         proxy: !c.data ? new Roo.data.HttpProxy({url: c.url}) : undefined,
1151         reader: new Roo.data.JsonReader(c, c.fields)
1152     }));
1153 };
1154 Roo.extend(Roo.data.JsonStore, Roo.data.Store);/*
1155  * Based on:
1156  * Ext JS Library 1.1.1
1157  * Copyright(c) 2006-2007, Ext JS, LLC.
1158  *
1159  * Originally Released Under LGPL - original licence link has changed is not relivant.
1160  *
1161  * Fork - LGPL
1162  * <script type="text/javascript">
1163  */
1164
1165  
1166 Roo.data.Field = function(config){
1167     if(typeof config == "string"){
1168         config = {name: config};
1169     }
1170     Roo.apply(this, config);
1171     
1172     if(!this.type){
1173         this.type = "auto";
1174     }
1175     
1176     var st = Roo.data.SortTypes;
1177     // named sortTypes are supported, here we look them up
1178     if(typeof this.sortType == "string"){
1179         this.sortType = st[this.sortType];
1180     }
1181     
1182     // set default sortType for strings and dates
1183     if(!this.sortType){
1184         switch(this.type){
1185             case "string":
1186                 this.sortType = st.asUCString;
1187                 break;
1188             case "date":
1189                 this.sortType = st.asDate;
1190                 break;
1191             default:
1192                 this.sortType = st.none;
1193         }
1194     }
1195
1196     // define once
1197     var stripRe = /[\$,%]/g;
1198
1199     // prebuilt conversion function for this field, instead of
1200     // switching every time we're reading a value
1201     if(!this.convert){
1202         var cv, dateFormat = this.dateFormat;
1203         switch(this.type){
1204             case "":
1205             case "auto":
1206             case undefined:
1207                 cv = function(v){ return v; };
1208                 break;
1209             case "string":
1210                 cv = function(v){ return (v === undefined || v === null) ? '' : String(v); };
1211                 break;
1212             case "int":
1213                 cv = function(v){
1214                     return v !== undefined && v !== null && v !== '' ?
1215                            parseInt(String(v).replace(stripRe, ""), 10) : '';
1216                     };
1217                 break;
1218             case "float":
1219                 cv = function(v){
1220                     return v !== undefined && v !== null && v !== '' ?
1221                            parseFloat(String(v).replace(stripRe, ""), 10) : ''; 
1222                     };
1223                 break;
1224             case "bool":
1225             case "boolean":
1226                 cv = function(v){ return v === true || v === "true" || v == 1; };
1227                 break;
1228             case "date":
1229                 cv = function(v){
1230                     if(!v){
1231                         return '';
1232                     }
1233                     if(v instanceof Date){
1234                         return v;
1235                     }
1236                     if(dateFormat){
1237                         if(dateFormat == "timestamp"){
1238                             return new Date(v*1000);
1239                         }
1240                         return Date.parseDate(v, dateFormat);
1241                     }
1242                     var parsed = Date.parse(v);
1243                     return parsed ? new Date(parsed) : null;
1244                 };
1245              break;
1246             
1247         }
1248         this.convert = cv;
1249     }
1250 };
1251
1252 Roo.data.Field.prototype = {
1253     dateFormat: null,
1254     defaultValue: "",
1255     mapping: null,
1256     sortType : null,
1257     sortDir : "ASC"
1258 };/*
1259  * Based on:
1260  * Ext JS Library 1.1.1
1261  * Copyright(c) 2006-2007, Ext JS, LLC.
1262  *
1263  * Originally Released Under LGPL - original licence link has changed is not relivant.
1264  *
1265  * Fork - LGPL
1266  * <script type="text/javascript">
1267  */
1268  
1269 // Base class for reading structured data from a data source.  This class is intended to be
1270 // extended (see ArrayReader, JsonReader and XmlReader) and should not be created directly.
1271
1272 /**
1273  * @class Roo.data.DataReader
1274  * Base class for reading structured data from a data source.  This class is intended to be
1275  * extended (see {Roo.data.ArrayReader}, {Roo.data.JsonReader} and {Roo.data.XmlReader}) and should not be created directly.
1276  */
1277
1278 Roo.data.DataReader = function(meta, recordType){
1279     
1280     this.meta = meta;
1281     
1282     this.recordType = recordType instanceof Array ? 
1283         Roo.data.Record.create(recordType) : recordType;
1284 };
1285
1286 Roo.data.DataReader.prototype = {
1287     
1288     
1289     readerType : 'Data',
1290      /**
1291      * Create an empty record
1292      * @param {Object} data (optional) - overlay some values
1293      * @return {Roo.data.Record} record created.
1294      */
1295     newRow :  function(d) {
1296         var da =  {};
1297         this.recordType.prototype.fields.each(function(c) {
1298             switch( c.type) {
1299                 case 'int' : da[c.name] = 0; break;
1300                 case 'date' : da[c.name] = new Date(); break;
1301                 case 'float' : da[c.name] = 0.0; break;
1302                 case 'boolean' : da[c.name] = false; break;
1303                 default : da[c.name] = ""; break;
1304             }
1305             
1306         });
1307         return new this.recordType(Roo.apply(da, d));
1308     }
1309     
1310     
1311 };/*
1312  * Based on:
1313  * Ext JS Library 1.1.1
1314  * Copyright(c) 2006-2007, Ext JS, LLC.
1315  *
1316  * Originally Released Under LGPL - original licence link has changed is not relivant.
1317  *
1318  * Fork - LGPL
1319  * <script type="text/javascript">
1320  */
1321
1322 /**
1323  * @class Roo.data.DataProxy
1324  * @extends Roo.data.Observable
1325  * This class is an abstract base class for implementations which provide retrieval of
1326  * unformatted data objects.<br>
1327  * <p>
1328  * DataProxy implementations are usually used in conjunction with an implementation of Roo.data.DataReader
1329  * (of the appropriate type which knows how to parse the data object) to provide a block of
1330  * {@link Roo.data.Records} to an {@link Roo.data.Store}.<br>
1331  * <p>
1332  * Custom implementations must implement the load method as described in
1333  * {@link Roo.data.HttpProxy#load}.
1334  */
1335 Roo.data.DataProxy = function(){
1336     this.addEvents({
1337         /**
1338          * @event beforeload
1339          * Fires before a network request is made to retrieve a data object.
1340          * @param {Object} This DataProxy object.
1341          * @param {Object} params The params parameter to the load function.
1342          */
1343         beforeload : true,
1344         /**
1345          * @event load
1346          * Fires before the load method's callback is called.
1347          * @param {Object} This DataProxy object.
1348          * @param {Object} o The data object.
1349          * @param {Object} arg The callback argument object passed to the load function.
1350          */
1351         load : true,
1352         /**
1353          * @event loadexception
1354          * Fires if an Exception occurs during data retrieval.
1355          * @param {Object} This DataProxy object.
1356          * @param {Object} o The data object.
1357          * @param {Object} arg The callback argument object passed to the load function.
1358          * @param {Object} e The Exception.
1359          */
1360         loadexception : true
1361     });
1362     Roo.data.DataProxy.superclass.constructor.call(this);
1363 };
1364
1365 Roo.extend(Roo.data.DataProxy, Roo.util.Observable);
1366
1367     /**
1368      * @cfg {void} listeners (Not available) Constructor blocks listeners from being set
1369      */
1370 /*
1371  * Based on:
1372  * Ext JS Library 1.1.1
1373  * Copyright(c) 2006-2007, Ext JS, LLC.
1374  *
1375  * Originally Released Under LGPL - original licence link has changed is not relivant.
1376  *
1377  * Fork - LGPL
1378  * <script type="text/javascript">
1379  */
1380 /**
1381  * @class Roo.data.MemoryProxy
1382  * An implementation of Roo.data.DataProxy that simply passes the data specified in its constructor
1383  * to the Reader when its load method is called.
1384  * @constructor
1385  * @param {Object} data The data object which the Reader uses to construct a block of Roo.data.Records.
1386  */
1387 Roo.data.MemoryProxy = function(data){
1388     if (data.data) {
1389         data = data.data;
1390     }
1391     Roo.data.MemoryProxy.superclass.constructor.call(this);
1392     this.data = data;
1393 };
1394
1395 Roo.extend(Roo.data.MemoryProxy, Roo.data.DataProxy, {
1396     
1397     /**
1398      * Load data from the requested source (in this case an in-memory
1399      * data object passed to the constructor), read the data object into
1400      * a block of Roo.data.Records using the passed Roo.data.DataReader implementation, and
1401      * process that block using the passed callback.
1402      * @param {Object} params This parameter is not used by the MemoryProxy class.
1403      * @param {Roo.data.DataReader} reader The Reader object which converts the data
1404      * object into a block of Roo.data.Records.
1405      * @param {Function} callback The function into which to pass the block of Roo.data.records.
1406      * The function must be passed <ul>
1407      * <li>The Record block object</li>
1408      * <li>The "arg" argument from the load function</li>
1409      * <li>A boolean success indicator</li>
1410      * </ul>
1411      * @param {Object} scope The scope in which to call the callback
1412      * @param {Object} arg An optional argument which is passed to the callback as its second parameter.
1413      */
1414     load : function(params, reader, callback, scope, arg){
1415         params = params || {};
1416         var result;
1417         try {
1418             result = reader.readRecords(params.data ? params.data :this.data);
1419         }catch(e){
1420             this.fireEvent("loadexception", this, arg, null, e);
1421             callback.call(scope, null, arg, false);
1422             return;
1423         }
1424         callback.call(scope, result, arg, true);
1425     },
1426     
1427     // private
1428     update : function(params, records){
1429         
1430     }
1431 });/*
1432  * Based on:
1433  * Ext JS Library 1.1.1
1434  * Copyright(c) 2006-2007, Ext JS, LLC.
1435  *
1436  * Originally Released Under LGPL - original licence link has changed is not relivant.
1437  *
1438  * Fork - LGPL
1439  * <script type="text/javascript">
1440  */
1441 /**
1442  * @class Roo.data.HttpProxy
1443  * @extends Roo.data.DataProxy
1444  * An implementation of {@link Roo.data.DataProxy} that reads a data object from an {@link Roo.data.Connection} object
1445  * configured to reference a certain URL.<br><br>
1446  * <p>
1447  * <em>Note that this class cannot be used to retrieve data from a domain other than the domain
1448  * from which the running page was served.<br><br>
1449  * <p>
1450  * For cross-domain access to remote data, use an {@link Roo.data.ScriptTagProxy}.</em><br><br>
1451  * <p>
1452  * Be aware that to enable the browser to parse an XML document, the server must set
1453  * the Content-Type header in the HTTP response to "text/xml".
1454  * @constructor
1455  * @param {Object} conn Connection config options to add to each request (e.g. {url: 'foo.php'} or
1456  * an {@link Roo.data.Connection} object.  If a Connection config is passed, the singleton {@link Roo.Ajax} object
1457  * will be used to make the request.
1458  */
1459 Roo.data.HttpProxy = function(conn){
1460     Roo.data.HttpProxy.superclass.constructor.call(this);
1461     // is conn a conn config or a real conn?
1462     this.conn = conn;
1463     this.useAjax = !conn || !conn.events;
1464   
1465 };
1466
1467 Roo.extend(Roo.data.HttpProxy, Roo.data.DataProxy, {
1468     // thse are take from connection...
1469     
1470     /**
1471      * @cfg {String} url (Optional) The default URL to be used for requests to the server. (defaults to undefined)
1472      */
1473     /**
1474      * @cfg {Object} extraParams (Optional) An object containing properties which are used as
1475      * extra parameters to each request made by this object. (defaults to undefined)
1476      */
1477     /**
1478      * @cfg {Object} defaultHeaders (Optional) An object containing request headers which are added
1479      *  to each request made by this object. (defaults to undefined)
1480      */
1481     /**
1482      * @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)
1483      */
1484     /**
1485      * @cfg {Number} timeout (Optional) The timeout in milliseconds to be used for requests. (defaults to 30000)
1486      */
1487      /**
1488      * @cfg {Boolean} autoAbort (Optional) Whether this request should abort any pending requests. (defaults to false)
1489      * @type Boolean
1490      */
1491   
1492
1493     /**
1494      * @cfg {Boolean} disableCaching (Optional) True to add a unique cache-buster param to GET requests. (defaults to true)
1495      * @type Boolean
1496      */
1497     /**
1498      * Return the {@link Roo.data.Connection} object being used by this Proxy.
1499      * @return {Connection} The Connection object. This object may be used to subscribe to events on
1500      * a finer-grained basis than the DataProxy events.
1501      */
1502     getConnection : function(){
1503         return this.useAjax ? Roo.Ajax : this.conn;
1504     },
1505
1506     /**
1507      * Load data from the configured {@link Roo.data.Connection}, read the data object into
1508      * a block of Roo.data.Records using the passed {@link Roo.data.DataReader} implementation, and
1509      * process that block using the passed callback.
1510      * @param {Object} params An object containing properties which are to be used as HTTP parameters
1511      * for the request to the remote server.
1512      * @param {Roo.data.DataReader} reader The Reader object which converts the data
1513      * object into a block of Roo.data.Records.
1514      * @param {Function} callback The function into which to pass the block of Roo.data.Records.
1515      * The function must be passed <ul>
1516      * <li>The Record block object</li>
1517      * <li>The "arg" argument from the load function</li>
1518      * <li>A boolean success indicator</li>
1519      * </ul>
1520      * @param {Object} scope The scope in which to call the callback
1521      * @param {Object} arg An optional argument which is passed to the callback as its second parameter.
1522      */
1523     load : function(params, reader, callback, scope, arg){
1524         if(this.fireEvent("beforeload", this, params) !== false){
1525             var  o = {
1526                 params : params || {},
1527                 request: {
1528                     callback : callback,
1529                     scope : scope,
1530                     arg : arg
1531                 },
1532                 reader: reader,
1533                 callback : this.loadResponse,
1534                 scope: this
1535             };
1536             if(this.useAjax){
1537                 Roo.applyIf(o, this.conn);
1538                 if(this.activeRequest){
1539                     Roo.Ajax.abort(this.activeRequest);
1540                 }
1541                 this.activeRequest = Roo.Ajax.request(o);
1542             }else{
1543                 this.conn.request(o);
1544             }
1545         }else{
1546             callback.call(scope||this, null, arg, false);
1547         }
1548     },
1549
1550     // private
1551     loadResponse : function(o, success, response){
1552         delete this.activeRequest;
1553         if(!success){
1554             this.fireEvent("loadexception", this, o, response);
1555             o.request.callback.call(o.request.scope, null, o.request.arg, false);
1556             return;
1557         }
1558         var result;
1559         try {
1560             result = o.reader.read(response);
1561         }catch(e){
1562             this.fireEvent("loadexception", this, o, response, e);
1563             o.request.callback.call(o.request.scope, null, o.request.arg, false);
1564             return;
1565         }
1566         
1567         this.fireEvent("load", this, o, o.request.arg);
1568         o.request.callback.call(o.request.scope, result, o.request.arg, true);
1569     },
1570
1571     // private
1572     update : function(dataSet){
1573
1574     },
1575
1576     // private
1577     updateResponse : function(dataSet){
1578
1579     }
1580 });/*
1581  * Based on:
1582  * Ext JS Library 1.1.1
1583  * Copyright(c) 2006-2007, Ext JS, LLC.
1584  *
1585  * Originally Released Under LGPL - original licence link has changed is not relivant.
1586  *
1587  * Fork - LGPL
1588  * <script type="text/javascript">
1589  */
1590
1591 /**
1592  * @class Roo.data.ScriptTagProxy
1593  * An implementation of Roo.data.DataProxy that reads a data object from a URL which may be in a domain
1594  * other than the originating domain of the running page.<br><br>
1595  * <p>
1596  * <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
1597  * of the running page, you must use this class, rather than DataProxy.</em><br><br>
1598  * <p>
1599  * The content passed back from a server resource requested by a ScriptTagProxy is executable JavaScript
1600  * source code that is used as the source inside a &lt;script> tag.<br><br>
1601  * <p>
1602  * In order for the browser to process the returned data, the server must wrap the data object
1603  * with a call to a callback function, the name of which is passed as a parameter by the ScriptTagProxy.
1604  * Below is a Java example for a servlet which returns data for either a ScriptTagProxy, or an HttpProxy
1605  * depending on whether the callback name was passed:
1606  * <p>
1607  * <pre><code>
1608 boolean scriptTag = false;
1609 String cb = request.getParameter("callback");
1610 if (cb != null) {
1611     scriptTag = true;
1612     response.setContentType("text/javascript");
1613 } else {
1614     response.setContentType("application/x-json");
1615 }
1616 Writer out = response.getWriter();
1617 if (scriptTag) {
1618     out.write(cb + "(");
1619 }
1620 out.print(dataBlock.toJsonString());
1621 if (scriptTag) {
1622     out.write(");");
1623 }
1624 </pre></code>
1625  *
1626  * @constructor
1627  * @param {Object} config A configuration object.
1628  */
1629 Roo.data.ScriptTagProxy = function(config){
1630     Roo.data.ScriptTagProxy.superclass.constructor.call(this);
1631     Roo.apply(this, config);
1632     this.head = document.getElementsByTagName("head")[0];
1633 };
1634
1635 Roo.data.ScriptTagProxy.TRANS_ID = 1000;
1636
1637 Roo.extend(Roo.data.ScriptTagProxy, Roo.data.DataProxy, {
1638     /**
1639      * @cfg {String} url The URL from which to request the data object.
1640      */
1641     /**
1642      * @cfg {Number} timeout (Optional) The number of milliseconds to wait for a response. Defaults to 30 seconds.
1643      */
1644     timeout : 30000,
1645     /**
1646      * @cfg {String} callbackParam (Optional) The name of the parameter to pass to the server which tells
1647      * the server the name of the callback function set up by the load call to process the returned data object.
1648      * Defaults to "callback".<p>The server-side processing must read this parameter value, and generate
1649      * javascript output which calls this named function passing the data object as its only parameter.
1650      */
1651     callbackParam : "callback",
1652     /**
1653      *  @cfg {Boolean} nocache (Optional) Defaults to true. Disable cacheing by adding a unique parameter
1654      * name to the request.
1655      */
1656     nocache : true,
1657
1658     /**
1659      * Load data from the configured URL, read the data object into
1660      * a block of Roo.data.Records using the passed Roo.data.DataReader implementation, and
1661      * process that block using the passed callback.
1662      * @param {Object} params An object containing properties which are to be used as HTTP parameters
1663      * for the request to the remote server.
1664      * @param {Roo.data.DataReader} reader The Reader object which converts the data
1665      * object into a block of Roo.data.Records.
1666      * @param {Function} callback The function into which to pass the block of Roo.data.Records.
1667      * The function must be passed <ul>
1668      * <li>The Record block object</li>
1669      * <li>The "arg" argument from the load function</li>
1670      * <li>A boolean success indicator</li>
1671      * </ul>
1672      * @param {Object} scope The scope in which to call the callback
1673      * @param {Object} arg An optional argument which is passed to the callback as its second parameter.
1674      */
1675     load : function(params, reader, callback, scope, arg){
1676         if(this.fireEvent("beforeload", this, params) !== false){
1677
1678             var p = Roo.urlEncode(Roo.apply(params, this.extraParams));
1679
1680             var url = this.url;
1681             url += (url.indexOf("?") != -1 ? "&" : "?") + p;
1682             if(this.nocache){
1683                 url += "&_dc=" + (new Date().getTime());
1684             }
1685             var transId = ++Roo.data.ScriptTagProxy.TRANS_ID;
1686             var trans = {
1687                 id : transId,
1688                 cb : "stcCallback"+transId,
1689                 scriptId : "stcScript"+transId,
1690                 params : params,
1691                 arg : arg,
1692                 url : url,
1693                 callback : callback,
1694                 scope : scope,
1695                 reader : reader
1696             };
1697             var conn = this;
1698
1699             window[trans.cb] = function(o){
1700                 conn.handleResponse(o, trans);
1701             };
1702
1703             url += String.format("&{0}={1}", this.callbackParam, trans.cb);
1704
1705             if(this.autoAbort !== false){
1706                 this.abort();
1707             }
1708
1709             trans.timeoutId = this.handleFailure.defer(this.timeout, this, [trans]);
1710
1711             var script = document.createElement("script");
1712             script.setAttribute("src", url);
1713             script.setAttribute("type", "text/javascript");
1714             script.setAttribute("id", trans.scriptId);
1715             this.head.appendChild(script);
1716
1717             this.trans = trans;
1718         }else{
1719             callback.call(scope||this, null, arg, false);
1720         }
1721     },
1722
1723     // private
1724     isLoading : function(){
1725         return this.trans ? true : false;
1726     },
1727
1728     /**
1729      * Abort the current server request.
1730      */
1731     abort : function(){
1732         if(this.isLoading()){
1733             this.destroyTrans(this.trans);
1734         }
1735     },
1736
1737     // private
1738     destroyTrans : function(trans, isLoaded){
1739         this.head.removeChild(document.getElementById(trans.scriptId));
1740         clearTimeout(trans.timeoutId);
1741         if(isLoaded){
1742             window[trans.cb] = undefined;
1743             try{
1744                 delete window[trans.cb];
1745             }catch(e){}
1746         }else{
1747             // if hasn't been loaded, wait for load to remove it to prevent script error
1748             window[trans.cb] = function(){
1749                 window[trans.cb] = undefined;
1750                 try{
1751                     delete window[trans.cb];
1752                 }catch(e){}
1753             };
1754         }
1755     },
1756
1757     // private
1758     handleResponse : function(o, trans){
1759         this.trans = false;
1760         this.destroyTrans(trans, true);
1761         var result;
1762         try {
1763             result = trans.reader.readRecords(o);
1764         }catch(e){
1765             this.fireEvent("loadexception", this, o, trans.arg, e);
1766             trans.callback.call(trans.scope||window, null, trans.arg, false);
1767             return;
1768         }
1769         this.fireEvent("load", this, o, trans.arg);
1770         trans.callback.call(trans.scope||window, result, trans.arg, true);
1771     },
1772
1773     // private
1774     handleFailure : function(trans){
1775         this.trans = false;
1776         this.destroyTrans(trans, false);
1777         this.fireEvent("loadexception", this, null, trans.arg);
1778         trans.callback.call(trans.scope||window, null, trans.arg, false);
1779     }
1780 });/*
1781  * Based on:
1782  * Ext JS Library 1.1.1
1783  * Copyright(c) 2006-2007, Ext JS, LLC.
1784  *
1785  * Originally Released Under LGPL - original licence link has changed is not relivant.
1786  *
1787  * Fork - LGPL
1788  * <script type="text/javascript">
1789  */
1790
1791 /**
1792  * @class Roo.data.JsonReader
1793  * @extends Roo.data.DataReader
1794  * Data reader class to create an Array of Roo.data.Record objects from a JSON response
1795  * based on mappings in a provided Roo.data.Record constructor.
1796  * 
1797  * The default behaviour of a store is to send ?_requestMeta=1, unless the class has recieved 'metaData' property
1798  * in the reply previously. 
1799  * 
1800  * <p>
1801  * Example code:
1802  * <pre><code>
1803 var RecordDef = Roo.data.Record.create([
1804     {name: 'name', mapping: 'name'},     // "mapping" property not needed if it's the same as "name"
1805     {name: 'occupation'}                 // This field will use "occupation" as the mapping.
1806 ]);
1807 var myReader = new Roo.data.JsonReader({
1808     totalProperty: "results",    // The property which contains the total dataset size (optional)
1809     root: "rows",                // The property which contains an Array of row objects
1810     id: "id"                     // The property within each row object that provides an ID for the record (optional)
1811 }, RecordDef);
1812 </code></pre>
1813  * <p>
1814  * This would consume a JSON file like this:
1815  * <pre><code>
1816 { 'results': 2, 'rows': [
1817     { 'id': 1, 'name': 'Bill', occupation: 'Gardener' },
1818     { 'id': 2, 'name': 'Ben', occupation: 'Horticulturalist' } ]
1819 }
1820 </code></pre>
1821  * @cfg {String} totalProperty Name of the property from which to retrieve the total number of records
1822  * in the dataset. This is only needed if the whole dataset is not passed in one go, but is being
1823  * paged from the remote server.
1824  * @cfg {String} successProperty Name of the property from which to retrieve the success attribute used by forms.
1825  * @cfg {String} root name of the property which contains the Array of row objects.
1826  * @cfg {String} id Name of the property within a row object that contains a record identifier value.
1827  * @cfg {Array} fields Array of field definition objects
1828  * @constructor
1829  * Create a new JsonReader
1830  * @param {Object} meta Metadata configuration options
1831  * @param {Object} recordType Either an Array of field definition objects,
1832  * or an {@link Roo.data.Record} object created using {@link Roo.data.Record#create}.
1833  */
1834 Roo.data.JsonReader = function(meta, recordType){
1835     
1836     meta = meta || {};
1837     // set some defaults:
1838     Roo.applyIf(meta, {
1839         totalProperty: 'total',
1840         successProperty : 'success',
1841         root : 'data',
1842         id : 'id'
1843     });
1844     
1845     Roo.data.JsonReader.superclass.constructor.call(this, meta, recordType||meta.fields);
1846 };
1847 Roo.extend(Roo.data.JsonReader, Roo.data.DataReader, {
1848     
1849     readerType : 'Json',
1850     
1851     /**
1852      * @prop {Boolean} metaFromRemote  - if the meta data was loaded from the remote source.
1853      * Used by Store query builder to append _requestMeta to params.
1854      * 
1855      */
1856     metaFromRemote : false,
1857     /**
1858      * This method is only used by a DataProxy which has retrieved data from a remote server.
1859      * @param {Object} response The XHR object which contains the JSON data in its responseText.
1860      * @return {Object} data A data block which is used by an Roo.data.Store object as
1861      * a cache of Roo.data.Records.
1862      */
1863     read : function(response){
1864         var json = response.responseText;
1865        
1866         var o = /* eval:var:o */ eval("("+json+")");
1867         if(!o) {
1868             throw {message: "JsonReader.read: Json object not found"};
1869         }
1870         
1871         if(o.metaData){
1872             
1873             delete this.ef;
1874             this.metaFromRemote = true;
1875             this.meta = o.metaData;
1876             this.recordType = Roo.data.Record.create(o.metaData.fields);
1877             this.onMetaChange(this.meta, this.recordType, o);
1878         }
1879         return this.readRecords(o);
1880     },
1881
1882     // private function a store will implement
1883     onMetaChange : function(meta, recordType, o){
1884
1885     },
1886
1887     /**
1888          * @ignore
1889          */
1890     simpleAccess: function(obj, subsc) {
1891         return obj[subsc];
1892     },
1893
1894         /**
1895          * @ignore
1896          */
1897     getJsonAccessor: function(){
1898         var re = /[\[\.]/;
1899         return function(expr) {
1900             try {
1901                 return(re.test(expr))
1902                     ? new Function("obj", "return obj." + expr)
1903                     : function(obj){
1904                         return obj[expr];
1905                     };
1906             } catch(e){}
1907             return Roo.emptyFn;
1908         };
1909     }(),
1910
1911     /**
1912      * Create a data block containing Roo.data.Records from an XML document.
1913      * @param {Object} o An object which contains an Array of row objects in the property specified
1914      * in the config as 'root, and optionally a property, specified in the config as 'totalProperty'
1915      * which contains the total size of the dataset.
1916      * @return {Object} data A data block which is used by an Roo.data.Store object as
1917      * a cache of Roo.data.Records.
1918      */
1919     readRecords : function(o){
1920         /**
1921          * After any data loads, the raw JSON data is available for further custom processing.
1922          * @type Object
1923          */
1924         this.o = o;
1925         var s = this.meta, Record = this.recordType,
1926             f = Record ? Record.prototype.fields : null, fi = f ? f.items : [], fl = f ? f.length : 0;
1927
1928 //      Generate extraction functions for the totalProperty, the root, the id, and for each field
1929         if (!this.ef) {
1930             if(s.totalProperty) {
1931                     this.getTotal = this.getJsonAccessor(s.totalProperty);
1932                 }
1933                 if(s.successProperty) {
1934                     this.getSuccess = this.getJsonAccessor(s.successProperty);
1935                 }
1936                 this.getRoot = s.root ? this.getJsonAccessor(s.root) : function(p){return p;};
1937                 if (s.id) {
1938                         var g = this.getJsonAccessor(s.id);
1939                         this.getId = function(rec) {
1940                                 var r = g(rec);  
1941                                 return (r === undefined || r === "") ? null : r;
1942                         };
1943                 } else {
1944                         this.getId = function(){return null;};
1945                 }
1946             this.ef = [];
1947             for(var jj = 0; jj < fl; jj++){
1948                 f = fi[jj];
1949                 var map = (f.mapping !== undefined && f.mapping !== null) ? f.mapping : f.name;
1950                 this.ef[jj] = this.getJsonAccessor(map);
1951             }
1952         }
1953
1954         var root = this.getRoot(o), c = root.length, totalRecords = c, success = true;
1955         if(s.totalProperty){
1956             var vt = parseInt(this.getTotal(o), 10);
1957             if(!isNaN(vt)){
1958                 totalRecords = vt;
1959             }
1960         }
1961         if(s.successProperty){
1962             var vs = this.getSuccess(o);
1963             if(vs === false || vs === 'false'){
1964                 success = false;
1965             }
1966         }
1967         var records = [];
1968         for(var i = 0; i < c; i++){
1969                 var n = root[i];
1970             var values = {};
1971             var id = this.getId(n);
1972             for(var j = 0; j < fl; j++){
1973                 f = fi[j];
1974             var v = this.ef[j](n);
1975             if (!f.convert) {
1976                 Roo.log('missing convert for ' + f.name);
1977                 Roo.log(f);
1978                 continue;
1979             }
1980             values[f.name] = f.convert((v !== undefined) ? v : f.defaultValue);
1981             }
1982             var record = new Record(values, id);
1983             record.json = n;
1984             records[i] = record;
1985         }
1986         return {
1987             raw : o,
1988             success : success,
1989             records : records,
1990             totalRecords : totalRecords
1991         };
1992     },
1993     // used when loading children.. @see loadDataFromChildren
1994     toLoadData: function(rec)
1995     {
1996         // expect rec just to be an array.. eg [a,b,c, [...] << cn ]
1997         var data = typeof(rec.data.cn) == 'undefined' ? [] : rec.data.cn;
1998         return { data : data, total : data.length };
1999         
2000     }
2001 });/*
2002  * Based on:
2003  * Ext JS Library 1.1.1
2004  * Copyright(c) 2006-2007, Ext JS, LLC.
2005  *
2006  * Originally Released Under LGPL - original licence link has changed is not relivant.
2007  *
2008  * Fork - LGPL
2009  * <script type="text/javascript">
2010  */
2011
2012 /**
2013  * @class Roo.data.XmlReader
2014  * @extends Roo.data.DataReader
2015  * Data reader class to create an Array of {@link Roo.data.Record} objects from an XML document
2016  * based on mappings in a provided Roo.data.Record constructor.<br><br>
2017  * <p>
2018  * <em>Note that in order for the browser to parse a returned XML document, the Content-Type
2019  * header in the HTTP response must be set to "text/xml".</em>
2020  * <p>
2021  * Example code:
2022  * <pre><code>
2023 var RecordDef = Roo.data.Record.create([
2024    {name: 'name', mapping: 'name'},     // "mapping" property not needed if it's the same as "name"
2025    {name: 'occupation'}                 // This field will use "occupation" as the mapping.
2026 ]);
2027 var myReader = new Roo.data.XmlReader({
2028    totalRecords: "results", // The element which contains the total dataset size (optional)
2029    record: "row",           // The repeated element which contains row information
2030    id: "id"                 // The element within the row that provides an ID for the record (optional)
2031 }, RecordDef);
2032 </code></pre>
2033  * <p>
2034  * This would consume an XML file like this:
2035  * <pre><code>
2036 &lt;?xml?>
2037 &lt;dataset>
2038  &lt;results>2&lt;/results>
2039  &lt;row>
2040    &lt;id>1&lt;/id>
2041    &lt;name>Bill&lt;/name>
2042    &lt;occupation>Gardener&lt;/occupation>
2043  &lt;/row>
2044  &lt;row>
2045    &lt;id>2&lt;/id>
2046    &lt;name>Ben&lt;/name>
2047    &lt;occupation>Horticulturalist&lt;/occupation>
2048  &lt;/row>
2049 &lt;/dataset>
2050 </code></pre>
2051  * @cfg {String} totalRecords The DomQuery path from which to retrieve the total number of records
2052  * in the dataset. This is only needed if the whole dataset is not passed in one go, but is being
2053  * paged from the remote server.
2054  * @cfg {String} record The DomQuery path to the repeated element which contains record information.
2055  * @cfg {String} success The DomQuery path to the success attribute used by forms.
2056  * @cfg {String} id The DomQuery path relative from the record element to the element that contains
2057  * a record identifier value.
2058  * @constructor
2059  * Create a new XmlReader
2060  * @param {Object} meta Metadata configuration options
2061  * @param {Mixed} recordType The definition of the data record type to produce.  This can be either a valid
2062  * Record subclass created with {@link Roo.data.Record#create}, or an array of objects with which to call
2063  * Roo.data.Record.create.  See the {@link Roo.data.Record} class for more details.
2064  */
2065 Roo.data.XmlReader = function(meta, recordType){
2066     meta = meta || {};
2067     Roo.data.XmlReader.superclass.constructor.call(this, meta, recordType||meta.fields);
2068 };
2069 Roo.extend(Roo.data.XmlReader, Roo.data.DataReader, {
2070     
2071     readerType : 'Xml',
2072     
2073     /**
2074      * This method is only used by a DataProxy which has retrieved data from a remote server.
2075          * @param {Object} response The XHR object which contains the parsed XML document.  The response is expected
2076          * to contain a method called 'responseXML' that returns an XML document object.
2077      * @return {Object} records A data block which is used by an {@link Roo.data.Store} as
2078      * a cache of Roo.data.Records.
2079      */
2080     read : function(response){
2081         var doc = response.responseXML;
2082         if(!doc) {
2083             throw {message: "XmlReader.read: XML Document not available"};
2084         }
2085         return this.readRecords(doc);
2086     },
2087
2088     /**
2089      * Create a data block containing Roo.data.Records from an XML document.
2090          * @param {Object} doc A parsed XML document.
2091      * @return {Object} records A data block which is used by an {@link Roo.data.Store} as
2092      * a cache of Roo.data.Records.
2093      */
2094     readRecords : function(doc){
2095         /**
2096          * After any data loads/reads, the raw XML Document is available for further custom processing.
2097          * @type XMLDocument
2098          */
2099         this.xmlData = doc;
2100         var root = doc.documentElement || doc;
2101         var q = Roo.DomQuery;
2102         var recordType = this.recordType, fields = recordType.prototype.fields;
2103         var sid = this.meta.id;
2104         var totalRecords = 0, success = true;
2105         if(this.meta.totalRecords){
2106             totalRecords = q.selectNumber(this.meta.totalRecords, root, 0);
2107         }
2108         
2109         if(this.meta.success){
2110             var sv = q.selectValue(this.meta.success, root, true);
2111             success = sv !== false && sv !== 'false';
2112         }
2113         var records = [];
2114         var ns = q.select(this.meta.record, root);
2115         for(var i = 0, len = ns.length; i < len; i++) {
2116                 var n = ns[i];
2117                 var values = {};
2118                 var id = sid ? q.selectValue(sid, n) : undefined;
2119                 for(var j = 0, jlen = fields.length; j < jlen; j++){
2120                     var f = fields.items[j];
2121                 var v = q.selectValue(f.mapping || f.name, n, f.defaultValue);
2122                     v = f.convert(v);
2123                     values[f.name] = v;
2124                 }
2125                 var record = new recordType(values, id);
2126                 record.node = n;
2127                 records[records.length] = record;
2128             }
2129
2130             return {
2131                 success : success,
2132                 records : records,
2133                 totalRecords : totalRecords || records.length
2134             };
2135     }
2136 });/*
2137  * Based on:
2138  * Ext JS Library 1.1.1
2139  * Copyright(c) 2006-2007, Ext JS, LLC.
2140  *
2141  * Originally Released Under LGPL - original licence link has changed is not relivant.
2142  *
2143  * Fork - LGPL
2144  * <script type="text/javascript">
2145  */
2146
2147 /**
2148  * @class Roo.data.ArrayReader
2149  * @extends Roo.data.DataReader
2150  * Data reader class to create an Array of Roo.data.Record objects from an Array.
2151  * Each element of that Array represents a row of data fields. The
2152  * fields are pulled into a Record object using as a subscript, the <em>mapping</em> property
2153  * of the field definition if it exists, or the field's ordinal position in the definition.<br>
2154  * <p>
2155  * Example code:.
2156  * <pre><code>
2157 var RecordDef = Roo.data.Record.create([
2158     {name: 'name', mapping: 1},         // "mapping" only needed if an "id" field is present which
2159     {name: 'occupation', mapping: 2}    // precludes using the ordinal position as the index.
2160 ]);
2161 var myReader = new Roo.data.ArrayReader({
2162     id: 0                     // The subscript within row Array that provides an ID for the Record (optional)
2163 }, RecordDef);
2164 </code></pre>
2165  * <p>
2166  * This would consume an Array like this:
2167  * <pre><code>
2168 [ [1, 'Bill', 'Gardener'], [2, 'Ben', 'Horticulturalist'] ]
2169   </code></pre>
2170  
2171  * @constructor
2172  * Create a new JsonReader
2173  * @param {Object} meta Metadata configuration options.
2174  * @param {Object|Array} recordType Either an Array of field definition objects
2175  * 
2176  * @cfg {Array} fields Array of field definition objects
2177  * @cfg {String} id Name of the property within a row object that contains a record identifier value.
2178  * as specified to {@link Roo.data.Record#create},
2179  * or an {@link Roo.data.Record} object
2180  *
2181  * 
2182  * created using {@link Roo.data.Record#create}.
2183  */
2184 Roo.data.ArrayReader = function(meta, recordType)
2185 {    
2186     Roo.data.ArrayReader.superclass.constructor.call(this, meta, recordType||meta.fields);
2187 };
2188
2189 Roo.extend(Roo.data.ArrayReader, Roo.data.JsonReader, {
2190     
2191       /**
2192      * Create a data block containing Roo.data.Records from an XML document.
2193      * @param {Object} o An Array of row objects which represents the dataset.
2194      * @return {Object} A data block which is used by an {@link Roo.data.Store} object as
2195      * a cache of Roo.data.Records.
2196      */
2197     readRecords : function(o)
2198     {
2199         var sid = this.meta ? this.meta.id : null;
2200         var recordType = this.recordType, fields = recordType.prototype.fields;
2201         var records = [];
2202         var root = o;
2203         for(var i = 0; i < root.length; i++){
2204                 var n = root[i];
2205             var values = {};
2206             var id = ((sid || sid === 0) && n[sid] !== undefined && n[sid] !== "" ? n[sid] : null);
2207             for(var j = 0, jlen = fields.length; j < jlen; j++){
2208                 var f = fields.items[j];
2209                 var k = f.mapping !== undefined && f.mapping !== null ? f.mapping : j;
2210                 var v = n[k] !== undefined ? n[k] : f.defaultValue;
2211                 v = f.convert(v);
2212                 values[f.name] = v;
2213             }
2214             var record = new recordType(values, id);
2215             record.json = n;
2216             records[records.length] = record;
2217         }
2218         return {
2219             records : records,
2220             totalRecords : records.length
2221         };
2222     },
2223     // used when loading children.. @see loadDataFromChildren
2224     toLoadData: function(rec)
2225     {
2226         // expect rec just to be an array.. eg [a,b,c, [...] << cn ]
2227         return typeof(rec.data.cn) == 'undefined' ? [] : rec.data.cn;
2228         
2229     }
2230     
2231     
2232 });/*
2233  * Based on:
2234  * Ext JS Library 1.1.1
2235  * Copyright(c) 2006-2007, Ext JS, LLC.
2236  *
2237  * Originally Released Under LGPL - original licence link has changed is not relivant.
2238  *
2239  * Fork - LGPL
2240  * <script type="text/javascript">
2241  */
2242
2243
2244 /**
2245  * @class Roo.data.Tree
2246  * @extends Roo.util.Observable
2247  * Represents a tree data structure and bubbles all the events for its nodes. The nodes
2248  * in the tree have most standard DOM functionality.
2249  * @constructor
2250  * @param {Node} root (optional) The root node
2251  */
2252 Roo.data.Tree = function(root){
2253    this.nodeHash = {};
2254    /**
2255     * The root node for this tree
2256     * @type Node
2257     */
2258    this.root = null;
2259    if(root){
2260        this.setRootNode(root);
2261    }
2262    this.addEvents({
2263        /**
2264         * @event append
2265         * Fires when a new child node is appended to a node in this tree.
2266         * @param {Tree} tree The owner tree
2267         * @param {Node} parent The parent node
2268         * @param {Node} node The newly appended node
2269         * @param {Number} index The index of the newly appended node
2270         */
2271        "append" : true,
2272        /**
2273         * @event remove
2274         * Fires when a child node is removed from a node in this tree.
2275         * @param {Tree} tree The owner tree
2276         * @param {Node} parent The parent node
2277         * @param {Node} node The child node removed
2278         */
2279        "remove" : true,
2280        /**
2281         * @event move
2282         * Fires when a node is moved to a new location in the tree
2283         * @param {Tree} tree The owner tree
2284         * @param {Node} node The node moved
2285         * @param {Node} oldParent The old parent of this node
2286         * @param {Node} newParent The new parent of this node
2287         * @param {Number} index The index it was moved to
2288         */
2289        "move" : true,
2290        /**
2291         * @event insert
2292         * Fires when a new child node is inserted in a node in this tree.
2293         * @param {Tree} tree The owner tree
2294         * @param {Node} parent The parent node
2295         * @param {Node} node The child node inserted
2296         * @param {Node} refNode The child node the node was inserted before
2297         */
2298        "insert" : true,
2299        /**
2300         * @event beforeappend
2301         * Fires before a new child is appended to a node in this tree, return false to cancel the append.
2302         * @param {Tree} tree The owner tree
2303         * @param {Node} parent The parent node
2304         * @param {Node} node The child node to be appended
2305         */
2306        "beforeappend" : true,
2307        /**
2308         * @event beforeremove
2309         * Fires before a child is removed from a node in this tree, return false to cancel the remove.
2310         * @param {Tree} tree The owner tree
2311         * @param {Node} parent The parent node
2312         * @param {Node} node The child node to be removed
2313         */
2314        "beforeremove" : true,
2315        /**
2316         * @event beforemove
2317         * Fires before a node is moved to a new location in the tree. Return false to cancel the move.
2318         * @param {Tree} tree The owner tree
2319         * @param {Node} node The node being moved
2320         * @param {Node} oldParent The parent of the node
2321         * @param {Node} newParent The new parent the node is moving to
2322         * @param {Number} index The index it is being moved to
2323         */
2324        "beforemove" : true,
2325        /**
2326         * @event beforeinsert
2327         * Fires before a new child is inserted in a node in this tree, return false to cancel the insert.
2328         * @param {Tree} tree The owner tree
2329         * @param {Node} parent The parent node
2330         * @param {Node} node The child node to be inserted
2331         * @param {Node} refNode The child node the node is being inserted before
2332         */
2333        "beforeinsert" : true
2334    });
2335
2336     Roo.data.Tree.superclass.constructor.call(this);
2337 };
2338
2339 Roo.extend(Roo.data.Tree, Roo.util.Observable, {
2340     pathSeparator: "/",
2341
2342     proxyNodeEvent : function(){
2343         return this.fireEvent.apply(this, arguments);
2344     },
2345
2346     /**
2347      * Returns the root node for this tree.
2348      * @return {Node}
2349      */
2350     getRootNode : function(){
2351         return this.root;
2352     },
2353
2354     /**
2355      * Sets the root node for this tree.
2356      * @param {Node} node
2357      * @return {Node}
2358      */
2359     setRootNode : function(node){
2360         this.root = node;
2361         node.ownerTree = this;
2362         node.isRoot = true;
2363         this.registerNode(node);
2364         return node;
2365     },
2366
2367     /**
2368      * Gets a node in this tree by its id.
2369      * @param {String} id
2370      * @return {Node}
2371      */
2372     getNodeById : function(id){
2373         return this.nodeHash[id];
2374     },
2375
2376     registerNode : function(node){
2377         this.nodeHash[node.id] = node;
2378     },
2379
2380     unregisterNode : function(node){
2381         delete this.nodeHash[node.id];
2382     },
2383
2384     toString : function(){
2385         return "[Tree"+(this.id?" "+this.id:"")+"]";
2386     }
2387 });
2388
2389 /**
2390  * @class Roo.data.Node
2391  * @extends Roo.util.Observable
2392  * @cfg {Boolean} leaf true if this node is a leaf and does not have children
2393  * @cfg {String} id The id for this node. If one is not specified, one is generated.
2394  * @constructor
2395  * @param {Object} attributes The attributes/config for the node
2396  */
2397 Roo.data.Node = function(attributes){
2398     /**
2399      * The attributes supplied for the node. You can use this property to access any custom attributes you supplied.
2400      * @type {Object}
2401      */
2402     this.attributes = attributes || {};
2403     this.leaf = this.attributes.leaf;
2404     /**
2405      * The node id. @type String
2406      */
2407     this.id = this.attributes.id;
2408     if(!this.id){
2409         this.id = Roo.id(null, "ynode-");
2410         this.attributes.id = this.id;
2411     }
2412      
2413     
2414     /**
2415      * All child nodes of this node. @type Array
2416      */
2417     this.childNodes = [];
2418     if(!this.childNodes.indexOf){ // indexOf is a must
2419         this.childNodes.indexOf = function(o){
2420             for(var i = 0, len = this.length; i < len; i++){
2421                 if(this[i] == o) {
2422                     return i;
2423                 }
2424             }
2425             return -1;
2426         };
2427     }
2428     /**
2429      * The parent node for this node. @type Node
2430      */
2431     this.parentNode = null;
2432     /**
2433      * The first direct child node of this node, or null if this node has no child nodes. @type Node
2434      */
2435     this.firstChild = null;
2436     /**
2437      * The last direct child node of this node, or null if this node has no child nodes. @type Node
2438      */
2439     this.lastChild = null;
2440     /**
2441      * The node immediately preceding this node in the tree, or null if there is no sibling node. @type Node
2442      */
2443     this.previousSibling = null;
2444     /**
2445      * The node immediately following this node in the tree, or null if there is no sibling node. @type Node
2446      */
2447     this.nextSibling = null;
2448
2449     this.addEvents({
2450        /**
2451         * @event append
2452         * Fires when a new child node is appended
2453         * @param {Tree} tree The owner tree
2454         * @param {Node} this This node
2455         * @param {Node} node The newly appended node
2456         * @param {Number} index The index of the newly appended node
2457         */
2458        "append" : true,
2459        /**
2460         * @event remove
2461         * Fires when a child node is removed
2462         * @param {Tree} tree The owner tree
2463         * @param {Node} this This node
2464         * @param {Node} node The removed node
2465         */
2466        "remove" : true,
2467        /**
2468         * @event move
2469         * Fires when this node is moved to a new location in the tree
2470         * @param {Tree} tree The owner tree
2471         * @param {Node} this This node
2472         * @param {Node} oldParent The old parent of this node
2473         * @param {Node} newParent The new parent of this node
2474         * @param {Number} index The index it was moved to
2475         */
2476        "move" : true,
2477        /**
2478         * @event insert
2479         * Fires when a new child node is inserted.
2480         * @param {Tree} tree The owner tree
2481         * @param {Node} this This node
2482         * @param {Node} node The child node inserted
2483         * @param {Node} refNode The child node the node was inserted before
2484         */
2485        "insert" : true,
2486        /**
2487         * @event beforeappend
2488         * Fires before a new child is appended, return false to cancel the append.
2489         * @param {Tree} tree The owner tree
2490         * @param {Node} this This node
2491         * @param {Node} node The child node to be appended
2492         */
2493        "beforeappend" : true,
2494        /**
2495         * @event beforeremove
2496         * Fires before a child is removed, return false to cancel the remove.
2497         * @param {Tree} tree The owner tree
2498         * @param {Node} this This node
2499         * @param {Node} node The child node to be removed
2500         */
2501        "beforeremove" : true,
2502        /**
2503         * @event beforemove
2504         * Fires before this node is moved to a new location in the tree. Return false to cancel the move.
2505         * @param {Tree} tree The owner tree
2506         * @param {Node} this This node
2507         * @param {Node} oldParent The parent of this node
2508         * @param {Node} newParent The new parent this node is moving to
2509         * @param {Number} index The index it is being moved to
2510         */
2511        "beforemove" : true,
2512        /**
2513         * @event beforeinsert
2514         * Fires before a new child is inserted, return false to cancel the insert.
2515         * @param {Tree} tree The owner tree
2516         * @param {Node} this This node
2517         * @param {Node} node The child node to be inserted
2518         * @param {Node} refNode The child node the node is being inserted before
2519         */
2520        "beforeinsert" : true
2521    });
2522     this.listeners = this.attributes.listeners;
2523     Roo.data.Node.superclass.constructor.call(this);
2524 };
2525
2526 Roo.extend(Roo.data.Node, Roo.util.Observable, {
2527     fireEvent : function(evtName){
2528         // first do standard event for this node
2529         if(Roo.data.Node.superclass.fireEvent.apply(this, arguments) === false){
2530             return false;
2531         }
2532         // then bubble it up to the tree if the event wasn't cancelled
2533         var ot = this.getOwnerTree();
2534         if(ot){
2535             if(ot.proxyNodeEvent.apply(ot, arguments) === false){
2536                 return false;
2537             }
2538         }
2539         return true;
2540     },
2541
2542     /**
2543      * Returns true if this node is a leaf
2544      * @return {Boolean}
2545      */
2546     isLeaf : function(){
2547         return this.leaf === true;
2548     },
2549
2550     // private
2551     setFirstChild : function(node){
2552         this.firstChild = node;
2553     },
2554
2555     //private
2556     setLastChild : function(node){
2557         this.lastChild = node;
2558     },
2559
2560
2561     /**
2562      * Returns true if this node is the last child of its parent
2563      * @return {Boolean}
2564      */
2565     isLast : function(){
2566        return (!this.parentNode ? true : this.parentNode.lastChild == this);
2567     },
2568
2569     /**
2570      * Returns true if this node is the first child of its parent
2571      * @return {Boolean}
2572      */
2573     isFirst : function(){
2574        return (!this.parentNode ? true : this.parentNode.firstChild == this);
2575     },
2576
2577     hasChildNodes : function(){
2578         return !this.isLeaf() && this.childNodes.length > 0;
2579     },
2580
2581     /**
2582      * Insert node(s) as the last child node of this node.
2583      * @param {Node/Array} node The node or Array of nodes to append
2584      * @return {Node} The appended node if single append, or null if an array was passed
2585      */
2586     appendChild : function(node){
2587         var multi = false;
2588         if(node instanceof Array){
2589             multi = node;
2590         }else if(arguments.length > 1){
2591             multi = arguments;
2592         }
2593         
2594         // if passed an array or multiple args do them one by one
2595         if(multi){
2596             for(var i = 0, len = multi.length; i < len; i++) {
2597                 this.appendChild(multi[i]);
2598             }
2599         }else{
2600             if(this.fireEvent("beforeappend", this.ownerTree, this, node) === false){
2601                 return false;
2602             }
2603             var index = this.childNodes.length;
2604             var oldParent = node.parentNode;
2605             // it's a move, make sure we move it cleanly
2606             if(oldParent){
2607                 if(node.fireEvent("beforemove", node.getOwnerTree(), node, oldParent, this, index) === false){
2608                     return false;
2609                 }
2610                 oldParent.removeChild(node);
2611             }
2612             
2613             index = this.childNodes.length;
2614             if(index == 0){
2615                 this.setFirstChild(node);
2616             }
2617             this.childNodes.push(node);
2618             node.parentNode = this;
2619             var ps = this.childNodes[index-1];
2620             if(ps){
2621                 node.previousSibling = ps;
2622                 ps.nextSibling = node;
2623             }else{
2624                 node.previousSibling = null;
2625             }
2626             node.nextSibling = null;
2627             this.setLastChild(node);
2628             node.setOwnerTree(this.getOwnerTree());
2629             this.fireEvent("append", this.ownerTree, this, node, index);
2630             if(this.ownerTree) {
2631                 this.ownerTree.fireEvent("appendnode", this, node, index);
2632             }
2633             if(oldParent){
2634                 node.fireEvent("move", this.ownerTree, node, oldParent, this, index);
2635             }
2636             return node;
2637         }
2638     },
2639
2640     /**
2641      * Removes a child node from this node.
2642      * @param {Node} node The node to remove
2643      * @return {Node} The removed node
2644      */
2645     removeChild : function(node){
2646         var index = this.childNodes.indexOf(node);
2647         if(index == -1){
2648             return false;
2649         }
2650         if(this.fireEvent("beforeremove", this.ownerTree, this, node) === false){
2651             return false;
2652         }
2653
2654         // remove it from childNodes collection
2655         this.childNodes.splice(index, 1);
2656
2657         // update siblings
2658         if(node.previousSibling){
2659             node.previousSibling.nextSibling = node.nextSibling;
2660         }
2661         if(node.nextSibling){
2662             node.nextSibling.previousSibling = node.previousSibling;
2663         }
2664
2665         // update child refs
2666         if(this.firstChild == node){
2667             this.setFirstChild(node.nextSibling);
2668         }
2669         if(this.lastChild == node){
2670             this.setLastChild(node.previousSibling);
2671         }
2672
2673         node.setOwnerTree(null);
2674         // clear any references from the node
2675         node.parentNode = null;
2676         node.previousSibling = null;
2677         node.nextSibling = null;
2678         this.fireEvent("remove", this.ownerTree, this, node);
2679         return node;
2680     },
2681
2682     /**
2683      * Inserts the first node before the second node in this nodes childNodes collection.
2684      * @param {Node} node The node to insert
2685      * @param {Node} refNode The node to insert before (if null the node is appended)
2686      * @return {Node} The inserted node
2687      */
2688     insertBefore : function(node, refNode){
2689         if(!refNode){ // like standard Dom, refNode can be null for append
2690             return this.appendChild(node);
2691         }
2692         // nothing to do
2693         if(node == refNode){
2694             return false;
2695         }
2696
2697         if(this.fireEvent("beforeinsert", this.ownerTree, this, node, refNode) === false){
2698             return false;
2699         }
2700         var index = this.childNodes.indexOf(refNode);
2701         var oldParent = node.parentNode;
2702         var refIndex = index;
2703
2704         // when moving internally, indexes will change after remove
2705         if(oldParent == this && this.childNodes.indexOf(node) < index){
2706             refIndex--;
2707         }
2708
2709         // it's a move, make sure we move it cleanly
2710         if(oldParent){
2711             if(node.fireEvent("beforemove", node.getOwnerTree(), node, oldParent, this, index, refNode) === false){
2712                 return false;
2713             }
2714             oldParent.removeChild(node);
2715         }
2716         if(refIndex == 0){
2717             this.setFirstChild(node);
2718         }
2719         this.childNodes.splice(refIndex, 0, node);
2720         node.parentNode = this;
2721         var ps = this.childNodes[refIndex-1];
2722         if(ps){
2723             node.previousSibling = ps;
2724             ps.nextSibling = node;
2725         }else{
2726             node.previousSibling = null;
2727         }
2728         node.nextSibling = refNode;
2729         refNode.previousSibling = node;
2730         node.setOwnerTree(this.getOwnerTree());
2731         this.fireEvent("insert", this.ownerTree, this, node, refNode);
2732         if(oldParent){
2733             node.fireEvent("move", this.ownerTree, node, oldParent, this, refIndex, refNode);
2734         }
2735         return node;
2736     },
2737
2738     /**
2739      * Returns the child node at the specified index.
2740      * @param {Number} index
2741      * @return {Node}
2742      */
2743     item : function(index){
2744         return this.childNodes[index];
2745     },
2746
2747     /**
2748      * Replaces one child node in this node with another.
2749      * @param {Node} newChild The replacement node
2750      * @param {Node} oldChild The node to replace
2751      * @return {Node} The replaced node
2752      */
2753     replaceChild : function(newChild, oldChild){
2754         this.insertBefore(newChild, oldChild);
2755         this.removeChild(oldChild);
2756         return oldChild;
2757     },
2758
2759     /**
2760      * Returns the index of a child node
2761      * @param {Node} node
2762      * @return {Number} The index of the node or -1 if it was not found
2763      */
2764     indexOf : function(child){
2765         return this.childNodes.indexOf(child);
2766     },
2767
2768     /**
2769      * Returns the tree this node is in.
2770      * @return {Tree}
2771      */
2772     getOwnerTree : function(){
2773         // if it doesn't have one, look for one
2774         if(!this.ownerTree){
2775             var p = this;
2776             while(p){
2777                 if(p.ownerTree){
2778                     this.ownerTree = p.ownerTree;
2779                     break;
2780                 }
2781                 p = p.parentNode;
2782             }
2783         }
2784         return this.ownerTree;
2785     },
2786
2787     /**
2788      * Returns depth of this node (the root node has a depth of 0)
2789      * @return {Number}
2790      */
2791     getDepth : function(){
2792         var depth = 0;
2793         var p = this;
2794         while(p.parentNode){
2795             ++depth;
2796             p = p.parentNode;
2797         }
2798         return depth;
2799     },
2800
2801     // private
2802     setOwnerTree : function(tree){
2803         // if it's move, we need to update everyone
2804         if(tree != this.ownerTree){
2805             if(this.ownerTree){
2806                 this.ownerTree.unregisterNode(this);
2807             }
2808             this.ownerTree = tree;
2809             var cs = this.childNodes;
2810             for(var i = 0, len = cs.length; i < len; i++) {
2811                 cs[i].setOwnerTree(tree);
2812             }
2813             if(tree){
2814                 tree.registerNode(this);
2815             }
2816         }
2817     },
2818
2819     /**
2820      * Returns the path for this node. The path can be used to expand or select this node programmatically.
2821      * @param {String} attr (optional) The attr to use for the path (defaults to the node's id)
2822      * @return {String} The path
2823      */
2824     getPath : function(attr){
2825         attr = attr || "id";
2826         var p = this.parentNode;
2827         var b = [this.attributes[attr]];
2828         while(p){
2829             b.unshift(p.attributes[attr]);
2830             p = p.parentNode;
2831         }
2832         var sep = this.getOwnerTree().pathSeparator;
2833         return sep + b.join(sep);
2834     },
2835
2836     /**
2837      * Bubbles up the tree from this node, calling the specified function with each node. The scope (<i>this</i>) of
2838      * function call will be the scope provided or the current node. The arguments to the function
2839      * will be the args provided or the current node. If the function returns false at any point,
2840      * the bubble is stopped.
2841      * @param {Function} fn The function to call
2842      * @param {Object} scope (optional) The scope of the function (defaults to current node)
2843      * @param {Array} args (optional) The args to call the function with (default to passing the current node)
2844      */
2845     bubble : function(fn, scope, args){
2846         var p = this;
2847         while(p){
2848             if(fn.call(scope || p, args || p) === false){
2849                 break;
2850             }
2851             p = p.parentNode;
2852         }
2853     },
2854
2855     /**
2856      * Cascades down the tree from this node, calling the specified function with each node. The scope (<i>this</i>) of
2857      * function call will be the scope provided or the current node. The arguments to the function
2858      * will be the args provided or the current node. If the function returns false at any point,
2859      * the cascade is stopped on that branch.
2860      * @param {Function} fn The function to call
2861      * @param {Object} scope (optional) The scope of the function (defaults to current node)
2862      * @param {Array} args (optional) The args to call the function with (default to passing the current node)
2863      */
2864     cascade : function(fn, scope, args){
2865         if(fn.call(scope || this, args || this) !== false){
2866             var cs = this.childNodes;
2867             for(var i = 0, len = cs.length; i < len; i++) {
2868                 cs[i].cascade(fn, scope, args);
2869             }
2870         }
2871     },
2872
2873     /**
2874      * Interates the child nodes of this node, calling the specified function with each node. The scope (<i>this</i>) of
2875      * function call will be the scope provided or the current node. The arguments to the function
2876      * will be the args provided or the current node. If the function returns false at any point,
2877      * the iteration stops.
2878      * @param {Function} fn The function to call
2879      * @param {Object} scope (optional) The scope of the function (defaults to current node)
2880      * @param {Array} args (optional) The args to call the function with (default to passing the current node)
2881      */
2882     eachChild : function(fn, scope, args){
2883         var cs = this.childNodes;
2884         for(var i = 0, len = cs.length; i < len; i++) {
2885                 if(fn.call(scope || this, args || cs[i]) === false){
2886                     break;
2887                 }
2888         }
2889     },
2890
2891     /**
2892      * Finds the first child that has the attribute with the specified value.
2893      * @param {String} attribute The attribute name
2894      * @param {Mixed} value The value to search for
2895      * @return {Node} The found child or null if none was found
2896      */
2897     findChild : function(attribute, value){
2898         var cs = this.childNodes;
2899         for(var i = 0, len = cs.length; i < len; i++) {
2900                 if(cs[i].attributes[attribute] == value){
2901                     return cs[i];
2902                 }
2903         }
2904         return null;
2905     },
2906
2907     /**
2908      * Finds the first child by a custom function. The child matches if the function passed
2909      * returns true.
2910      * @param {Function} fn
2911      * @param {Object} scope (optional)
2912      * @return {Node} The found child or null if none was found
2913      */
2914     findChildBy : function(fn, scope){
2915         var cs = this.childNodes;
2916         for(var i = 0, len = cs.length; i < len; i++) {
2917                 if(fn.call(scope||cs[i], cs[i]) === true){
2918                     return cs[i];
2919                 }
2920         }
2921         return null;
2922     },
2923
2924     /**
2925      * Sorts this nodes children using the supplied sort function
2926      * @param {Function} fn
2927      * @param {Object} scope (optional)
2928      */
2929     sort : function(fn, scope){
2930         var cs = this.childNodes;
2931         var len = cs.length;
2932         if(len > 0){
2933             var sortFn = scope ? function(){fn.apply(scope, arguments);} : fn;
2934             cs.sort(sortFn);
2935             for(var i = 0; i < len; i++){
2936                 var n = cs[i];
2937                 n.previousSibling = cs[i-1];
2938                 n.nextSibling = cs[i+1];
2939                 if(i == 0){
2940                     this.setFirstChild(n);
2941                 }
2942                 if(i == len-1){
2943                     this.setLastChild(n);
2944                 }
2945             }
2946         }
2947     },
2948
2949     /**
2950      * Returns true if this node is an ancestor (at any point) of the passed node.
2951      * @param {Node} node
2952      * @return {Boolean}
2953      */
2954     contains : function(node){
2955         return node.isAncestor(this);
2956     },
2957
2958     /**
2959      * Returns true if the passed node is an ancestor (at any point) of this node.
2960      * @param {Node} node
2961      * @return {Boolean}
2962      */
2963     isAncestor : function(node){
2964         var p = this.parentNode;
2965         while(p){
2966             if(p == node){
2967                 return true;
2968             }
2969             p = p.parentNode;
2970         }
2971         return false;
2972     },
2973
2974     toString : function(){
2975         return "[Node"+(this.id?" "+this.id:"")+"]";
2976     }
2977 });/*
2978  * Based on:
2979  * Ext JS Library 1.1.1
2980  * Copyright(c) 2006-2007, Ext JS, LLC.
2981  *
2982  * Originally Released Under LGPL - original licence link has changed is not relivant.
2983  *
2984  * Fork - LGPL
2985  * <script type="text/javascript">
2986  */
2987  (function(){ 
2988 /**
2989  * @class Roo.Layer
2990  * @extends Roo.Element
2991  * An extended {@link Roo.Element} object that supports a shadow and shim, constrain to viewport and
2992  * automatic maintaining of shadow/shim positions.
2993  * @cfg {Boolean} shim False to disable the iframe shim in browsers which need one (defaults to true)
2994  * @cfg {String/Boolean} shadow True to create a shadow element with default class "x-layer-shadow", or
2995  * you can pass a string with a CSS class name. False turns off the shadow.
2996  * @cfg {Object} dh DomHelper object config to create element with (defaults to {tag: "div", cls: "x-layer"}).
2997  * @cfg {Boolean} constrain False to disable constrain to viewport (defaults to true)
2998  * @cfg {String} cls CSS class to add to the element
2999  * @cfg {Number} zindex Starting z-index (defaults to 11000)
3000  * @cfg {Number} shadowOffset Number of pixels to offset the shadow (defaults to 3)
3001  * @constructor
3002  * @param {Object} config An object with config options.
3003  * @param {String/HTMLElement} existingEl (optional) Uses an existing DOM element. If the element is not found it creates it.
3004  */
3005
3006 Roo.Layer = function(config, existingEl){
3007     config = config || {};
3008     var dh = Roo.DomHelper;
3009     var cp = config.parentEl, pel = cp ? Roo.getDom(cp) : document.body;
3010     if(existingEl){
3011         this.dom = Roo.getDom(existingEl);
3012     }
3013     if(!this.dom){
3014         var o = config.dh || {tag: "div", cls: "x-layer"};
3015         this.dom = dh.append(pel, o);
3016     }
3017     if(config.cls){
3018         this.addClass(config.cls);
3019     }
3020     this.constrain = config.constrain !== false;
3021     this.visibilityMode = Roo.Element.VISIBILITY;
3022     if(config.id){
3023         this.id = this.dom.id = config.id;
3024     }else{
3025         this.id = Roo.id(this.dom);
3026     }
3027     this.zindex = config.zindex || this.getZIndex();
3028     this.position("absolute", this.zindex);
3029     if(config.shadow){
3030         this.shadowOffset = config.shadowOffset || 4;
3031         this.shadow = new Roo.Shadow({
3032             offset : this.shadowOffset,
3033             mode : config.shadow
3034         });
3035     }else{
3036         this.shadowOffset = 0;
3037     }
3038     this.useShim = config.shim !== false && Roo.useShims;
3039     this.useDisplay = config.useDisplay;
3040     this.hide();
3041 };
3042
3043 var supr = Roo.Element.prototype;
3044
3045 // shims are shared among layer to keep from having 100 iframes
3046 var shims = [];
3047
3048 Roo.extend(Roo.Layer, Roo.Element, {
3049
3050     getZIndex : function(){
3051         return this.zindex || parseInt(this.getStyle("z-index"), 10) || 11000;
3052     },
3053
3054     getShim : function(){
3055         if(!this.useShim){
3056             return null;
3057         }
3058         if(this.shim){
3059             return this.shim;
3060         }
3061         var shim = shims.shift();
3062         if(!shim){
3063             shim = this.createShim();
3064             shim.enableDisplayMode('block');
3065             shim.dom.style.display = 'none';
3066             shim.dom.style.visibility = 'visible';
3067         }
3068         var pn = this.dom.parentNode;
3069         if(shim.dom.parentNode != pn){
3070             pn.insertBefore(shim.dom, this.dom);
3071         }
3072         shim.setStyle('z-index', this.getZIndex()-2);
3073         this.shim = shim;
3074         return shim;
3075     },
3076
3077     hideShim : function(){
3078         if(this.shim){
3079             this.shim.setDisplayed(false);
3080             shims.push(this.shim);
3081             delete this.shim;
3082         }
3083     },
3084
3085     disableShadow : function(){
3086         if(this.shadow){
3087             this.shadowDisabled = true;
3088             this.shadow.hide();
3089             this.lastShadowOffset = this.shadowOffset;
3090             this.shadowOffset = 0;
3091         }
3092     },
3093
3094     enableShadow : function(show){
3095         if(this.shadow){
3096             this.shadowDisabled = false;
3097             this.shadowOffset = this.lastShadowOffset;
3098             delete this.lastShadowOffset;
3099             if(show){
3100                 this.sync(true);
3101             }
3102         }
3103     },
3104
3105     // private
3106     // this code can execute repeatedly in milliseconds (i.e. during a drag) so
3107     // code size was sacrificed for effeciency (e.g. no getBox/setBox, no XY calls)
3108     sync : function(doShow){
3109         var sw = this.shadow;
3110         if(!this.updating && this.isVisible() && (sw || this.useShim)){
3111             var sh = this.getShim();
3112
3113             var w = this.getWidth(),
3114                 h = this.getHeight();
3115
3116             var l = this.getLeft(true),
3117                 t = this.getTop(true);
3118
3119             if(sw && !this.shadowDisabled){
3120                 if(doShow && !sw.isVisible()){
3121                     sw.show(this);
3122                 }else{
3123                     sw.realign(l, t, w, h);
3124                 }
3125                 if(sh){
3126                     if(doShow){
3127                        sh.show();
3128                     }
3129                     // fit the shim behind the shadow, so it is shimmed too
3130                     var a = sw.adjusts, s = sh.dom.style;
3131                     s.left = (Math.min(l, l+a.l))+"px";
3132                     s.top = (Math.min(t, t+a.t))+"px";
3133                     s.width = (w+a.w)+"px";
3134                     s.height = (h+a.h)+"px";
3135                 }
3136             }else if(sh){
3137                 if(doShow){
3138                    sh.show();
3139                 }
3140                 sh.setSize(w, h);
3141                 sh.setLeftTop(l, t);
3142             }
3143             
3144         }
3145     },
3146
3147     // private
3148     destroy : function(){
3149         this.hideShim();
3150         if(this.shadow){
3151             this.shadow.hide();
3152         }
3153         this.removeAllListeners();
3154         var pn = this.dom.parentNode;
3155         if(pn){
3156             pn.removeChild(this.dom);
3157         }
3158         Roo.Element.uncache(this.id);
3159     },
3160
3161     remove : function(){
3162         this.destroy();
3163     },
3164
3165     // private
3166     beginUpdate : function(){
3167         this.updating = true;
3168     },
3169
3170     // private
3171     endUpdate : function(){
3172         this.updating = false;
3173         this.sync(true);
3174     },
3175
3176     // private
3177     hideUnders : function(negOffset){
3178         if(this.shadow){
3179             this.shadow.hide();
3180         }
3181         this.hideShim();
3182     },
3183
3184     // private
3185     constrainXY : function(){
3186         if(this.constrain){
3187             var vw = Roo.lib.Dom.getViewWidth(),
3188                 vh = Roo.lib.Dom.getViewHeight();
3189             var s = Roo.get(document).getScroll();
3190
3191             var xy = this.getXY();
3192             var x = xy[0], y = xy[1];   
3193             var w = this.dom.offsetWidth+this.shadowOffset, h = this.dom.offsetHeight+this.shadowOffset;
3194             // only move it if it needs it
3195             var moved = false;
3196             // first validate right/bottom
3197             if((x + w) > vw+s.left){
3198                 x = vw - w - this.shadowOffset;
3199                 moved = true;
3200             }
3201             if((y + h) > vh+s.top){
3202                 y = vh - h - this.shadowOffset;
3203                 moved = true;
3204             }
3205             // then make sure top/left isn't negative
3206             if(x < s.left){
3207                 x = s.left;
3208                 moved = true;
3209             }
3210             if(y < s.top){
3211                 y = s.top;
3212                 moved = true;
3213             }
3214             if(moved){
3215                 if(this.avoidY){
3216                     var ay = this.avoidY;
3217                     if(y <= ay && (y+h) >= ay){
3218                         y = ay-h-5;   
3219                     }
3220                 }
3221                 xy = [x, y];
3222                 this.storeXY(xy);
3223                 supr.setXY.call(this, xy);
3224                 this.sync();
3225             }
3226         }
3227     },
3228
3229     isVisible : function(){
3230         return this.visible;    
3231     },
3232
3233     // private
3234     showAction : function(){
3235         this.visible = true; // track visibility to prevent getStyle calls
3236         if(this.useDisplay === true){
3237             this.setDisplayed("");
3238         }else if(this.lastXY){
3239             supr.setXY.call(this, this.lastXY);
3240         }else if(this.lastLT){
3241             supr.setLeftTop.call(this, this.lastLT[0], this.lastLT[1]);
3242         }
3243     },
3244
3245     // private
3246     hideAction : function(){
3247         this.visible = false;
3248         if(this.useDisplay === true){
3249             this.setDisplayed(false);
3250         }else{
3251             this.setLeftTop(-10000,-10000);
3252         }
3253     },
3254
3255     // overridden Element method
3256     setVisible : function(v, a, d, c, e){
3257         if(v){
3258             this.showAction();
3259         }
3260         if(a && v){
3261             var cb = function(){
3262                 this.sync(true);
3263                 if(c){
3264                     c();
3265                 }
3266             }.createDelegate(this);
3267             supr.setVisible.call(this, true, true, d, cb, e);
3268         }else{
3269             if(!v){
3270                 this.hideUnders(true);
3271             }
3272             var cb = c;
3273             if(a){
3274                 cb = function(){
3275                     this.hideAction();
3276                     if(c){
3277                         c();
3278                     }
3279                 }.createDelegate(this);
3280             }
3281             supr.setVisible.call(this, v, a, d, cb, e);
3282             if(v){
3283                 this.sync(true);
3284             }else if(!a){
3285                 this.hideAction();
3286             }
3287         }
3288     },
3289
3290     storeXY : function(xy){
3291         delete this.lastLT;
3292         this.lastXY = xy;
3293     },
3294
3295     storeLeftTop : function(left, top){
3296         delete this.lastXY;
3297         this.lastLT = [left, top];
3298     },
3299
3300     // private
3301     beforeFx : function(){
3302         this.beforeAction();
3303         return Roo.Layer.superclass.beforeFx.apply(this, arguments);
3304     },
3305
3306     // private
3307     afterFx : function(){
3308         Roo.Layer.superclass.afterFx.apply(this, arguments);
3309         this.sync(this.isVisible());
3310     },
3311
3312     // private
3313     beforeAction : function(){
3314         if(!this.updating && this.shadow){
3315             this.shadow.hide();
3316         }
3317     },
3318
3319     // overridden Element method
3320     setLeft : function(left){
3321         this.storeLeftTop(left, this.getTop(true));
3322         supr.setLeft.apply(this, arguments);
3323         this.sync();
3324     },
3325
3326     setTop : function(top){
3327         this.storeLeftTop(this.getLeft(true), top);
3328         supr.setTop.apply(this, arguments);
3329         this.sync();
3330     },
3331
3332     setLeftTop : function(left, top){
3333         this.storeLeftTop(left, top);
3334         supr.setLeftTop.apply(this, arguments);
3335         this.sync();
3336     },
3337
3338     setXY : function(xy, a, d, c, e){
3339         this.fixDisplay();
3340         this.beforeAction();
3341         this.storeXY(xy);
3342         var cb = this.createCB(c);
3343         supr.setXY.call(this, xy, a, d, cb, e);
3344         if(!a){
3345             cb();
3346         }
3347     },
3348
3349     // private
3350     createCB : function(c){
3351         var el = this;
3352         return function(){
3353             el.constrainXY();
3354             el.sync(true);
3355             if(c){
3356                 c();
3357             }
3358         };
3359     },
3360
3361     // overridden Element method
3362     setX : function(x, a, d, c, e){
3363         this.setXY([x, this.getY()], a, d, c, e);
3364     },
3365
3366     // overridden Element method
3367     setY : function(y, a, d, c, e){
3368         this.setXY([this.getX(), y], a, d, c, e);
3369     },
3370
3371     // overridden Element method
3372     setSize : function(w, h, a, d, c, e){
3373         this.beforeAction();
3374         var cb = this.createCB(c);
3375         supr.setSize.call(this, w, h, a, d, cb, e);
3376         if(!a){
3377             cb();
3378         }
3379     },
3380
3381     // overridden Element method
3382     setWidth : function(w, a, d, c, e){
3383         this.beforeAction();
3384         var cb = this.createCB(c);
3385         supr.setWidth.call(this, w, a, d, cb, e);
3386         if(!a){
3387             cb();
3388         }
3389     },
3390
3391     // overridden Element method
3392     setHeight : function(h, a, d, c, e){
3393         this.beforeAction();
3394         var cb = this.createCB(c);
3395         supr.setHeight.call(this, h, a, d, cb, e);
3396         if(!a){
3397             cb();
3398         }
3399     },
3400
3401     // overridden Element method
3402     setBounds : function(x, y, w, h, a, d, c, e){
3403         this.beforeAction();
3404         var cb = this.createCB(c);
3405         if(!a){
3406             this.storeXY([x, y]);
3407             supr.setXY.call(this, [x, y]);
3408             supr.setSize.call(this, w, h, a, d, cb, e);
3409             cb();
3410         }else{
3411             supr.setBounds.call(this, x, y, w, h, a, d, cb, e);
3412         }
3413         return this;
3414     },
3415     
3416     /**
3417      * Sets the z-index of this layer and adjusts any shadow and shim z-indexes. The layer z-index is automatically
3418      * incremented by two more than the value passed in so that it always shows above any shadow or shim (the shadow
3419      * element, if any, will be assigned z-index + 1, and the shim element, if any, will be assigned the unmodified z-index).
3420      * @param {Number} zindex The new z-index to set
3421      * @return {this} The Layer
3422      */
3423     setZIndex : function(zindex){
3424         this.zindex = zindex;
3425         this.setStyle("z-index", zindex + 2);
3426         if(this.shadow){
3427             this.shadow.setZIndex(zindex + 1);
3428         }
3429         if(this.shim){
3430             this.shim.setStyle("z-index", zindex);
3431         }
3432     }
3433 });
3434 })();/*
3435  * Based on:
3436  * Ext JS Library 1.1.1
3437  * Copyright(c) 2006-2007, Ext JS, LLC.
3438  *
3439  * Originally Released Under LGPL - original licence link has changed is not relivant.
3440  *
3441  * Fork - LGPL
3442  * <script type="text/javascript">
3443  */
3444
3445
3446 /**
3447  * @class Roo.Shadow
3448  * Simple class that can provide a shadow effect for any element.  Note that the element MUST be absolutely positioned,
3449  * and the shadow does not provide any shimming.  This should be used only in simple cases -- for more advanced
3450  * functionality that can also provide the same shadow effect, see the {@link Roo.Layer} class.
3451  * @constructor
3452  * Create a new Shadow
3453  * @param {Object} config The config object
3454  */
3455 Roo.Shadow = function(config){
3456     Roo.apply(this, config);
3457     if(typeof this.mode != "string"){
3458         this.mode = this.defaultMode;
3459     }
3460     var o = this.offset, a = {h: 0};
3461     var rad = Math.floor(this.offset/2);
3462     switch(this.mode.toLowerCase()){ // all this hideous nonsense calculates the various offsets for shadows
3463         case "drop":
3464             a.w = 0;
3465             a.l = a.t = o;
3466             a.t -= 1;
3467             if(Roo.isIE){
3468                 a.l -= this.offset + rad;
3469                 a.t -= this.offset + rad;
3470                 a.w -= rad;
3471                 a.h -= rad;
3472                 a.t += 1;
3473             }
3474         break;
3475         case "sides":
3476             a.w = (o*2);
3477             a.l = -o;
3478             a.t = o-1;
3479             if(Roo.isIE){
3480                 a.l -= (this.offset - rad);
3481                 a.t -= this.offset + rad;
3482                 a.l += 1;
3483                 a.w -= (this.offset - rad)*2;
3484                 a.w -= rad + 1;
3485                 a.h -= 1;
3486             }
3487         break;
3488         case "frame":
3489             a.w = a.h = (o*2);
3490             a.l = a.t = -o;
3491             a.t += 1;
3492             a.h -= 2;
3493             if(Roo.isIE){
3494                 a.l -= (this.offset - rad);
3495                 a.t -= (this.offset - rad);
3496                 a.l += 1;
3497                 a.w -= (this.offset + rad + 1);
3498                 a.h -= (this.offset + rad);
3499                 a.h += 1;
3500             }
3501         break;
3502     };
3503
3504     this.adjusts = a;
3505 };
3506
3507 Roo.Shadow.prototype = {
3508     /**
3509      * @cfg {String} mode
3510      * The shadow display mode.  Supports the following options:<br />
3511      * sides: Shadow displays on both sides and bottom only<br />
3512      * frame: Shadow displays equally on all four sides<br />
3513      * drop: Traditional bottom-right drop shadow (default)
3514      */
3515     /**
3516      * @cfg {String} offset
3517      * The number of pixels to offset the shadow from the element (defaults to 4)
3518      */
3519     offset: 4,
3520
3521     // private
3522     defaultMode: "drop",
3523
3524     /**
3525      * Displays the shadow under the target element
3526      * @param {String/HTMLElement/Element} targetEl The id or element under which the shadow should display
3527      */
3528     show : function(target){
3529         target = Roo.get(target);
3530         if(!this.el){
3531             this.el = Roo.Shadow.Pool.pull();
3532             if(this.el.dom.nextSibling != target.dom){
3533                 this.el.insertBefore(target);
3534             }
3535         }
3536         this.el.setStyle("z-index", this.zIndex || parseInt(target.getStyle("z-index"), 10)-1);
3537         if(Roo.isIE){
3538             this.el.dom.style.filter="progid:DXImageTransform.Microsoft.alpha(opacity=50) progid:DXImageTransform.Microsoft.Blur(pixelradius="+(this.offset)+")";
3539         }
3540         this.realign(
3541             target.getLeft(true),
3542             target.getTop(true),
3543             target.getWidth(),
3544             target.getHeight()
3545         );
3546         this.el.dom.style.display = "block";
3547     },
3548
3549     /**
3550      * Returns true if the shadow is visible, else false
3551      */
3552     isVisible : function(){
3553         return this.el ? true : false;  
3554     },
3555
3556     /**
3557      * Direct alignment when values are already available. Show must be called at least once before
3558      * calling this method to ensure it is initialized.
3559      * @param {Number} left The target element left position
3560      * @param {Number} top The target element top position
3561      * @param {Number} width The target element width
3562      * @param {Number} height The target element height
3563      */
3564     realign : function(l, t, w, h){
3565         if(!this.el){
3566             return;
3567         }
3568         var a = this.adjusts, d = this.el.dom, s = d.style;
3569         var iea = 0;
3570         s.left = (l+a.l)+"px";
3571         s.top = (t+a.t)+"px";
3572         var sw = (w+a.w), sh = (h+a.h), sws = sw +"px", shs = sh + "px";
3573  
3574         if(s.width != sws || s.height != shs){
3575             s.width = sws;
3576             s.height = shs;
3577             if(!Roo.isIE){
3578                 var cn = d.childNodes;
3579                 var sww = Math.max(0, (sw-12))+"px";
3580                 cn[0].childNodes[1].style.width = sww;
3581                 cn[1].childNodes[1].style.width = sww;
3582                 cn[2].childNodes[1].style.width = sww;
3583                 cn[1].style.height = Math.max(0, (sh-12))+"px";
3584             }
3585         }
3586     },
3587
3588     /**
3589      * Hides this shadow
3590      */
3591     hide : function(){
3592         if(this.el){
3593             this.el.dom.style.display = "none";
3594             Roo.Shadow.Pool.push(this.el);
3595             delete this.el;
3596         }
3597     },
3598
3599     /**
3600      * Adjust the z-index of this shadow
3601      * @param {Number} zindex The new z-index
3602      */
3603     setZIndex : function(z){
3604         this.zIndex = z;
3605         if(this.el){
3606             this.el.setStyle("z-index", z);
3607         }
3608     }
3609 };
3610
3611 // Private utility class that manages the internal Shadow cache
3612 Roo.Shadow.Pool = function(){
3613     var p = [];
3614     var markup = Roo.isIE ?
3615                  '<div class="x-ie-shadow"></div>' :
3616                  '<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>';
3617     return {
3618         pull : function(){
3619             var sh = p.shift();
3620             if(!sh){
3621                 sh = Roo.get(Roo.DomHelper.insertHtml("beforeBegin", document.body.firstChild, markup));
3622                 sh.autoBoxAdjust = false;
3623             }
3624             return sh;
3625         },
3626
3627         push : function(sh){
3628             p.push(sh);
3629         }
3630     };
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 /**
3644  * @class Roo.SplitBar
3645  * @extends Roo.util.Observable
3646  * Creates draggable splitter bar functionality from two elements (element to be dragged and element to be resized).
3647  * <br><br>
3648  * Usage:
3649  * <pre><code>
3650 var split = new Roo.SplitBar("elementToDrag", "elementToSize",
3651                    Roo.SplitBar.HORIZONTAL, Roo.SplitBar.LEFT);
3652 split.setAdapter(new Roo.SplitBar.AbsoluteLayoutAdapter("container"));
3653 split.minSize = 100;
3654 split.maxSize = 600;
3655 split.animate = true;
3656 split.on('moved', splitterMoved);
3657 </code></pre>
3658  * @constructor
3659  * Create a new SplitBar
3660  * @param {String/HTMLElement/Roo.Element} dragElement The element to be dragged and act as the SplitBar. 
3661  * @param {String/HTMLElement/Roo.Element} resizingElement The element to be resized based on where the SplitBar element is dragged 
3662  * @param {Number} orientation (optional) Either Roo.SplitBar.HORIZONTAL or Roo.SplitBar.VERTICAL. (Defaults to HORIZONTAL)
3663  * @param {Number} placement (optional) Either Roo.SplitBar.LEFT or Roo.SplitBar.RIGHT for horizontal or  
3664                         Roo.SplitBar.TOP or Roo.SplitBar.BOTTOM for vertical. (By default, this is determined automatically by the initial
3665                         position of the SplitBar).
3666  */
3667 Roo.SplitBar = function(dragElement, resizingElement, orientation, placement, existingProxy){
3668     
3669     /** @private */
3670     this.el = Roo.get(dragElement, true);
3671     this.el.dom.unselectable = "on";
3672     /** @private */
3673     this.resizingEl = Roo.get(resizingElement, true);
3674
3675     /**
3676      * @private
3677      * The orientation of the split. Either Roo.SplitBar.HORIZONTAL or Roo.SplitBar.VERTICAL. (Defaults to HORIZONTAL)
3678      * Note: If this is changed after creating the SplitBar, the placement property must be manually updated
3679      * @type Number
3680      */
3681     this.orientation = orientation || Roo.SplitBar.HORIZONTAL;
3682     
3683     /**
3684      * The minimum size of the resizing element. (Defaults to 0)
3685      * @type Number
3686      */
3687     this.minSize = 0;
3688     
3689     /**
3690      * The maximum size of the resizing element. (Defaults to 2000)
3691      * @type Number
3692      */
3693     this.maxSize = 2000;
3694     
3695     /**
3696      * Whether to animate the transition to the new size
3697      * @type Boolean
3698      */
3699     this.animate = false;
3700     
3701     /**
3702      * Whether to create a transparent shim that overlays the page when dragging, enables dragging across iframes.
3703      * @type Boolean
3704      */
3705     this.useShim = false;
3706     
3707     /** @private */
3708     this.shim = null;
3709     
3710     if(!existingProxy){
3711         /** @private */
3712         this.proxy = Roo.SplitBar.createProxy(this.orientation);
3713     }else{
3714         this.proxy = Roo.get(existingProxy).dom;
3715     }
3716     /** @private */
3717     this.dd = new Roo.dd.DDProxy(this.el.dom.id, "XSplitBars", {dragElId : this.proxy.id});
3718     
3719     /** @private */
3720     this.dd.b4StartDrag = this.onStartProxyDrag.createDelegate(this);
3721     
3722     /** @private */
3723     this.dd.endDrag = this.onEndProxyDrag.createDelegate(this);
3724     
3725     /** @private */
3726     this.dragSpecs = {};
3727     
3728     /**
3729      * @private The adapter to use to positon and resize elements
3730      */
3731     this.adapter = new Roo.SplitBar.BasicLayoutAdapter();
3732     this.adapter.init(this);
3733     
3734     if(this.orientation == Roo.SplitBar.HORIZONTAL){
3735         /** @private */
3736         this.placement = placement || (this.el.getX() > this.resizingEl.getX() ? Roo.SplitBar.LEFT : Roo.SplitBar.RIGHT);
3737         this.el.addClass("x-splitbar-h");
3738     }else{
3739         /** @private */
3740         this.placement = placement || (this.el.getY() > this.resizingEl.getY() ? Roo.SplitBar.TOP : Roo.SplitBar.BOTTOM);
3741         this.el.addClass("x-splitbar-v");
3742     }
3743     
3744     this.addEvents({
3745         /**
3746          * @event resize
3747          * Fires when the splitter is moved (alias for {@link #event-moved})
3748          * @param {Roo.SplitBar} this
3749          * @param {Number} newSize the new width or height
3750          */
3751         "resize" : true,
3752         /**
3753          * @event moved
3754          * Fires when the splitter is moved
3755          * @param {Roo.SplitBar} this
3756          * @param {Number} newSize the new width or height
3757          */
3758         "moved" : true,
3759         /**
3760          * @event beforeresize
3761          * Fires before the splitter is dragged
3762          * @param {Roo.SplitBar} this
3763          */
3764         "beforeresize" : true,
3765
3766         "beforeapply" : true
3767     });
3768
3769     Roo.util.Observable.call(this);
3770 };
3771
3772 Roo.extend(Roo.SplitBar, Roo.util.Observable, {
3773     onStartProxyDrag : function(x, y){
3774         this.fireEvent("beforeresize", this);
3775         if(!this.overlay){
3776             var o = Roo.DomHelper.insertFirst(document.body,  {cls: "x-drag-overlay", html: "&#160;"}, true);
3777             o.unselectable();
3778             o.enableDisplayMode("block");
3779             // all splitbars share the same overlay
3780             Roo.SplitBar.prototype.overlay = o;
3781         }
3782         this.overlay.setSize(Roo.lib.Dom.getViewWidth(true), Roo.lib.Dom.getViewHeight(true));
3783         this.overlay.show();
3784         Roo.get(this.proxy).setDisplayed("block");
3785         var size = this.adapter.getElementSize(this);
3786         this.activeMinSize = this.getMinimumSize();;
3787         this.activeMaxSize = this.getMaximumSize();;
3788         var c1 = size - this.activeMinSize;
3789         var c2 = Math.max(this.activeMaxSize - size, 0);
3790         if(this.orientation == Roo.SplitBar.HORIZONTAL){
3791             this.dd.resetConstraints();
3792             this.dd.setXConstraint(
3793                 this.placement == Roo.SplitBar.LEFT ? c1 : c2, 
3794                 this.placement == Roo.SplitBar.LEFT ? c2 : c1
3795             );
3796             this.dd.setYConstraint(0, 0);
3797         }else{
3798             this.dd.resetConstraints();
3799             this.dd.setXConstraint(0, 0);
3800             this.dd.setYConstraint(
3801                 this.placement == Roo.SplitBar.TOP ? c1 : c2, 
3802                 this.placement == Roo.SplitBar.TOP ? c2 : c1
3803             );
3804          }
3805         this.dragSpecs.startSize = size;
3806         this.dragSpecs.startPoint = [x, y];
3807         Roo.dd.DDProxy.prototype.b4StartDrag.call(this.dd, x, y);
3808     },
3809     
3810     /** 
3811      * @private Called after the drag operation by the DDProxy
3812      */
3813     onEndProxyDrag : function(e){
3814         Roo.get(this.proxy).setDisplayed(false);
3815         var endPoint = Roo.lib.Event.getXY(e);
3816         if(this.overlay){
3817             this.overlay.hide();
3818         }
3819         var newSize;
3820         if(this.orientation == Roo.SplitBar.HORIZONTAL){
3821             newSize = this.dragSpecs.startSize + 
3822                 (this.placement == Roo.SplitBar.LEFT ?
3823                     endPoint[0] - this.dragSpecs.startPoint[0] :
3824                     this.dragSpecs.startPoint[0] - endPoint[0]
3825                 );
3826         }else{
3827             newSize = this.dragSpecs.startSize + 
3828                 (this.placement == Roo.SplitBar.TOP ?
3829                     endPoint[1] - this.dragSpecs.startPoint[1] :
3830                     this.dragSpecs.startPoint[1] - endPoint[1]
3831                 );
3832         }
3833         newSize = Math.min(Math.max(newSize, this.activeMinSize), this.activeMaxSize);
3834         if(newSize != this.dragSpecs.startSize){
3835             if(this.fireEvent('beforeapply', this, newSize) !== false){
3836                 this.adapter.setElementSize(this, newSize);
3837                 this.fireEvent("moved", this, newSize);
3838                 this.fireEvent("resize", this, newSize);
3839             }
3840         }
3841     },
3842     
3843     /**
3844      * Get the adapter this SplitBar uses
3845      * @return The adapter object
3846      */
3847     getAdapter : function(){
3848         return this.adapter;
3849     },
3850     
3851     /**
3852      * Set the adapter this SplitBar uses
3853      * @param {Object} adapter A SplitBar adapter object
3854      */
3855     setAdapter : function(adapter){
3856         this.adapter = adapter;
3857         this.adapter.init(this);
3858     },
3859     
3860     /**
3861      * Gets the minimum size for the resizing element
3862      * @return {Number} The minimum size
3863      */
3864     getMinimumSize : function(){
3865         return this.minSize;
3866     },
3867     
3868     /**
3869      * Sets the minimum size for the resizing element
3870      * @param {Number} minSize The minimum size
3871      */
3872     setMinimumSize : function(minSize){
3873         this.minSize = minSize;
3874     },
3875     
3876     /**
3877      * Gets the maximum size for the resizing element
3878      * @return {Number} The maximum size
3879      */
3880     getMaximumSize : function(){
3881         return this.maxSize;
3882     },
3883     
3884     /**
3885      * Sets the maximum size for the resizing element
3886      * @param {Number} maxSize The maximum size
3887      */
3888     setMaximumSize : function(maxSize){
3889         this.maxSize = maxSize;
3890     },
3891     
3892     /**
3893      * Sets the initialize size for the resizing element
3894      * @param {Number} size The initial size
3895      */
3896     setCurrentSize : function(size){
3897         var oldAnimate = this.animate;
3898         this.animate = false;
3899         this.adapter.setElementSize(this, size);
3900         this.animate = oldAnimate;
3901     },
3902     
3903     /**
3904      * Destroy this splitbar. 
3905      * @param {Boolean} removeEl True to remove the element
3906      */
3907     destroy : function(removeEl){
3908         if(this.shim){
3909             this.shim.remove();
3910         }
3911         this.dd.unreg();
3912         this.proxy.parentNode.removeChild(this.proxy);
3913         if(removeEl){
3914             this.el.remove();
3915         }
3916     }
3917 });
3918
3919 /**
3920  * @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.
3921  */
3922 Roo.SplitBar.createProxy = function(dir){
3923     var proxy = new Roo.Element(document.createElement("div"));
3924     proxy.unselectable();
3925     var cls = 'x-splitbar-proxy';
3926     proxy.addClass(cls + ' ' + (dir == Roo.SplitBar.HORIZONTAL ? cls +'-h' : cls + '-v'));
3927     document.body.appendChild(proxy.dom);
3928     return proxy.dom;
3929 };
3930
3931 /** 
3932  * @class Roo.SplitBar.BasicLayoutAdapter
3933  * Default Adapter. It assumes the splitter and resizing element are not positioned
3934  * elements and only gets/sets the width of the element. Generally used for table based layouts.
3935  */
3936 Roo.SplitBar.BasicLayoutAdapter = function(){
3937 };
3938
3939 Roo.SplitBar.BasicLayoutAdapter.prototype = {
3940     // do nothing for now
3941     init : function(s){
3942     
3943     },
3944     /**
3945      * Called before drag operations to get the current size of the resizing element. 
3946      * @param {Roo.SplitBar} s The SplitBar using this adapter
3947      */
3948      getElementSize : function(s){
3949         if(s.orientation == Roo.SplitBar.HORIZONTAL){
3950             return s.resizingEl.getWidth();
3951         }else{
3952             return s.resizingEl.getHeight();
3953         }
3954     },
3955     
3956     /**
3957      * Called after drag operations to set the size of the resizing element.
3958      * @param {Roo.SplitBar} s The SplitBar using this adapter
3959      * @param {Number} newSize The new size to set
3960      * @param {Function} onComplete A function to be invoked when resizing is complete
3961      */
3962     setElementSize : function(s, newSize, onComplete){
3963         if(s.orientation == Roo.SplitBar.HORIZONTAL){
3964             if(!s.animate){
3965                 s.resizingEl.setWidth(newSize);
3966                 if(onComplete){
3967                     onComplete(s, newSize);
3968                 }
3969             }else{
3970                 s.resizingEl.setWidth(newSize, true, .1, onComplete, 'easeOut');
3971             }
3972         }else{
3973             
3974             if(!s.animate){
3975                 s.resizingEl.setHeight(newSize);
3976                 if(onComplete){
3977                     onComplete(s, newSize);
3978                 }
3979             }else{
3980                 s.resizingEl.setHeight(newSize, true, .1, onComplete, 'easeOut');
3981             }
3982         }
3983     }
3984 };
3985
3986 /** 
3987  *@class Roo.SplitBar.AbsoluteLayoutAdapter
3988  * @extends Roo.SplitBar.BasicLayoutAdapter
3989  * Adapter that  moves the splitter element to align with the resized sizing element. 
3990  * Used with an absolute positioned SplitBar.
3991  * @param {String/HTMLElement/Roo.Element} container The container that wraps around the absolute positioned content. If it's
3992  * document.body, make sure you assign an id to the body element.
3993  */
3994 Roo.SplitBar.AbsoluteLayoutAdapter = function(container){
3995     this.basic = new Roo.SplitBar.BasicLayoutAdapter();
3996     this.container = Roo.get(container);
3997 };
3998
3999 Roo.SplitBar.AbsoluteLayoutAdapter.prototype = {
4000     init : function(s){
4001         this.basic.init(s);
4002     },
4003     
4004     getElementSize : function(s){
4005         return this.basic.getElementSize(s);
4006     },
4007     
4008     setElementSize : function(s, newSize, onComplete){
4009         this.basic.setElementSize(s, newSize, this.moveSplitter.createDelegate(this, [s]));
4010     },
4011     
4012     moveSplitter : function(s){
4013         var yes = Roo.SplitBar;
4014         switch(s.placement){
4015             case yes.LEFT:
4016                 s.el.setX(s.resizingEl.getRight());
4017                 break;
4018             case yes.RIGHT:
4019                 s.el.setStyle("right", (this.container.getWidth() - s.resizingEl.getLeft()) + "px");
4020                 break;
4021             case yes.TOP:
4022                 s.el.setY(s.resizingEl.getBottom());
4023                 break;
4024             case yes.BOTTOM:
4025                 s.el.setY(s.resizingEl.getTop() - s.el.getHeight());
4026                 break;
4027         }
4028     }
4029 };
4030
4031 /**
4032  * Orientation constant - Create a vertical SplitBar
4033  * @static
4034  * @type Number
4035  */
4036 Roo.SplitBar.VERTICAL = 1;
4037
4038 /**
4039  * Orientation constant - Create a horizontal SplitBar
4040  * @static
4041  * @type Number
4042  */
4043 Roo.SplitBar.HORIZONTAL = 2;
4044
4045 /**
4046  * Placement constant - The resizing element is to the left of the splitter element
4047  * @static
4048  * @type Number
4049  */
4050 Roo.SplitBar.LEFT = 1;
4051
4052 /**
4053  * Placement constant - The resizing element is to the right of the splitter element
4054  * @static
4055  * @type Number
4056  */
4057 Roo.SplitBar.RIGHT = 2;
4058
4059 /**
4060  * Placement constant - The resizing element is positioned above the splitter element
4061  * @static
4062  * @type Number
4063  */
4064 Roo.SplitBar.TOP = 3;
4065
4066 /**
4067  * Placement constant - The resizing element is positioned under splitter element
4068  * @static
4069  * @type Number
4070  */
4071 Roo.SplitBar.BOTTOM = 4;
4072 /*
4073  * Based on:
4074  * Ext JS Library 1.1.1
4075  * Copyright(c) 2006-2007, Ext JS, LLC.
4076  *
4077  * Originally Released Under LGPL - original licence link has changed is not relivant.
4078  *
4079  * Fork - LGPL
4080  * <script type="text/javascript">
4081  */
4082
4083 /**
4084  * @class Roo.View
4085  * @extends Roo.util.Observable
4086  * Create a "View" for an element based on a data model or UpdateManager and the supplied DomHelper template. 
4087  * This class also supports single and multi selection modes. <br>
4088  * Create a data model bound view:
4089  <pre><code>
4090  var store = new Roo.data.Store(...);
4091
4092  var view = new Roo.View({
4093     el : "my-element",
4094     tpl : '&lt;div id="{0}"&gt;{2} - {1}&lt;/div&gt;', // auto create template
4095  
4096     singleSelect: true,
4097     selectedClass: "ydataview-selected",
4098     store: store
4099  });
4100
4101  // listen for node click?
4102  view.on("click", function(vw, index, node, e){
4103  alert('Node "' + node.id + '" at index: ' + index + " was clicked.");
4104  });
4105
4106  // load XML data
4107  dataModel.load("foobar.xml");
4108  </code></pre>
4109  For an example of creating a JSON/UpdateManager view, see {@link Roo.JsonView}.
4110  * <br><br>
4111  * <b>Note: The root of your template must be a single node. Table/row implementations may work but are not supported due to
4112  * IE"s limited insertion support with tables and Opera"s faulty event bubbling.</b>
4113  * 
4114  * Note: old style constructor is still suported (container, template, config)
4115  * 
4116  * @constructor
4117  * Create a new View
4118  * @param {Object} config The config object
4119  * 
4120  */
4121 Roo.View = function(config, depreciated_tpl, depreciated_config){
4122     
4123     this.parent = false;
4124     
4125     if (typeof(depreciated_tpl) == 'undefined') {
4126         // new way.. - universal constructor.
4127         Roo.apply(this, config);
4128         this.el  = Roo.get(this.el);
4129     } else {
4130         // old format..
4131         this.el  = Roo.get(config);
4132         this.tpl = depreciated_tpl;
4133         Roo.apply(this, depreciated_config);
4134     }
4135     this.wrapEl  = this.el.wrap().wrap();
4136     ///this.el = this.wrapEla.appendChild(document.createElement("div"));
4137     
4138     
4139     if(typeof(this.tpl) == "string"){
4140         this.tpl = new Roo.Template(this.tpl);
4141     } else {
4142         // support xtype ctors..
4143         this.tpl = new Roo.factory(this.tpl, Roo);
4144     }
4145     
4146     
4147     this.tpl.compile();
4148     
4149     /** @private */
4150     this.addEvents({
4151         /**
4152          * @event beforeclick
4153          * Fires before a click is processed. Returns false to cancel the default action.
4154          * @param {Roo.View} this
4155          * @param {Number} index The index of the target node
4156          * @param {HTMLElement} node The target node
4157          * @param {Roo.EventObject} e The raw event object
4158          */
4159             "beforeclick" : true,
4160         /**
4161          * @event click
4162          * Fires when a template node is clicked.
4163          * @param {Roo.View} this
4164          * @param {Number} index The index of the target node
4165          * @param {HTMLElement} node The target node
4166          * @param {Roo.EventObject} e The raw event object
4167          */
4168             "click" : true,
4169         /**
4170          * @event dblclick
4171          * Fires when a template node is double clicked.
4172          * @param {Roo.View} this
4173          * @param {Number} index The index of the target node
4174          * @param {HTMLElement} node The target node
4175          * @param {Roo.EventObject} e The raw event object
4176          */
4177             "dblclick" : true,
4178         /**
4179          * @event contextmenu
4180          * Fires when a template node is right clicked.
4181          * @param {Roo.View} this
4182          * @param {Number} index The index of the target node
4183          * @param {HTMLElement} node The target node
4184          * @param {Roo.EventObject} e The raw event object
4185          */
4186             "contextmenu" : true,
4187         /**
4188          * @event selectionchange
4189          * Fires when the selected nodes change.
4190          * @param {Roo.View} this
4191          * @param {Array} selections Array of the selected nodes
4192          */
4193             "selectionchange" : true,
4194     
4195         /**
4196          * @event beforeselect
4197          * Fires before a selection is made. If any handlers return false, the selection is cancelled.
4198          * @param {Roo.View} this
4199          * @param {HTMLElement} node The node to be selected
4200          * @param {Array} selections Array of currently selected nodes
4201          */
4202             "beforeselect" : true,
4203         /**
4204          * @event preparedata
4205          * Fires on every row to render, to allow you to change the data.
4206          * @param {Roo.View} this
4207          * @param {Object} data to be rendered (change this)
4208          */
4209           "preparedata" : true
4210           
4211           
4212         });
4213
4214
4215
4216     this.el.on({
4217         "click": this.onClick,
4218         "dblclick": this.onDblClick,
4219         "contextmenu": this.onContextMenu,
4220         scope:this
4221     });
4222
4223     this.selections = [];
4224     this.nodes = [];
4225     this.cmp = new Roo.CompositeElementLite([]);
4226     if(this.store){
4227         this.store = Roo.factory(this.store, Roo.data);
4228         this.setStore(this.store, true);
4229     }
4230     
4231     if ( this.footer && this.footer.xtype) {
4232            
4233          var fctr = this.wrapEl.appendChild(document.createElement("div"));
4234         
4235         this.footer.dataSource = this.store;
4236         this.footer.container = fctr;
4237         this.footer = Roo.factory(this.footer, Roo);
4238         fctr.insertFirst(this.el);
4239         
4240         // this is a bit insane - as the paging toolbar seems to detach the el..
4241 //        dom.parentNode.parentNode.parentNode
4242          // they get detached?
4243     }
4244     
4245     
4246     Roo.View.superclass.constructor.call(this);
4247     
4248     
4249 };
4250
4251 Roo.extend(Roo.View, Roo.util.Observable, {
4252     
4253      /**
4254      * @cfg {Roo.data.Store} store Data store to load data from.
4255      */
4256     store : false,
4257     
4258     /**
4259      * @cfg {String|Roo.Element} el The container element.
4260      */
4261     el : '',
4262     
4263     /**
4264      * @cfg {String|Roo.Template} tpl The template used by this View 
4265      */
4266     tpl : false,
4267     /**
4268      * @cfg {String} dataName the named area of the template to use as the data area
4269      *                          Works with domtemplates roo-name="name"
4270      */
4271     dataName: false,
4272     /**
4273      * @cfg {String} selectedClass The css class to add to selected nodes
4274      */
4275     selectedClass : "x-view-selected",
4276      /**
4277      * @cfg {String} emptyText The empty text to show when nothing is loaded.
4278      */
4279     emptyText : "",
4280     
4281     /**
4282      * @cfg {String} text to display on mask (default Loading)
4283      */
4284     mask : false,
4285     /**
4286      * @cfg {Boolean} multiSelect Allow multiple selection
4287      */
4288     multiSelect : false,
4289     /**
4290      * @cfg {Boolean} singleSelect Allow single selection
4291      */
4292     singleSelect:  false,
4293     
4294     /**
4295      * @cfg {Boolean} toggleSelect - selecting 
4296      */
4297     toggleSelect : false,
4298     
4299     /**
4300      * @cfg {Boolean} tickable - selecting 
4301      */
4302     tickable : false,
4303     
4304     /**
4305      * Returns the element this view is bound to.
4306      * @return {Roo.Element}
4307      */
4308     getEl : function(){
4309         return this.wrapEl;
4310     },
4311     
4312     
4313
4314     /**
4315      * Refreshes the view. - called by datachanged on the store. - do not call directly.
4316      */
4317     refresh : function(){
4318         //Roo.log('refresh');
4319         var t = this.tpl;
4320         
4321         // if we are using something like 'domtemplate', then
4322         // the what gets used is:
4323         // t.applySubtemplate(NAME, data, wrapping data..)
4324         // the outer template then get' applied with
4325         //     the store 'extra data'
4326         // and the body get's added to the
4327         //      roo-name="data" node?
4328         //      <span class='roo-tpl-{name}'></span> ?????
4329         
4330         
4331         
4332         this.clearSelections();
4333         this.el.update("");
4334         var html = [];
4335         var records = this.store.getRange();
4336         if(records.length < 1) {
4337             
4338             // is this valid??  = should it render a template??
4339             
4340             this.el.update(this.emptyText);
4341             return;
4342         }
4343         var el = this.el;
4344         if (this.dataName) {
4345             this.el.update(t.apply(this.store.meta)); //????
4346             el = this.el.child('.roo-tpl-' + this.dataName);
4347         }
4348         
4349         for(var i = 0, len = records.length; i < len; i++){
4350             var data = this.prepareData(records[i].data, i, records[i]);
4351             this.fireEvent("preparedata", this, data, i, records[i]);
4352             
4353             var d = Roo.apply({}, data);
4354             
4355             if(this.tickable){
4356                 Roo.apply(d, {'roo-id' : Roo.id()});
4357                 
4358                 var _this = this;
4359             
4360                 Roo.each(this.parent.item, function(item){
4361                     if(item[_this.parent.valueField] != data[_this.parent.valueField]){
4362                         return;
4363                     }
4364                     Roo.apply(d, {'roo-data-checked' : 'checked'});
4365                 });
4366             }
4367             
4368             html[html.length] = Roo.util.Format.trim(
4369                 this.dataName ?
4370                     t.applySubtemplate(this.dataName, d, this.store.meta) :
4371                     t.apply(d)
4372             );
4373         }
4374         
4375         
4376         
4377         el.update(html.join(""));
4378         this.nodes = el.dom.childNodes;
4379         this.updateIndexes(0);
4380     },
4381     
4382
4383     /**
4384      * Function to override to reformat the data that is sent to
4385      * the template for each node.
4386      * DEPRICATED - use the preparedata event handler.
4387      * @param {Array/Object} data The raw data (array of colData for a data model bound view or
4388      * a JSON object for an UpdateManager bound view).
4389      */
4390     prepareData : function(data, index, record)
4391     {
4392         this.fireEvent("preparedata", this, data, index, record);
4393         return data;
4394     },
4395
4396     onUpdate : function(ds, record){
4397         // Roo.log('on update');   
4398         this.clearSelections();
4399         var index = this.store.indexOf(record);
4400         var n = this.nodes[index];
4401         this.tpl.insertBefore(n, this.prepareData(record.data, index, record));
4402         n.parentNode.removeChild(n);
4403         this.updateIndexes(index, index);
4404     },
4405
4406     
4407     
4408 // --------- FIXME     
4409     onAdd : function(ds, records, index)
4410     {
4411         //Roo.log(['on Add', ds, records, index] );        
4412         this.clearSelections();
4413         if(this.nodes.length == 0){
4414             this.refresh();
4415             return;
4416         }
4417         var n = this.nodes[index];
4418         for(var i = 0, len = records.length; i < len; i++){
4419             var d = this.prepareData(records[i].data, i, records[i]);
4420             if(n){
4421                 this.tpl.insertBefore(n, d);
4422             }else{
4423                 
4424                 this.tpl.append(this.el, d);
4425             }
4426         }
4427         this.updateIndexes(index);
4428     },
4429
4430     onRemove : function(ds, record, index){
4431        // Roo.log('onRemove');
4432         this.clearSelections();
4433         var el = this.dataName  ?
4434             this.el.child('.roo-tpl-' + this.dataName) :
4435             this.el; 
4436         
4437         el.dom.removeChild(this.nodes[index]);
4438         this.updateIndexes(index);
4439     },
4440
4441     /**
4442      * Refresh an individual node.
4443      * @param {Number} index
4444      */
4445     refreshNode : function(index){
4446         this.onUpdate(this.store, this.store.getAt(index));
4447     },
4448
4449     updateIndexes : function(startIndex, endIndex){
4450         var ns = this.nodes;
4451         startIndex = startIndex || 0;
4452         endIndex = endIndex || ns.length - 1;
4453         for(var i = startIndex; i <= endIndex; i++){
4454             ns[i].nodeIndex = i;
4455         }
4456     },
4457
4458     /**
4459      * Changes the data store this view uses and refresh the view.
4460      * @param {Store} store
4461      */
4462     setStore : function(store, initial){
4463         if(!initial && this.store){
4464             this.store.un("datachanged", this.refresh);
4465             this.store.un("add", this.onAdd);
4466             this.store.un("remove", this.onRemove);
4467             this.store.un("update", this.onUpdate);
4468             this.store.un("clear", this.refresh);
4469             this.store.un("beforeload", this.onBeforeLoad);
4470             this.store.un("load", this.onLoad);
4471             this.store.un("loadexception", this.onLoad);
4472         }
4473         if(store){
4474           
4475             store.on("datachanged", this.refresh, this);
4476             store.on("add", this.onAdd, this);
4477             store.on("remove", this.onRemove, this);
4478             store.on("update", this.onUpdate, this);
4479             store.on("clear", this.refresh, this);
4480             store.on("beforeload", this.onBeforeLoad, this);
4481             store.on("load", this.onLoad, this);
4482             store.on("loadexception", this.onLoad, this);
4483         }
4484         
4485         if(store){
4486             this.refresh();
4487         }
4488     },
4489     /**
4490      * onbeforeLoad - masks the loading area.
4491      *
4492      */
4493     onBeforeLoad : function(store,opts)
4494     {
4495          //Roo.log('onBeforeLoad');   
4496         if (!opts.add) {
4497             this.el.update("");
4498         }
4499         this.el.mask(this.mask ? this.mask : "Loading" ); 
4500     },
4501     onLoad : function ()
4502     {
4503         this.el.unmask();
4504     },
4505     
4506
4507     /**
4508      * Returns the template node the passed child belongs to or null if it doesn't belong to one.
4509      * @param {HTMLElement} node
4510      * @return {HTMLElement} The template node
4511      */
4512     findItemFromChild : function(node){
4513         var el = this.dataName  ?
4514             this.el.child('.roo-tpl-' + this.dataName,true) :
4515             this.el.dom; 
4516         
4517         if(!node || node.parentNode == el){
4518                     return node;
4519             }
4520             var p = node.parentNode;
4521             while(p && p != el){
4522             if(p.parentNode == el){
4523                 return p;
4524             }
4525             p = p.parentNode;
4526         }
4527             return null;
4528     },
4529
4530     /** @ignore */
4531     onClick : function(e){
4532         var item = this.findItemFromChild(e.getTarget());
4533         if(item){
4534             var index = this.indexOf(item);
4535             if(this.onItemClick(item, index, e) !== false){
4536                 this.fireEvent("click", this, index, item, e);
4537             }
4538         }else{
4539             this.clearSelections();
4540         }
4541     },
4542
4543     /** @ignore */
4544     onContextMenu : function(e){
4545         var item = this.findItemFromChild(e.getTarget());
4546         if(item){
4547             this.fireEvent("contextmenu", this, this.indexOf(item), item, e);
4548         }
4549     },
4550
4551     /** @ignore */
4552     onDblClick : function(e){
4553         var item = this.findItemFromChild(e.getTarget());
4554         if(item){
4555             this.fireEvent("dblclick", this, this.indexOf(item), item, e);
4556         }
4557     },
4558
4559     onItemClick : function(item, index, e)
4560     {
4561         if(this.fireEvent("beforeclick", this, index, item, e) === false){
4562             return false;
4563         }
4564         if (this.toggleSelect) {
4565             var m = this.isSelected(item) ? 'unselect' : 'select';
4566             //Roo.log(m);
4567             var _t = this;
4568             _t[m](item, true, false);
4569             return true;
4570         }
4571         if(this.multiSelect || this.singleSelect){
4572             if(this.multiSelect && e.shiftKey && this.lastSelection){
4573                 this.select(this.getNodes(this.indexOf(this.lastSelection), index), false);
4574             }else{
4575                 this.select(item, this.multiSelect && e.ctrlKey);
4576                 this.lastSelection = item;
4577             }
4578             
4579             if(!this.tickable){
4580                 e.preventDefault();
4581             }
4582             
4583         }
4584         return true;
4585     },
4586
4587     /**
4588      * Get the number of selected nodes.
4589      * @return {Number}
4590      */
4591     getSelectionCount : function(){
4592         return this.selections.length;
4593     },
4594
4595     /**
4596      * Get the currently selected nodes.
4597      * @return {Array} An array of HTMLElements
4598      */
4599     getSelectedNodes : function(){
4600         return this.selections;
4601     },
4602
4603     /**
4604      * Get the indexes of the selected nodes.
4605      * @return {Array}
4606      */
4607     getSelectedIndexes : function(){
4608         var indexes = [], s = this.selections;
4609         for(var i = 0, len = s.length; i < len; i++){
4610             indexes.push(s[i].nodeIndex);
4611         }
4612         return indexes;
4613     },
4614
4615     /**
4616      * Clear all selections
4617      * @param {Boolean} suppressEvent (optional) true to skip firing of the selectionchange event
4618      */
4619     clearSelections : function(suppressEvent){
4620         if(this.nodes && (this.multiSelect || this.singleSelect) && this.selections.length > 0){
4621             this.cmp.elements = this.selections;
4622             this.cmp.removeClass(this.selectedClass);
4623             this.selections = [];
4624             if(!suppressEvent){
4625                 this.fireEvent("selectionchange", this, this.selections);
4626             }
4627         }
4628     },
4629
4630     /**
4631      * Returns true if the passed node is selected
4632      * @param {HTMLElement/Number} node The node or node index
4633      * @return {Boolean}
4634      */
4635     isSelected : function(node){
4636         var s = this.selections;
4637         if(s.length < 1){
4638             return false;
4639         }
4640         node = this.getNode(node);
4641         return s.indexOf(node) !== -1;
4642     },
4643
4644     /**
4645      * Selects nodes.
4646      * @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
4647      * @param {Boolean} keepExisting (optional) true to keep existing selections
4648      * @param {Boolean} suppressEvent (optional) true to skip firing of the selectionchange vent
4649      */
4650     select : function(nodeInfo, keepExisting, suppressEvent){
4651         if(nodeInfo instanceof Array){
4652             if(!keepExisting){
4653                 this.clearSelections(true);
4654             }
4655             for(var i = 0, len = nodeInfo.length; i < len; i++){
4656                 this.select(nodeInfo[i], true, true);
4657             }
4658             return;
4659         } 
4660         var node = this.getNode(nodeInfo);
4661         if(!node || this.isSelected(node)){
4662             return; // already selected.
4663         }
4664         if(!keepExisting){
4665             this.clearSelections(true);
4666         }
4667         
4668         if(this.fireEvent("beforeselect", this, node, this.selections) !== false){
4669             Roo.fly(node).addClass(this.selectedClass);
4670             this.selections.push(node);
4671             if(!suppressEvent){
4672                 this.fireEvent("selectionchange", this, this.selections);
4673             }
4674         }
4675         
4676         
4677     },
4678       /**
4679      * Unselects nodes.
4680      * @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
4681      * @param {Boolean} keepExisting (optional) true IGNORED (for campatibility with select)
4682      * @param {Boolean} suppressEvent (optional) true to skip firing of the selectionchange vent
4683      */
4684     unselect : function(nodeInfo, keepExisting, suppressEvent)
4685     {
4686         if(nodeInfo instanceof Array){
4687             Roo.each(this.selections, function(s) {
4688                 this.unselect(s, nodeInfo);
4689             }, this);
4690             return;
4691         }
4692         var node = this.getNode(nodeInfo);
4693         if(!node || !this.isSelected(node)){
4694             //Roo.log("not selected");
4695             return; // not selected.
4696         }
4697         // fireevent???
4698         var ns = [];
4699         Roo.each(this.selections, function(s) {
4700             if (s == node ) {
4701                 Roo.fly(node).removeClass(this.selectedClass);
4702
4703                 return;
4704             }
4705             ns.push(s);
4706         },this);
4707         
4708         this.selections= ns;
4709         this.fireEvent("selectionchange", this, this.selections);
4710     },
4711
4712     /**
4713      * Gets a template node.
4714      * @param {HTMLElement/String/Number} nodeInfo An HTMLElement template node, index of a template node or the id of a template node
4715      * @return {HTMLElement} The node or null if it wasn't found
4716      */
4717     getNode : function(nodeInfo){
4718         if(typeof nodeInfo == "string"){
4719             return document.getElementById(nodeInfo);
4720         }else if(typeof nodeInfo == "number"){
4721             return this.nodes[nodeInfo];
4722         }
4723         return nodeInfo;
4724     },
4725
4726     /**
4727      * Gets a range template nodes.
4728      * @param {Number} startIndex
4729      * @param {Number} endIndex
4730      * @return {Array} An array of nodes
4731      */
4732     getNodes : function(start, end){
4733         var ns = this.nodes;
4734         start = start || 0;
4735         end = typeof end == "undefined" ? ns.length - 1 : end;
4736         var nodes = [];
4737         if(start <= end){
4738             for(var i = start; i <= end; i++){
4739                 nodes.push(ns[i]);
4740             }
4741         } else{
4742             for(var i = start; i >= end; i--){
4743                 nodes.push(ns[i]);
4744             }
4745         }
4746         return nodes;
4747     },
4748
4749     /**
4750      * Finds the index of the passed node
4751      * @param {HTMLElement/String/Number} nodeInfo An HTMLElement template node, index of a template node or the id of a template node
4752      * @return {Number} The index of the node or -1
4753      */
4754     indexOf : function(node){
4755         node = this.getNode(node);
4756         if(typeof node.nodeIndex == "number"){
4757             return node.nodeIndex;
4758         }
4759         var ns = this.nodes;
4760         for(var i = 0, len = ns.length; i < len; i++){
4761             if(ns[i] == node){
4762                 return i;
4763             }
4764         }
4765         return -1;
4766     }
4767 });
4768 /*
4769  * Based on:
4770  * Ext JS Library 1.1.1
4771  * Copyright(c) 2006-2007, Ext JS, LLC.
4772  *
4773  * Originally Released Under LGPL - original licence link has changed is not relivant.
4774  *
4775  * Fork - LGPL
4776  * <script type="text/javascript">
4777  */
4778
4779 /**
4780  * @class Roo.JsonView
4781  * @extends Roo.View
4782  * Shortcut class to create a JSON + {@link Roo.UpdateManager} template view. Usage:
4783 <pre><code>
4784 var view = new Roo.JsonView({
4785     container: "my-element",
4786     tpl: '&lt;div id="{id}"&gt;{foo} - {bar}&lt;/div&gt;', // auto create template
4787     multiSelect: true, 
4788     jsonRoot: "data" 
4789 });
4790
4791 // listen for node click?
4792 view.on("click", function(vw, index, node, e){
4793     alert('Node "' + node.id + '" at index: ' + index + " was clicked.");
4794 });
4795
4796 // direct load of JSON data
4797 view.load("foobar.php");
4798
4799 // Example from my blog list
4800 var tpl = new Roo.Template(
4801     '&lt;div class="entry"&gt;' +
4802     '&lt;a class="entry-title" href="{link}"&gt;{title}&lt;/a&gt;' +
4803     "&lt;h4&gt;{date} by {author} | {comments} Comments&lt;/h4&gt;{description}" +
4804     "&lt;/div&gt;&lt;hr /&gt;"
4805 );
4806
4807 var moreView = new Roo.JsonView({
4808     container :  "entry-list", 
4809     template : tpl,
4810     jsonRoot: "posts"
4811 });
4812 moreView.on("beforerender", this.sortEntries, this);
4813 moreView.load({
4814     url: "/blog/get-posts.php",
4815     params: "allposts=true",
4816     text: "Loading Blog Entries..."
4817 });
4818 </code></pre>
4819
4820 * Note: old code is supported with arguments : (container, template, config)
4821
4822
4823  * @constructor
4824  * Create a new JsonView
4825  * 
4826  * @param {Object} config The config object
4827  * 
4828  */
4829 Roo.JsonView = function(config, depreciated_tpl, depreciated_config){
4830     
4831     
4832     Roo.JsonView.superclass.constructor.call(this, config, depreciated_tpl, depreciated_config);
4833
4834     var um = this.el.getUpdateManager();
4835     um.setRenderer(this);
4836     um.on("update", this.onLoad, this);
4837     um.on("failure", this.onLoadException, this);
4838
4839     /**
4840      * @event beforerender
4841      * Fires before rendering of the downloaded JSON data.
4842      * @param {Roo.JsonView} this
4843      * @param {Object} data The JSON data loaded
4844      */
4845     /**
4846      * @event load
4847      * Fires when data is loaded.
4848      * @param {Roo.JsonView} this
4849      * @param {Object} data The JSON data loaded
4850      * @param {Object} response The raw Connect response object
4851      */
4852     /**
4853      * @event loadexception
4854      * Fires when loading fails.
4855      * @param {Roo.JsonView} this
4856      * @param {Object} response The raw Connect response object
4857      */
4858     this.addEvents({
4859         'beforerender' : true,
4860         'load' : true,
4861         'loadexception' : true
4862     });
4863 };
4864 Roo.extend(Roo.JsonView, Roo.View, {
4865     /**
4866      * @type {String} The root property in the loaded JSON object that contains the data
4867      */
4868     jsonRoot : "",
4869
4870     /**
4871      * Refreshes the view.
4872      */
4873     refresh : function(){
4874         this.clearSelections();
4875         this.el.update("");
4876         var html = [];
4877         var o = this.jsonData;
4878         if(o && o.length > 0){
4879             for(var i = 0, len = o.length; i < len; i++){
4880                 var data = this.prepareData(o[i], i, o);
4881                 html[html.length] = this.tpl.apply(data);
4882             }
4883         }else{
4884             html.push(this.emptyText);
4885         }
4886         this.el.update(html.join(""));
4887         this.nodes = this.el.dom.childNodes;
4888         this.updateIndexes(0);
4889     },
4890
4891     /**
4892      * 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.
4893      * @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:
4894      <pre><code>
4895      view.load({
4896          url: "your-url.php",
4897          params: {param1: "foo", param2: "bar"}, // or a URL encoded string
4898          callback: yourFunction,
4899          scope: yourObject, //(optional scope)
4900          discardUrl: false,
4901          nocache: false,
4902          text: "Loading...",
4903          timeout: 30,
4904          scripts: false
4905      });
4906      </code></pre>
4907      * The only required property is <i>url</i>. The optional properties <i>nocache</i>, <i>text</i> and <i>scripts</i>
4908      * 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.
4909      * @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}
4910      * @param {Function} callback (optional) Callback when transaction is complete - called with signature (oElement, bSuccess)
4911      * @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.
4912      */
4913     load : function(){
4914         var um = this.el.getUpdateManager();
4915         um.update.apply(um, arguments);
4916     },
4917
4918     // note - render is a standard framework call...
4919     // using it for the response is really flaky... - it's called by UpdateManager normally, except when called by the XComponent/addXtype.
4920     render : function(el, response){
4921         
4922         this.clearSelections();
4923         this.el.update("");
4924         var o;
4925         try{
4926             if (response != '') {
4927                 o = Roo.util.JSON.decode(response.responseText);
4928                 if(this.jsonRoot){
4929                     
4930                     o = o[this.jsonRoot];
4931                 }
4932             }
4933         } catch(e){
4934         }
4935         /**
4936          * The current JSON data or null
4937          */
4938         this.jsonData = o;
4939         this.beforeRender();
4940         this.refresh();
4941     },
4942
4943 /**
4944  * Get the number of records in the current JSON dataset
4945  * @return {Number}
4946  */
4947     getCount : function(){
4948         return this.jsonData ? this.jsonData.length : 0;
4949     },
4950
4951 /**
4952  * Returns the JSON object for the specified node(s)
4953  * @param {HTMLElement/Array} node The node or an array of nodes
4954  * @return {Object/Array} If you pass in an array, you get an array back, otherwise
4955  * you get the JSON object for the node
4956  */
4957     getNodeData : function(node){
4958         if(node instanceof Array){
4959             var data = [];
4960             for(var i = 0, len = node.length; i < len; i++){
4961                 data.push(this.getNodeData(node[i]));
4962             }
4963             return data;
4964         }
4965         return this.jsonData[this.indexOf(node)] || null;
4966     },
4967
4968     beforeRender : function(){
4969         this.snapshot = this.jsonData;
4970         if(this.sortInfo){
4971             this.sort.apply(this, this.sortInfo);
4972         }
4973         this.fireEvent("beforerender", this, this.jsonData);
4974     },
4975
4976     onLoad : function(el, o){
4977         this.fireEvent("load", this, this.jsonData, o);
4978     },
4979
4980     onLoadException : function(el, o){
4981         this.fireEvent("loadexception", this, o);
4982     },
4983
4984 /**
4985  * Filter the data by a specific property.
4986  * @param {String} property A property on your JSON objects
4987  * @param {String/RegExp} value Either string that the property values
4988  * should start with, or a RegExp to test against the property
4989  */
4990     filter : function(property, value){
4991         if(this.jsonData){
4992             var data = [];
4993             var ss = this.snapshot;
4994             if(typeof value == "string"){
4995                 var vlen = value.length;
4996                 if(vlen == 0){
4997                     this.clearFilter();
4998                     return;
4999                 }
5000                 value = value.toLowerCase();
5001                 for(var i = 0, len = ss.length; i < len; i++){
5002                     var o = ss[i];
5003                     if(o[property].substr(0, vlen).toLowerCase() == value){
5004                         data.push(o);
5005                     }
5006                 }
5007             } else if(value.exec){ // regex?
5008                 for(var i = 0, len = ss.length; i < len; i++){
5009                     var o = ss[i];
5010                     if(value.test(o[property])){
5011                         data.push(o);
5012                     }
5013                 }
5014             } else{
5015                 return;
5016             }
5017             this.jsonData = data;
5018             this.refresh();
5019         }
5020     },
5021
5022 /**
5023  * Filter by a function. The passed function will be called with each
5024  * object in the current dataset. If the function returns true the value is kept,
5025  * otherwise it is filtered.
5026  * @param {Function} fn
5027  * @param {Object} scope (optional) The scope of the function (defaults to this JsonView)
5028  */
5029     filterBy : function(fn, scope){
5030         if(this.jsonData){
5031             var data = [];
5032             var ss = this.snapshot;
5033             for(var i = 0, len = ss.length; i < len; i++){
5034                 var o = ss[i];
5035                 if(fn.call(scope || this, o)){
5036                     data.push(o);
5037                 }
5038             }
5039             this.jsonData = data;
5040             this.refresh();
5041         }
5042     },
5043
5044 /**
5045  * Clears the current filter.
5046  */
5047     clearFilter : function(){
5048         if(this.snapshot && this.jsonData != this.snapshot){
5049             this.jsonData = this.snapshot;
5050             this.refresh();
5051         }
5052     },
5053
5054
5055 /**
5056  * Sorts the data for this view and refreshes it.
5057  * @param {String} property A property on your JSON objects to sort on
5058  * @param {String} direction (optional) "desc" or "asc" (defaults to "asc")
5059  * @param {Function} sortType (optional) A function to call to convert the data to a sortable value.
5060  */
5061     sort : function(property, dir, sortType){
5062         this.sortInfo = Array.prototype.slice.call(arguments, 0);
5063         if(this.jsonData){
5064             var p = property;
5065             var dsc = dir && dir.toLowerCase() == "desc";
5066             var f = function(o1, o2){
5067                 var v1 = sortType ? sortType(o1[p]) : o1[p];
5068                 var v2 = sortType ? sortType(o2[p]) : o2[p];
5069                 ;
5070                 if(v1 < v2){
5071                     return dsc ? +1 : -1;
5072                 } else if(v1 > v2){
5073                     return dsc ? -1 : +1;
5074                 } else{
5075                     return 0;
5076                 }
5077             };
5078             this.jsonData.sort(f);
5079             this.refresh();
5080             if(this.jsonData != this.snapshot){
5081                 this.snapshot.sort(f);
5082             }
5083         }
5084     }
5085 });/*
5086  * Based on:
5087  * Ext JS Library 1.1.1
5088  * Copyright(c) 2006-2007, Ext JS, LLC.
5089  *
5090  * Originally Released Under LGPL - original licence link has changed is not relivant.
5091  *
5092  * Fork - LGPL
5093  * <script type="text/javascript">
5094  */
5095  
5096
5097 /**
5098  * @class Roo.ColorPalette
5099  * @extends Roo.Component
5100  * Simple color palette class for choosing colors.  The palette can be rendered to any container.<br />
5101  * Here's an example of typical usage:
5102  * <pre><code>
5103 var cp = new Roo.ColorPalette({value:'993300'});  // initial selected color
5104 cp.render('my-div');
5105
5106 cp.on('select', function(palette, selColor){
5107     // do something with selColor
5108 });
5109 </code></pre>
5110  * @constructor
5111  * Create a new ColorPalette
5112  * @param {Object} config The config object
5113  */
5114 Roo.ColorPalette = function(config){
5115     Roo.ColorPalette.superclass.constructor.call(this, config);
5116     this.addEvents({
5117         /**
5118              * @event select
5119              * Fires when a color is selected
5120              * @param {ColorPalette} this
5121              * @param {String} color The 6-digit color hex code (without the # symbol)
5122              */
5123         select: true
5124     });
5125
5126     if(this.handler){
5127         this.on("select", this.handler, this.scope, true);
5128     }
5129 };
5130 Roo.extend(Roo.ColorPalette, Roo.Component, {
5131     /**
5132      * @cfg {String} itemCls
5133      * The CSS class to apply to the containing element (defaults to "x-color-palette")
5134      */
5135     itemCls : "x-color-palette",
5136     /**
5137      * @cfg {String} value
5138      * The initial color to highlight (should be a valid 6-digit color hex code without the # symbol).  Note that
5139      * the hex codes are case-sensitive.
5140      */
5141     value : null,
5142     clickEvent:'click',
5143     // private
5144     ctype: "Roo.ColorPalette",
5145
5146     /**
5147      * @cfg {Boolean} allowReselect If set to true then reselecting a color that is already selected fires the selection event
5148      */
5149     allowReselect : false,
5150
5151     /**
5152      * <p>An array of 6-digit color hex code strings (without the # symbol).  This array can contain any number
5153      * of colors, and each hex code should be unique.  The width of the palette is controlled via CSS by adjusting
5154      * the width property of the 'x-color-palette' class (or assigning a custom class), so you can balance the number
5155      * of colors with the width setting until the box is symmetrical.</p>
5156      * <p>You can override individual colors if needed:</p>
5157      * <pre><code>
5158 var cp = new Roo.ColorPalette();
5159 cp.colors[0] = "FF0000";  // change the first box to red
5160 </code></pre>
5161
5162 Or you can provide a custom array of your own for complete control:
5163 <pre><code>
5164 var cp = new Roo.ColorPalette();
5165 cp.colors = ["000000", "993300", "333300"];
5166 </code></pre>
5167      * @type Array
5168      */
5169     colors : [
5170         "000000", "993300", "333300", "003300", "003366", "000080", "333399", "333333",
5171         "800000", "FF6600", "808000", "008000", "008080", "0000FF", "666699", "808080",
5172         "FF0000", "FF9900", "99CC00", "339966", "33CCCC", "3366FF", "800080", "969696",
5173         "FF00FF", "FFCC00", "FFFF00", "00FF00", "00FFFF", "00CCFF", "993366", "C0C0C0",
5174         "FF99CC", "FFCC99", "FFFF99", "CCFFCC", "CCFFFF", "99CCFF", "CC99FF", "FFFFFF"
5175     ],
5176
5177     // private
5178     onRender : function(container, position){
5179         var t = new Roo.MasterTemplate(
5180             '<tpl><a href="#" class="color-{0}" hidefocus="on"><em><span style="background:#{0}" unselectable="on">&#160;</span></em></a></tpl>'
5181         );
5182         var c = this.colors;
5183         for(var i = 0, len = c.length; i < len; i++){
5184             t.add([c[i]]);
5185         }
5186         var el = document.createElement("div");
5187         el.className = this.itemCls;
5188         t.overwrite(el);
5189         container.dom.insertBefore(el, position);
5190         this.el = Roo.get(el);
5191         this.el.on(this.clickEvent, this.handleClick,  this, {delegate: "a"});
5192         if(this.clickEvent != 'click'){
5193             this.el.on('click', Roo.emptyFn,  this, {delegate: "a", preventDefault:true});
5194         }
5195     },
5196
5197     // private
5198     afterRender : function(){
5199         Roo.ColorPalette.superclass.afterRender.call(this);
5200         if(this.value){
5201             var s = this.value;
5202             this.value = null;
5203             this.select(s);
5204         }
5205     },
5206
5207     // private
5208     handleClick : function(e, t){
5209         e.preventDefault();
5210         if(!this.disabled){
5211             var c = t.className.match(/(?:^|\s)color-(.{6})(?:\s|$)/)[1];
5212             this.select(c.toUpperCase());
5213         }
5214     },
5215
5216     /**
5217      * Selects the specified color in the palette (fires the select event)
5218      * @param {String} color A valid 6-digit color hex code (# will be stripped if included)
5219      */
5220     select : function(color){
5221         color = color.replace("#", "");
5222         if(color != this.value || this.allowReselect){
5223             var el = this.el;
5224             if(this.value){
5225                 el.child("a.color-"+this.value).removeClass("x-color-palette-sel");
5226             }
5227             el.child("a.color-"+color).addClass("x-color-palette-sel");
5228             this.value = color;
5229             this.fireEvent("select", this, color);
5230         }
5231     }
5232 });/*
5233  * Based on:
5234  * Ext JS Library 1.1.1
5235  * Copyright(c) 2006-2007, Ext JS, LLC.
5236  *
5237  * Originally Released Under LGPL - original licence link has changed is not relivant.
5238  *
5239  * Fork - LGPL
5240  * <script type="text/javascript">
5241  */
5242  
5243 /**
5244  * @class Roo.DatePicker
5245  * @extends Roo.Component
5246  * Simple date picker class.
5247  * @constructor
5248  * Create a new DatePicker
5249  * @param {Object} config The config object
5250  */
5251 Roo.DatePicker = function(config){
5252     Roo.DatePicker.superclass.constructor.call(this, config);
5253
5254     this.value = config && config.value ?
5255                  config.value.clearTime() : new Date().clearTime();
5256
5257     this.addEvents({
5258         /**
5259              * @event select
5260              * Fires when a date is selected
5261              * @param {DatePicker} this
5262              * @param {Date} date The selected date
5263              */
5264         'select': true,
5265         /**
5266              * @event monthchange
5267              * Fires when the displayed month changes 
5268              * @param {DatePicker} this
5269              * @param {Date} date The selected month
5270              */
5271         'monthchange': true
5272     });
5273
5274     if(this.handler){
5275         this.on("select", this.handler,  this.scope || this);
5276     }
5277     // build the disabledDatesRE
5278     if(!this.disabledDatesRE && this.disabledDates){
5279         var dd = this.disabledDates;
5280         var re = "(?:";
5281         for(var i = 0; i < dd.length; i++){
5282             re += dd[i];
5283             if(i != dd.length-1) {
5284                 re += "|";
5285             }
5286         }
5287         this.disabledDatesRE = new RegExp(re + ")");
5288     }
5289 };
5290
5291 Roo.extend(Roo.DatePicker, Roo.Component, {
5292     /**
5293      * @cfg {String} todayText
5294      * The text to display on the button that selects the current date (defaults to "Today")
5295      */
5296     todayText : "Today",
5297     /**
5298      * @cfg {String} okText
5299      * The text to display on the ok button
5300      */
5301     okText : "&#160;OK&#160;", // &#160; to give the user extra clicking room
5302     /**
5303      * @cfg {String} cancelText
5304      * The text to display on the cancel button
5305      */
5306     cancelText : "Cancel",
5307     /**
5308      * @cfg {String} todayTip
5309      * The tooltip to display for the button that selects the current date (defaults to "{current date} (Spacebar)")
5310      */
5311     todayTip : "{0} (Spacebar)",
5312     /**
5313      * @cfg {Date} minDate
5314      * Minimum allowable date (JavaScript date object, defaults to null)
5315      */
5316     minDate : null,
5317     /**
5318      * @cfg {Date} maxDate
5319      * Maximum allowable date (JavaScript date object, defaults to null)
5320      */
5321     maxDate : null,
5322     /**
5323      * @cfg {String} minText
5324      * The error text to display if the minDate validation fails (defaults to "This date is before the minimum date")
5325      */
5326     minText : "This date is before the minimum date",
5327     /**
5328      * @cfg {String} maxText
5329      * The error text to display if the maxDate validation fails (defaults to "This date is after the maximum date")
5330      */
5331     maxText : "This date is after the maximum date",
5332     /**
5333      * @cfg {String} format
5334      * The default date format string which can be overriden for localization support.  The format must be
5335      * valid according to {@link Date#parseDate} (defaults to 'm/d/y').
5336      */
5337     format : "m/d/y",
5338     /**
5339      * @cfg {Array} disabledDays
5340      * An array of days to disable, 0-based. For example, [0, 6] disables Sunday and Saturday (defaults to null).
5341      */
5342     disabledDays : null,
5343     /**
5344      * @cfg {String} disabledDaysText
5345      * The tooltip to display when the date falls on a disabled day (defaults to "")
5346      */
5347     disabledDaysText : "",
5348     /**
5349      * @cfg {RegExp} disabledDatesRE
5350      * JavaScript regular expression used to disable a pattern of dates (defaults to null)
5351      */
5352     disabledDatesRE : null,
5353     /**
5354      * @cfg {String} disabledDatesText
5355      * The tooltip text to display when the date falls on a disabled date (defaults to "")
5356      */
5357     disabledDatesText : "",
5358     /**
5359      * @cfg {Boolean} constrainToViewport
5360      * True to constrain the date picker to the viewport (defaults to true)
5361      */
5362     constrainToViewport : true,
5363     /**
5364      * @cfg {Array} monthNames
5365      * An array of textual month names which can be overriden for localization support (defaults to Date.monthNames)
5366      */
5367     monthNames : Date.monthNames,
5368     /**
5369      * @cfg {Array} dayNames
5370      * An array of textual day names which can be overriden for localization support (defaults to Date.dayNames)
5371      */
5372     dayNames : Date.dayNames,
5373     /**
5374      * @cfg {String} nextText
5375      * The next month navigation button tooltip (defaults to 'Next Month (Control+Right)')
5376      */
5377     nextText: 'Next Month (Control+Right)',
5378     /**
5379      * @cfg {String} prevText
5380      * The previous month navigation button tooltip (defaults to 'Previous Month (Control+Left)')
5381      */
5382     prevText: 'Previous Month (Control+Left)',
5383     /**
5384      * @cfg {String} monthYearText
5385      * The header month selector tooltip (defaults to 'Choose a month (Control+Up/Down to move years)')
5386      */
5387     monthYearText: 'Choose a month (Control+Up/Down to move years)',
5388     /**
5389      * @cfg {Number} startDay
5390      * Day index at which the week should begin, 0-based (defaults to 0, which is Sunday)
5391      */
5392     startDay : 0,
5393     /**
5394      * @cfg {Bool} showClear
5395      * Show a clear button (usefull for date form elements that can be blank.)
5396      */
5397     
5398     showClear: false,
5399     
5400     /**
5401      * Sets the value of the date field
5402      * @param {Date} value The date to set
5403      */
5404     setValue : function(value){
5405         var old = this.value;
5406         
5407         if (typeof(value) == 'string') {
5408          
5409             value = Date.parseDate(value, this.format);
5410         }
5411         if (!value) {
5412             value = new Date();
5413         }
5414         
5415         this.value = value.clearTime(true);
5416         if(this.el){
5417             this.update(this.value);
5418         }
5419     },
5420
5421     /**
5422      * Gets the current selected value of the date field
5423      * @return {Date} The selected date
5424      */
5425     getValue : function(){
5426         return this.value;
5427     },
5428
5429     // private
5430     focus : function(){
5431         if(this.el){
5432             this.update(this.activeDate);
5433         }
5434     },
5435
5436     // privateval
5437     onRender : function(container, position){
5438         
5439         var m = [
5440              '<table cellspacing="0">',
5441                 '<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>',
5442                 '<tr><td colspan="3"><table class="x-date-inner" cellspacing="0"><thead><tr>'];
5443         var dn = this.dayNames;
5444         for(var i = 0; i < 7; i++){
5445             var d = this.startDay+i;
5446             if(d > 6){
5447                 d = d-7;
5448             }
5449             m.push("<th><span>", dn[d].substr(0,1), "</span></th>");
5450         }
5451         m[m.length] = "</tr></thead><tbody><tr>";
5452         for(var i = 0; i < 42; i++) {
5453             if(i % 7 == 0 && i != 0){
5454                 m[m.length] = "</tr><tr>";
5455             }
5456             m[m.length] = '<td><a href="#" hidefocus="on" class="x-date-date" tabIndex="1"><em><span></span></em></a></td>';
5457         }
5458         m[m.length] = '</tr></tbody></table></td></tr><tr>'+
5459             '<td colspan="3" class="x-date-bottom" align="center"></td></tr></table><div class="x-date-mp"></div>';
5460
5461         var el = document.createElement("div");
5462         el.className = "x-date-picker";
5463         el.innerHTML = m.join("");
5464
5465         container.dom.insertBefore(el, position);
5466
5467         this.el = Roo.get(el);
5468         this.eventEl = Roo.get(el.firstChild);
5469
5470         new Roo.util.ClickRepeater(this.el.child("td.x-date-left a"), {
5471             handler: this.showPrevMonth,
5472             scope: this,
5473             preventDefault:true,
5474             stopDefault:true
5475         });
5476
5477         new Roo.util.ClickRepeater(this.el.child("td.x-date-right a"), {
5478             handler: this.showNextMonth,
5479             scope: this,
5480             preventDefault:true,
5481             stopDefault:true
5482         });
5483
5484         this.eventEl.on("mousewheel", this.handleMouseWheel,  this);
5485
5486         this.monthPicker = this.el.down('div.x-date-mp');
5487         this.monthPicker.enableDisplayMode('block');
5488         
5489         var kn = new Roo.KeyNav(this.eventEl, {
5490             "left" : function(e){
5491                 e.ctrlKey ?
5492                     this.showPrevMonth() :
5493                     this.update(this.activeDate.add("d", -1));
5494             },
5495
5496             "right" : function(e){
5497                 e.ctrlKey ?
5498                     this.showNextMonth() :
5499                     this.update(this.activeDate.add("d", 1));
5500             },
5501
5502             "up" : function(e){
5503                 e.ctrlKey ?
5504                     this.showNextYear() :
5505                     this.update(this.activeDate.add("d", -7));
5506             },
5507
5508             "down" : function(e){
5509                 e.ctrlKey ?
5510                     this.showPrevYear() :
5511                     this.update(this.activeDate.add("d", 7));
5512             },
5513
5514             "pageUp" : function(e){
5515                 this.showNextMonth();
5516             },
5517
5518             "pageDown" : function(e){
5519                 this.showPrevMonth();
5520             },
5521
5522             "enter" : function(e){
5523                 e.stopPropagation();
5524                 return true;
5525             },
5526
5527             scope : this
5528         });
5529
5530         this.eventEl.on("click", this.handleDateClick,  this, {delegate: "a.x-date-date"});
5531
5532         this.eventEl.addKeyListener(Roo.EventObject.SPACE, this.selectToday,  this);
5533
5534         this.el.unselectable();
5535         
5536         this.cells = this.el.select("table.x-date-inner tbody td");
5537         this.textNodes = this.el.query("table.x-date-inner tbody span");
5538
5539         this.mbtn = new Roo.Button(this.el.child("td.x-date-middle", true), {
5540             text: "&#160;",
5541             tooltip: this.monthYearText
5542         });
5543
5544         this.mbtn.on('click', this.showMonthPicker, this);
5545         this.mbtn.el.child(this.mbtn.menuClassTarget).addClass("x-btn-with-menu");
5546
5547
5548         var today = (new Date()).dateFormat(this.format);
5549         
5550         var baseTb = new Roo.Toolbar(this.el.child("td.x-date-bottom", true));
5551         if (this.showClear) {
5552             baseTb.add( new Roo.Toolbar.Fill());
5553         }
5554         baseTb.add({
5555             text: String.format(this.todayText, today),
5556             tooltip: String.format(this.todayTip, today),
5557             handler: this.selectToday,
5558             scope: this
5559         });
5560         
5561         //var todayBtn = new Roo.Button(this.el.child("td.x-date-bottom", true), {
5562             
5563         //});
5564         if (this.showClear) {
5565             
5566             baseTb.add( new Roo.Toolbar.Fill());
5567             baseTb.add({
5568                 text: '&#160;',
5569                 cls: 'x-btn-icon x-btn-clear',
5570                 handler: function() {
5571                     //this.value = '';
5572                     this.fireEvent("select", this, '');
5573                 },
5574                 scope: this
5575             });
5576         }
5577         
5578         
5579         if(Roo.isIE){
5580             this.el.repaint();
5581         }
5582         this.update(this.value);
5583     },
5584
5585     createMonthPicker : function(){
5586         if(!this.monthPicker.dom.firstChild){
5587             var buf = ['<table border="0" cellspacing="0">'];
5588             for(var i = 0; i < 6; i++){
5589                 buf.push(
5590                     '<tr><td class="x-date-mp-month"><a href="#">', this.monthNames[i].substr(0, 3), '</a></td>',
5591                     '<td class="x-date-mp-month x-date-mp-sep"><a href="#">', this.monthNames[i+6].substr(0, 3), '</a></td>',
5592                     i == 0 ?
5593                     '<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>' :
5594                     '<td class="x-date-mp-year"><a href="#"></a></td><td class="x-date-mp-year"><a href="#"></a></td></tr>'
5595                 );
5596             }
5597             buf.push(
5598                 '<tr class="x-date-mp-btns"><td colspan="4"><button type="button" class="x-date-mp-ok">',
5599                     this.okText,
5600                     '</button><button type="button" class="x-date-mp-cancel">',
5601                     this.cancelText,
5602                     '</button></td></tr>',
5603                 '</table>'
5604             );
5605             this.monthPicker.update(buf.join(''));
5606             this.monthPicker.on('click', this.onMonthClick, this);
5607             this.monthPicker.on('dblclick', this.onMonthDblClick, this);
5608
5609             this.mpMonths = this.monthPicker.select('td.x-date-mp-month');
5610             this.mpYears = this.monthPicker.select('td.x-date-mp-year');
5611
5612             this.mpMonths.each(function(m, a, i){
5613                 i += 1;
5614                 if((i%2) == 0){
5615                     m.dom.xmonth = 5 + Math.round(i * .5);
5616                 }else{
5617                     m.dom.xmonth = Math.round((i-1) * .5);
5618                 }
5619             });
5620         }
5621     },
5622
5623     showMonthPicker : function(){
5624         this.createMonthPicker();
5625         var size = this.el.getSize();
5626         this.monthPicker.setSize(size);
5627         this.monthPicker.child('table').setSize(size);
5628
5629         this.mpSelMonth = (this.activeDate || this.value).getMonth();
5630         this.updateMPMonth(this.mpSelMonth);
5631         this.mpSelYear = (this.activeDate || this.value).getFullYear();
5632         this.updateMPYear(this.mpSelYear);
5633
5634         this.monthPicker.slideIn('t', {duration:.2});
5635     },
5636
5637     updateMPYear : function(y){
5638         this.mpyear = y;
5639         var ys = this.mpYears.elements;
5640         for(var i = 1; i <= 10; i++){
5641             var td = ys[i-1], y2;
5642             if((i%2) == 0){
5643                 y2 = y + Math.round(i * .5);
5644                 td.firstChild.innerHTML = y2;
5645                 td.xyear = y2;
5646             }else{
5647                 y2 = y - (5-Math.round(i * .5));
5648                 td.firstChild.innerHTML = y2;
5649                 td.xyear = y2;
5650             }
5651             this.mpYears.item(i-1)[y2 == this.mpSelYear ? 'addClass' : 'removeClass']('x-date-mp-sel');
5652         }
5653     },
5654
5655     updateMPMonth : function(sm){
5656         this.mpMonths.each(function(m, a, i){
5657             m[m.dom.xmonth == sm ? 'addClass' : 'removeClass']('x-date-mp-sel');
5658         });
5659     },
5660
5661     selectMPMonth: function(m){
5662         
5663     },
5664
5665     onMonthClick : function(e, t){
5666         e.stopEvent();
5667         var el = new Roo.Element(t), pn;
5668         if(el.is('button.x-date-mp-cancel')){
5669             this.hideMonthPicker();
5670         }
5671         else if(el.is('button.x-date-mp-ok')){
5672             this.update(new Date(this.mpSelYear, this.mpSelMonth, (this.activeDate || this.value).getDate()));
5673             this.hideMonthPicker();
5674         }
5675         else if(pn = el.up('td.x-date-mp-month', 2)){
5676             this.mpMonths.removeClass('x-date-mp-sel');
5677             pn.addClass('x-date-mp-sel');
5678             this.mpSelMonth = pn.dom.xmonth;
5679         }
5680         else if(pn = el.up('td.x-date-mp-year', 2)){
5681             this.mpYears.removeClass('x-date-mp-sel');
5682             pn.addClass('x-date-mp-sel');
5683             this.mpSelYear = pn.dom.xyear;
5684         }
5685         else if(el.is('a.x-date-mp-prev')){
5686             this.updateMPYear(this.mpyear-10);
5687         }
5688         else if(el.is('a.x-date-mp-next')){
5689             this.updateMPYear(this.mpyear+10);
5690         }
5691     },
5692
5693     onMonthDblClick : function(e, t){
5694         e.stopEvent();
5695         var el = new Roo.Element(t), pn;
5696         if(pn = el.up('td.x-date-mp-month', 2)){
5697             this.update(new Date(this.mpSelYear, pn.dom.xmonth, (this.activeDate || this.value).getDate()));
5698             this.hideMonthPicker();
5699         }
5700         else if(pn = el.up('td.x-date-mp-year', 2)){
5701             this.update(new Date(pn.dom.xyear, this.mpSelMonth, (this.activeDate || this.value).getDate()));
5702             this.hideMonthPicker();
5703         }
5704     },
5705
5706     hideMonthPicker : function(disableAnim){
5707         if(this.monthPicker){
5708             if(disableAnim === true){
5709                 this.monthPicker.hide();
5710             }else{
5711                 this.monthPicker.slideOut('t', {duration:.2});
5712             }
5713         }
5714     },
5715
5716     // private
5717     showPrevMonth : function(e){
5718         this.update(this.activeDate.add("mo", -1));
5719     },
5720
5721     // private
5722     showNextMonth : function(e){
5723         this.update(this.activeDate.add("mo", 1));
5724     },
5725
5726     // private
5727     showPrevYear : function(){
5728         this.update(this.activeDate.add("y", -1));
5729     },
5730
5731     // private
5732     showNextYear : function(){
5733         this.update(this.activeDate.add("y", 1));
5734     },
5735
5736     // private
5737     handleMouseWheel : function(e){
5738         var delta = e.getWheelDelta();
5739         if(delta > 0){
5740             this.showPrevMonth();
5741             e.stopEvent();
5742         } else if(delta < 0){
5743             this.showNextMonth();
5744             e.stopEvent();
5745         }
5746     },
5747
5748     // private
5749     handleDateClick : function(e, t){
5750         e.stopEvent();
5751         if(t.dateValue && !Roo.fly(t.parentNode).hasClass("x-date-disabled")){
5752             this.setValue(new Date(t.dateValue));
5753             this.fireEvent("select", this, this.value);
5754         }
5755     },
5756
5757     // private
5758     selectToday : function(){
5759         this.setValue(new Date().clearTime());
5760         this.fireEvent("select", this, this.value);
5761     },
5762
5763     // private
5764     update : function(date)
5765     {
5766         var vd = this.activeDate;
5767         this.activeDate = date;
5768         if(vd && this.el){
5769             var t = date.getTime();
5770             if(vd.getMonth() == date.getMonth() && vd.getFullYear() == date.getFullYear()){
5771                 this.cells.removeClass("x-date-selected");
5772                 this.cells.each(function(c){
5773                    if(c.dom.firstChild.dateValue == t){
5774                        c.addClass("x-date-selected");
5775                        setTimeout(function(){
5776                             try{c.dom.firstChild.focus();}catch(e){}
5777                        }, 50);
5778                        return false;
5779                    }
5780                 });
5781                 return;
5782             }
5783         }
5784         
5785         var days = date.getDaysInMonth();
5786         var firstOfMonth = date.getFirstDateOfMonth();
5787         var startingPos = firstOfMonth.getDay()-this.startDay;
5788
5789         if(startingPos <= this.startDay){
5790             startingPos += 7;
5791         }
5792
5793         var pm = date.add("mo", -1);
5794         var prevStart = pm.getDaysInMonth()-startingPos;
5795
5796         var cells = this.cells.elements;
5797         var textEls = this.textNodes;
5798         days += startingPos;
5799
5800         // convert everything to numbers so it's fast
5801         var day = 86400000;
5802         var d = (new Date(pm.getFullYear(), pm.getMonth(), prevStart)).clearTime();
5803         var today = new Date().clearTime().getTime();
5804         var sel = date.clearTime().getTime();
5805         var min = this.minDate ? this.minDate.clearTime() : Number.NEGATIVE_INFINITY;
5806         var max = this.maxDate ? this.maxDate.clearTime() : Number.POSITIVE_INFINITY;
5807         var ddMatch = this.disabledDatesRE;
5808         var ddText = this.disabledDatesText;
5809         var ddays = this.disabledDays ? this.disabledDays.join("") : false;
5810         var ddaysText = this.disabledDaysText;
5811         var format = this.format;
5812
5813         var setCellClass = function(cal, cell){
5814             cell.title = "";
5815             var t = d.getTime();
5816             cell.firstChild.dateValue = t;
5817             if(t == today){
5818                 cell.className += " x-date-today";
5819                 cell.title = cal.todayText;
5820             }
5821             if(t == sel){
5822                 cell.className += " x-date-selected";
5823                 setTimeout(function(){
5824                     try{cell.firstChild.focus();}catch(e){}
5825                 }, 50);
5826             }
5827             // disabling
5828             if(t < min) {
5829                 cell.className = " x-date-disabled";
5830                 cell.title = cal.minText;
5831                 return;
5832             }
5833             if(t > max) {
5834                 cell.className = " x-date-disabled";
5835                 cell.title = cal.maxText;
5836                 return;
5837             }
5838             if(ddays){
5839                 if(ddays.indexOf(d.getDay()) != -1){
5840                     cell.title = ddaysText;
5841                     cell.className = " x-date-disabled";
5842                 }
5843             }
5844             if(ddMatch && format){
5845                 var fvalue = d.dateFormat(format);
5846                 if(ddMatch.test(fvalue)){
5847                     cell.title = ddText.replace("%0", fvalue);
5848                     cell.className = " x-date-disabled";
5849                 }
5850             }
5851         };
5852
5853         var i = 0;
5854         for(; i < startingPos; i++) {
5855             textEls[i].innerHTML = (++prevStart);
5856             d.setDate(d.getDate()+1);
5857             cells[i].className = "x-date-prevday";
5858             setCellClass(this, cells[i]);
5859         }
5860         for(; i < days; i++){
5861             intDay = i - startingPos + 1;
5862             textEls[i].innerHTML = (intDay);
5863             d.setDate(d.getDate()+1);
5864             cells[i].className = "x-date-active";
5865             setCellClass(this, cells[i]);
5866         }
5867         var extraDays = 0;
5868         for(; i < 42; i++) {
5869              textEls[i].innerHTML = (++extraDays);
5870              d.setDate(d.getDate()+1);
5871              cells[i].className = "x-date-nextday";
5872              setCellClass(this, cells[i]);
5873         }
5874
5875         this.mbtn.setText(this.monthNames[date.getMonth()] + " " + date.getFullYear());
5876         this.fireEvent('monthchange', this, date);
5877         
5878         if(!this.internalRender){
5879             var main = this.el.dom.firstChild;
5880             var w = main.offsetWidth;
5881             this.el.setWidth(w + this.el.getBorderWidth("lr"));
5882             Roo.fly(main).setWidth(w);
5883             this.internalRender = true;
5884             // opera does not respect the auto grow header center column
5885             // then, after it gets a width opera refuses to recalculate
5886             // without a second pass
5887             if(Roo.isOpera && !this.secondPass){
5888                 main.rows[0].cells[1].style.width = (w - (main.rows[0].cells[0].offsetWidth+main.rows[0].cells[2].offsetWidth)) + "px";
5889                 this.secondPass = true;
5890                 this.update.defer(10, this, [date]);
5891             }
5892         }
5893         
5894         
5895     }
5896 });        /*
5897  * Based on:
5898  * Ext JS Library 1.1.1
5899  * Copyright(c) 2006-2007, Ext JS, LLC.
5900  *
5901  * Originally Released Under LGPL - original licence link has changed is not relivant.
5902  *
5903  * Fork - LGPL
5904  * <script type="text/javascript">
5905  */
5906 /**
5907  * @class Roo.TabPanel
5908  * @extends Roo.util.Observable
5909  * A lightweight tab container.
5910  * <br><br>
5911  * Usage:
5912  * <pre><code>
5913 // basic tabs 1, built from existing content
5914 var tabs = new Roo.TabPanel("tabs1");
5915 tabs.addTab("script", "View Script");
5916 tabs.addTab("markup", "View Markup");
5917 tabs.activate("script");
5918
5919 // more advanced tabs, built from javascript
5920 var jtabs = new Roo.TabPanel("jtabs");
5921 jtabs.addTab("jtabs-1", "Normal Tab", "My content was added during construction.");
5922
5923 // set up the UpdateManager
5924 var tab2 = jtabs.addTab("jtabs-2", "Ajax Tab 1");
5925 var updater = tab2.getUpdateManager();
5926 updater.setDefaultUrl("ajax1.htm");
5927 tab2.on('activate', updater.refresh, updater, true);
5928
5929 // Use setUrl for Ajax loading
5930 var tab3 = jtabs.addTab("jtabs-3", "Ajax Tab 2");
5931 tab3.setUrl("ajax2.htm", null, true);
5932
5933 // Disabled tab
5934 var tab4 = jtabs.addTab("tabs1-5", "Disabled Tab", "Can't see me cause I'm disabled");
5935 tab4.disable();
5936
5937 jtabs.activate("jtabs-1");
5938  * </code></pre>
5939  * @constructor
5940  * Create a new TabPanel.
5941  * @param {String/HTMLElement/Roo.Element} container The id, DOM element or Roo.Element container where this TabPanel is to be rendered.
5942  * @param {Object/Boolean} config Config object to set any properties for this TabPanel, or true to render the tabs on the bottom.
5943  */
5944 Roo.TabPanel = function(container, config){
5945     /**
5946     * The container element for this TabPanel.
5947     * @type Roo.Element
5948     */
5949     this.el = Roo.get(container, true);
5950     if(config){
5951         if(typeof config == "boolean"){
5952             this.tabPosition = config ? "bottom" : "top";
5953         }else{
5954             Roo.apply(this, config);
5955         }
5956     }
5957     if(this.tabPosition == "bottom"){
5958         this.bodyEl = Roo.get(this.createBody(this.el.dom));
5959         this.el.addClass("x-tabs-bottom");
5960     }
5961     this.stripWrap = Roo.get(this.createStrip(this.el.dom), true);
5962     this.stripEl = Roo.get(this.createStripList(this.stripWrap.dom), true);
5963     this.stripBody = Roo.get(this.stripWrap.dom.firstChild.firstChild, true);
5964     if(Roo.isIE){
5965         Roo.fly(this.stripWrap.dom.firstChild).setStyle("overflow-x", "hidden");
5966     }
5967     if(this.tabPosition != "bottom"){
5968         /** The body element that contains {@link Roo.TabPanelItem} bodies. +
5969          * @type Roo.Element
5970          */
5971         this.bodyEl = Roo.get(this.createBody(this.el.dom));
5972         this.el.addClass("x-tabs-top");
5973     }
5974     this.items = [];
5975
5976     this.bodyEl.setStyle("position", "relative");
5977
5978     this.active = null;
5979     this.activateDelegate = this.activate.createDelegate(this);
5980
5981     this.addEvents({
5982         /**
5983          * @event tabchange
5984          * Fires when the active tab changes
5985          * @param {Roo.TabPanel} this
5986          * @param {Roo.TabPanelItem} activePanel The new active tab
5987          */
5988         "tabchange": true,
5989         /**
5990          * @event beforetabchange
5991          * Fires before the active tab changes, set cancel to true on the "e" parameter to cancel the change
5992          * @param {Roo.TabPanel} this
5993          * @param {Object} e Set cancel to true on this object to cancel the tab change
5994          * @param {Roo.TabPanelItem} tab The tab being changed to
5995          */
5996         "beforetabchange" : true
5997     });
5998
5999     Roo.EventManager.onWindowResize(this.onResize, this);
6000     this.cpad = this.el.getPadding("lr");
6001     this.hiddenCount = 0;
6002
6003
6004     // toolbar on the tabbar support...
6005     if (this.toolbar) {
6006         var tcfg = this.toolbar;
6007         tcfg.container = this.stripEl.child('td.x-tab-strip-toolbar');  
6008         this.toolbar = new Roo.Toolbar(tcfg);
6009         if (Roo.isSafari) {
6010             var tbl = tcfg.container.child('table', true);
6011             tbl.setAttribute('width', '100%');
6012         }
6013         
6014     }
6015    
6016
6017
6018     Roo.TabPanel.superclass.constructor.call(this);
6019 };
6020
6021 Roo.extend(Roo.TabPanel, Roo.util.Observable, {
6022     /*
6023      *@cfg {String} tabPosition "top" or "bottom" (defaults to "top")
6024      */
6025     tabPosition : "top",
6026     /*
6027      *@cfg {Number} currentTabWidth The width of the current tab (defaults to 0)
6028      */
6029     currentTabWidth : 0,
6030     /*
6031      *@cfg {Number} minTabWidth The minimum width of a tab (defaults to 40) (ignored if {@link #resizeTabs} is not true)
6032      */
6033     minTabWidth : 40,
6034     /*
6035      *@cfg {Number} maxTabWidth The maximum width of a tab (defaults to 250) (ignored if {@link #resizeTabs} is not true)
6036      */
6037     maxTabWidth : 250,
6038     /*
6039      *@cfg {Number} preferredTabWidth The preferred (default) width of a tab (defaults to 175) (ignored if {@link #resizeTabs} is not true)
6040      */
6041     preferredTabWidth : 175,
6042     /*
6043      *@cfg {Boolean} resizeTabs True to enable dynamic tab resizing (defaults to false)
6044      */
6045     resizeTabs : false,
6046     /*
6047      *@cfg {Boolean} monitorResize Set this to true to turn on window resize monitoring (ignored if {@link #resizeTabs} is not true) (defaults to true)
6048      */
6049     monitorResize : true,
6050     /*
6051      *@cfg {Object} toolbar xtype description of toolbar to show at the right of the tab bar. 
6052      */
6053     toolbar : false,
6054
6055     /**
6056      * Creates a new {@link Roo.TabPanelItem} by looking for an existing element with the provided id -- if it's not found it creates one.
6057      * @param {String} id The id of the div to use <b>or create</b>
6058      * @param {String} text The text for the tab
6059      * @param {String} content (optional) Content to put in the TabPanelItem body
6060      * @param {Boolean} closable (optional) True to create a close icon on the tab
6061      * @return {Roo.TabPanelItem} The created TabPanelItem
6062      */
6063     addTab : function(id, text, content, closable){
6064         var item = new Roo.TabPanelItem(this, id, text, closable);
6065         this.addTabItem(item);
6066         if(content){
6067             item.setContent(content);
6068         }
6069         return item;
6070     },
6071
6072     /**
6073      * Returns the {@link Roo.TabPanelItem} with the specified id/index
6074      * @param {String/Number} id The id or index of the TabPanelItem to fetch.
6075      * @return {Roo.TabPanelItem}
6076      */
6077     getTab : function(id){
6078         return this.items[id];
6079     },
6080
6081     /**
6082      * Hides the {@link Roo.TabPanelItem} with the specified id/index
6083      * @param {String/Number} id The id or index of the TabPanelItem to hide.
6084      */
6085     hideTab : function(id){
6086         var t = this.items[id];
6087         if(!t.isHidden()){
6088            t.setHidden(true);
6089            this.hiddenCount++;
6090            this.autoSizeTabs();
6091         }
6092     },
6093
6094     /**
6095      * "Unhides" the {@link Roo.TabPanelItem} with the specified id/index.
6096      * @param {String/Number} id The id or index of the TabPanelItem to unhide.
6097      */
6098     unhideTab : function(id){
6099         var t = this.items[id];
6100         if(t.isHidden()){
6101            t.setHidden(false);
6102            this.hiddenCount--;
6103            this.autoSizeTabs();
6104         }
6105     },
6106
6107     /**
6108      * Adds an existing {@link Roo.TabPanelItem}.
6109      * @param {Roo.TabPanelItem} item The TabPanelItem to add
6110      */
6111     addTabItem : function(item){
6112         this.items[item.id] = item;
6113         this.items.push(item);
6114         if(this.resizeTabs){
6115            item.setWidth(this.currentTabWidth || this.preferredTabWidth);
6116            this.autoSizeTabs();
6117         }else{
6118             item.autoSize();
6119         }
6120     },
6121
6122     /**
6123      * Removes a {@link Roo.TabPanelItem}.
6124      * @param {String/Number} id The id or index of the TabPanelItem to remove.
6125      */
6126     removeTab : function(id){
6127         var items = this.items;
6128         var tab = items[id];
6129         if(!tab) { return; }
6130         var index = items.indexOf(tab);
6131         if(this.active == tab && items.length > 1){
6132             var newTab = this.getNextAvailable(index);
6133             if(newTab) {
6134                 newTab.activate();
6135             }
6136         }
6137         this.stripEl.dom.removeChild(tab.pnode.dom);
6138         if(tab.bodyEl.dom.parentNode == this.bodyEl.dom){ // if it was moved already prevent error
6139             this.bodyEl.dom.removeChild(tab.bodyEl.dom);
6140         }
6141         items.splice(index, 1);
6142         delete this.items[tab.id];
6143         tab.fireEvent("close", tab);
6144         tab.purgeListeners();
6145         this.autoSizeTabs();
6146     },
6147
6148     getNextAvailable : function(start){
6149         var items = this.items;
6150         var index = start;
6151         // look for a next tab that will slide over to
6152         // replace the one being removed
6153         while(index < items.length){
6154             var item = items[++index];
6155             if(item && !item.isHidden()){
6156                 return item;
6157             }
6158         }
6159         // if one isn't found select the previous tab (on the left)
6160         index = start;
6161         while(index >= 0){
6162             var item = items[--index];
6163             if(item && !item.isHidden()){
6164                 return item;
6165             }
6166         }
6167         return null;
6168     },
6169
6170     /**
6171      * Disables a {@link Roo.TabPanelItem}. It cannot be the active tab, if it is this call is ignored.
6172      * @param {String/Number} id The id or index of the TabPanelItem to disable.
6173      */
6174     disableTab : function(id){
6175         var tab = this.items[id];
6176         if(tab && this.active != tab){
6177             tab.disable();
6178         }
6179     },
6180
6181     /**
6182      * Enables a {@link Roo.TabPanelItem} that is disabled.
6183      * @param {String/Number} id The id or index of the TabPanelItem to enable.
6184      */
6185     enableTab : function(id){
6186         var tab = this.items[id];
6187         tab.enable();
6188     },
6189
6190     /**
6191      * Activates a {@link Roo.TabPanelItem}. The currently active one will be deactivated.
6192      * @param {String/Number} id The id or index of the TabPanelItem to activate.
6193      * @return {Roo.TabPanelItem} The TabPanelItem.
6194      */
6195     activate : function(id){
6196         var tab = this.items[id];
6197         if(!tab){
6198             return null;
6199         }
6200         if(tab == this.active || tab.disabled){
6201             return tab;
6202         }
6203         var e = {};
6204         this.fireEvent("beforetabchange", this, e, tab);
6205         if(e.cancel !== true && !tab.disabled){
6206             if(this.active){
6207                 this.active.hide();
6208             }
6209             this.active = this.items[id];
6210             this.active.show();
6211             this.fireEvent("tabchange", this, this.active);
6212         }
6213         return tab;
6214     },
6215
6216     /**
6217      * Gets the active {@link Roo.TabPanelItem}.
6218      * @return {Roo.TabPanelItem} The active TabPanelItem or null if none are active.
6219      */
6220     getActiveTab : function(){
6221         return this.active;
6222     },
6223
6224     /**
6225      * Updates the tab body element to fit the height of the container element
6226      * for overflow scrolling
6227      * @param {Number} targetHeight (optional) Override the starting height from the elements height
6228      */
6229     syncHeight : function(targetHeight){
6230         var height = (targetHeight || this.el.getHeight())-this.el.getBorderWidth("tb")-this.el.getPadding("tb");
6231         var bm = this.bodyEl.getMargins();
6232         var newHeight = height-(this.stripWrap.getHeight()||0)-(bm.top+bm.bottom);
6233         this.bodyEl.setHeight(newHeight);
6234         return newHeight;
6235     },
6236
6237     onResize : function(){
6238         if(this.monitorResize){
6239             this.autoSizeTabs();
6240         }
6241     },
6242
6243     /**
6244      * Disables tab resizing while tabs are being added (if {@link #resizeTabs} is false this does nothing)
6245      */
6246     beginUpdate : function(){
6247         this.updating = true;
6248     },
6249
6250     /**
6251      * Stops an update and resizes the tabs (if {@link #resizeTabs} is false this does nothing)
6252      */
6253     endUpdate : function(){
6254         this.updating = false;
6255         this.autoSizeTabs();
6256     },
6257
6258     /**
6259      * Manual call to resize the tabs (if {@link #resizeTabs} is false this does nothing)
6260      */
6261     autoSizeTabs : function(){
6262         var count = this.items.length;
6263         var vcount = count - this.hiddenCount;
6264         if(!this.resizeTabs || count < 1 || vcount < 1 || this.updating) {
6265             return;
6266         }
6267         var w = Math.max(this.el.getWidth() - this.cpad, 10);
6268         var availWidth = Math.floor(w / vcount);
6269         var b = this.stripBody;
6270         if(b.getWidth() > w){
6271             var tabs = this.items;
6272             this.setTabWidth(Math.max(availWidth, this.minTabWidth)-2);
6273             if(availWidth < this.minTabWidth){
6274                 /*if(!this.sleft){    // incomplete scrolling code
6275                     this.createScrollButtons();
6276                 }
6277                 this.showScroll();
6278                 this.stripClip.setWidth(w - (this.sleft.getWidth()+this.sright.getWidth()));*/
6279             }
6280         }else{
6281             if(this.currentTabWidth < this.preferredTabWidth){
6282                 this.setTabWidth(Math.min(availWidth, this.preferredTabWidth)-2);
6283             }
6284         }
6285     },
6286
6287     /**
6288      * Returns the number of tabs in this TabPanel.
6289      * @return {Number}
6290      */
6291      getCount : function(){
6292          return this.items.length;
6293      },
6294
6295     /**
6296      * Resizes all the tabs to the passed width
6297      * @param {Number} The new width
6298      */
6299     setTabWidth : function(width){
6300         this.currentTabWidth = width;
6301         for(var i = 0, len = this.items.length; i < len; i++) {
6302                 if(!this.items[i].isHidden()) {
6303                 this.items[i].setWidth(width);
6304             }
6305         }
6306     },
6307
6308     /**
6309      * Destroys this TabPanel
6310      * @param {Boolean} removeEl (optional) True to remove the element from the DOM as well (defaults to undefined)
6311      */
6312     destroy : function(removeEl){
6313         Roo.EventManager.removeResizeListener(this.onResize, this);
6314         for(var i = 0, len = this.items.length; i < len; i++){
6315             this.items[i].purgeListeners();
6316         }
6317         if(removeEl === true){
6318             this.el.update("");
6319             this.el.remove();
6320         }
6321     }
6322 });
6323
6324 /**
6325  * @class Roo.TabPanelItem
6326  * @extends Roo.util.Observable
6327  * Represents an individual item (tab plus body) in a TabPanel.
6328  * @param {Roo.TabPanel} tabPanel The {@link Roo.TabPanel} this TabPanelItem belongs to
6329  * @param {String} id The id of this TabPanelItem
6330  * @param {String} text The text for the tab of this TabPanelItem
6331  * @param {Boolean} closable True to allow this TabPanelItem to be closable (defaults to false)
6332  */
6333 Roo.TabPanelItem = function(tabPanel, id, text, closable){
6334     /**
6335      * The {@link Roo.TabPanel} this TabPanelItem belongs to
6336      * @type Roo.TabPanel
6337      */
6338     this.tabPanel = tabPanel;
6339     /**
6340      * The id for this TabPanelItem
6341      * @type String
6342      */
6343     this.id = id;
6344     /** @private */
6345     this.disabled = false;
6346     /** @private */
6347     this.text = text;
6348     /** @private */
6349     this.loaded = false;
6350     this.closable = closable;
6351
6352     /**
6353      * The body element for this TabPanelItem.
6354      * @type Roo.Element
6355      */
6356     this.bodyEl = Roo.get(tabPanel.createItemBody(tabPanel.bodyEl.dom, id));
6357     this.bodyEl.setVisibilityMode(Roo.Element.VISIBILITY);
6358     this.bodyEl.setStyle("display", "block");
6359     this.bodyEl.setStyle("zoom", "1");
6360     this.hideAction();
6361
6362     var els = tabPanel.createStripElements(tabPanel.stripEl.dom, text, closable);
6363     /** @private */
6364     this.el = Roo.get(els.el, true);
6365     this.inner = Roo.get(els.inner, true);
6366     this.textEl = Roo.get(this.el.dom.firstChild.firstChild.firstChild, true);
6367     this.pnode = Roo.get(els.el.parentNode, true);
6368     this.el.on("mousedown", this.onTabMouseDown, this);
6369     this.el.on("click", this.onTabClick, this);
6370     /** @private */
6371     if(closable){
6372         var c = Roo.get(els.close, true);
6373         c.dom.title = this.closeText;
6374         c.addClassOnOver("close-over");
6375         c.on("click", this.closeClick, this);
6376      }
6377
6378     this.addEvents({
6379          /**
6380          * @event activate
6381          * Fires when this tab becomes the active tab.
6382          * @param {Roo.TabPanel} tabPanel The parent TabPanel
6383          * @param {Roo.TabPanelItem} this
6384          */
6385         "activate": true,
6386         /**
6387          * @event beforeclose
6388          * Fires before this tab is closed. To cancel the close, set cancel to true on e (e.cancel = true).
6389          * @param {Roo.TabPanelItem} this
6390          * @param {Object} e Set cancel to true on this object to cancel the close.
6391          */
6392         "beforeclose": true,
6393         /**
6394          * @event close
6395          * Fires when this tab is closed.
6396          * @param {Roo.TabPanelItem} this
6397          */
6398          "close": true,
6399         /**
6400          * @event deactivate
6401          * Fires when this tab is no longer the active tab.
6402          * @param {Roo.TabPanel} tabPanel The parent TabPanel
6403          * @param {Roo.TabPanelItem} this
6404          */
6405          "deactivate" : true
6406     });
6407     this.hidden = false;
6408
6409     Roo.TabPanelItem.superclass.constructor.call(this);
6410 };
6411
6412 Roo.extend(Roo.TabPanelItem, Roo.util.Observable, {
6413     purgeListeners : function(){
6414        Roo.util.Observable.prototype.purgeListeners.call(this);
6415        this.el.removeAllListeners();
6416     },
6417     /**
6418      * Shows this TabPanelItem -- this <b>does not</b> deactivate the currently active TabPanelItem.
6419      */
6420     show : function(){
6421         this.pnode.addClass("on");
6422         this.showAction();
6423         if(Roo.isOpera){
6424             this.tabPanel.stripWrap.repaint();
6425         }
6426         this.fireEvent("activate", this.tabPanel, this);
6427     },
6428
6429     /**
6430      * Returns true if this tab is the active tab.
6431      * @return {Boolean}
6432      */
6433     isActive : function(){
6434         return this.tabPanel.getActiveTab() == this;
6435     },
6436
6437     /**
6438      * Hides this TabPanelItem -- if you don't activate another TabPanelItem this could look odd.
6439      */
6440     hide : function(){
6441         this.pnode.removeClass("on");
6442         this.hideAction();
6443         this.fireEvent("deactivate", this.tabPanel, this);
6444     },
6445
6446     hideAction : function(){
6447         this.bodyEl.hide();
6448         this.bodyEl.setStyle("position", "absolute");
6449         this.bodyEl.setLeft("-20000px");
6450         this.bodyEl.setTop("-20000px");
6451     },
6452
6453     showAction : function(){
6454         this.bodyEl.setStyle("position", "relative");
6455         this.bodyEl.setTop("");
6456         this.bodyEl.setLeft("");
6457         this.bodyEl.show();
6458     },
6459
6460     /**
6461      * Set the tooltip for the tab.
6462      * @param {String} tooltip The tab's tooltip
6463      */
6464     setTooltip : function(text){
6465         if(Roo.QuickTips && Roo.QuickTips.isEnabled()){
6466             this.textEl.dom.qtip = text;
6467             this.textEl.dom.removeAttribute('title');
6468         }else{
6469             this.textEl.dom.title = text;
6470         }
6471     },
6472
6473     onTabClick : function(e){
6474         e.preventDefault();
6475         this.tabPanel.activate(this.id);
6476     },
6477
6478     onTabMouseDown : function(e){
6479         e.preventDefault();
6480         this.tabPanel.activate(this.id);
6481     },
6482
6483     getWidth : function(){
6484         return this.inner.getWidth();
6485     },
6486
6487     setWidth : function(width){
6488         var iwidth = width - this.pnode.getPadding("lr");
6489         this.inner.setWidth(iwidth);
6490         this.textEl.setWidth(iwidth-this.inner.getPadding("lr"));
6491         this.pnode.setWidth(width);
6492     },
6493
6494     /**
6495      * Show or hide the tab
6496      * @param {Boolean} hidden True to hide or false to show.
6497      */
6498     setHidden : function(hidden){
6499         this.hidden = hidden;
6500         this.pnode.setStyle("display", hidden ? "none" : "");
6501     },
6502
6503     /**
6504      * Returns true if this tab is "hidden"
6505      * @return {Boolean}
6506      */
6507     isHidden : function(){
6508         return this.hidden;
6509     },
6510
6511     /**
6512      * Returns the text for this tab
6513      * @return {String}
6514      */
6515     getText : function(){
6516         return this.text;
6517     },
6518
6519     autoSize : function(){
6520         //this.el.beginMeasure();
6521         this.textEl.setWidth(1);
6522         /*
6523          *  #2804 [new] Tabs in Roojs
6524          *  increase the width by 2-4 pixels to prevent the ellipssis showing in chrome
6525          */
6526         this.setWidth(this.textEl.dom.scrollWidth+this.pnode.getPadding("lr")+this.inner.getPadding("lr") + 2);
6527         //this.el.endMeasure();
6528     },
6529
6530     /**
6531      * Sets the text for the tab (Note: this also sets the tooltip text)
6532      * @param {String} text The tab's text and tooltip
6533      */
6534     setText : function(text){
6535         this.text = text;
6536         this.textEl.update(text);
6537         this.setTooltip(text);
6538         if(!this.tabPanel.resizeTabs){
6539             this.autoSize();
6540         }
6541     },
6542     /**
6543      * Activates this TabPanelItem -- this <b>does</b> deactivate the currently active TabPanelItem.
6544      */
6545     activate : function(){
6546         this.tabPanel.activate(this.id);
6547     },
6548
6549     /**
6550      * Disables this TabPanelItem -- this does nothing if this is the active TabPanelItem.
6551      */
6552     disable : function(){
6553         if(this.tabPanel.active != this){
6554             this.disabled = true;
6555             this.pnode.addClass("disabled");
6556         }
6557     },
6558
6559     /**
6560      * Enables this TabPanelItem if it was previously disabled.
6561      */
6562     enable : function(){
6563         this.disabled = false;
6564         this.pnode.removeClass("disabled");
6565     },
6566
6567     /**
6568      * Sets the content for this TabPanelItem.
6569      * @param {String} content The content
6570      * @param {Boolean} loadScripts true to look for and load scripts
6571      */
6572     setContent : function(content, loadScripts){
6573         this.bodyEl.update(content, loadScripts);
6574     },
6575
6576     /**
6577      * Gets the {@link Roo.UpdateManager} for the body of this TabPanelItem. Enables you to perform Ajax updates.
6578      * @return {Roo.UpdateManager} The UpdateManager
6579      */
6580     getUpdateManager : function(){
6581         return this.bodyEl.getUpdateManager();
6582     },
6583
6584     /**
6585      * Set a URL to be used to load the content for this TabPanelItem.
6586      * @param {String/Function} url The URL to load the content from, or a function to call to get the URL
6587      * @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)
6588      * @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)
6589      * @return {Roo.UpdateManager} The UpdateManager
6590      */
6591     setUrl : function(url, params, loadOnce){
6592         if(this.refreshDelegate){
6593             this.un('activate', this.refreshDelegate);
6594         }
6595         this.refreshDelegate = this._handleRefresh.createDelegate(this, [url, params, loadOnce]);
6596         this.on("activate", this.refreshDelegate);
6597         return this.bodyEl.getUpdateManager();
6598     },
6599
6600     /** @private */
6601     _handleRefresh : function(url, params, loadOnce){
6602         if(!loadOnce || !this.loaded){
6603             var updater = this.bodyEl.getUpdateManager();
6604             updater.update(url, params, this._setLoaded.createDelegate(this));
6605         }
6606     },
6607
6608     /**
6609      *   Forces a content refresh from the URL specified in the {@link #setUrl} method.
6610      *   Will fail silently if the setUrl method has not been called.
6611      *   This does not activate the panel, just updates its content.
6612      */
6613     refresh : function(){
6614         if(this.refreshDelegate){
6615            this.loaded = false;
6616            this.refreshDelegate();
6617         }
6618     },
6619
6620     /** @private */
6621     _setLoaded : function(){
6622         this.loaded = true;
6623     },
6624
6625     /** @private */
6626     closeClick : function(e){
6627         var o = {};
6628         e.stopEvent();
6629         this.fireEvent("beforeclose", this, o);
6630         if(o.cancel !== true){
6631             this.tabPanel.removeTab(this.id);
6632         }
6633     },
6634     /**
6635      * The text displayed in the tooltip for the close icon.
6636      * @type String
6637      */
6638     closeText : "Close this tab"
6639 });
6640
6641 /** @private */
6642 Roo.TabPanel.prototype.createStrip = function(container){
6643     var strip = document.createElement("div");
6644     strip.className = "x-tabs-wrap";
6645     container.appendChild(strip);
6646     return strip;
6647 };
6648 /** @private */
6649 Roo.TabPanel.prototype.createStripList = function(strip){
6650     // div wrapper for retard IE
6651     // returns the "tr" element.
6652     strip.innerHTML = '<div class="x-tabs-strip-wrap">'+
6653         '<table class="x-tabs-strip" cellspacing="0" cellpadding="0" border="0"><tbody><tr>'+
6654         '<td class="x-tab-strip-toolbar"></td></tr></tbody></table></div>';
6655     return strip.firstChild.firstChild.firstChild.firstChild;
6656 };
6657 /** @private */
6658 Roo.TabPanel.prototype.createBody = function(container){
6659     var body = document.createElement("div");
6660     Roo.id(body, "tab-body");
6661     Roo.fly(body).addClass("x-tabs-body");
6662     container.appendChild(body);
6663     return body;
6664 };
6665 /** @private */
6666 Roo.TabPanel.prototype.createItemBody = function(bodyEl, id){
6667     var body = Roo.getDom(id);
6668     if(!body){
6669         body = document.createElement("div");
6670         body.id = id;
6671     }
6672     Roo.fly(body).addClass("x-tabs-item-body");
6673     bodyEl.insertBefore(body, bodyEl.firstChild);
6674     return body;
6675 };
6676 /** @private */
6677 Roo.TabPanel.prototype.createStripElements = function(stripEl, text, closable){
6678     var td = document.createElement("td");
6679     stripEl.insertBefore(td, stripEl.childNodes[stripEl.childNodes.length-1]);
6680     //stripEl.appendChild(td);
6681     if(closable){
6682         td.className = "x-tabs-closable";
6683         if(!this.closeTpl){
6684             this.closeTpl = new Roo.Template(
6685                '<a href="#" class="x-tabs-right"><span class="x-tabs-left"><em class="x-tabs-inner">' +
6686                '<span unselectable="on"' + (this.disableTooltips ? '' : ' title="{text}"') +' class="x-tabs-text">{text}</span>' +
6687                '<div unselectable="on" class="close-icon">&#160;</div></em></span></a>'
6688             );
6689         }
6690         var el = this.closeTpl.overwrite(td, {"text": text});
6691         var close = el.getElementsByTagName("div")[0];
6692         var inner = el.getElementsByTagName("em")[0];
6693         return {"el": el, "close": close, "inner": inner};
6694     } else {
6695         if(!this.tabTpl){
6696             this.tabTpl = new Roo.Template(
6697                '<a href="#" class="x-tabs-right"><span class="x-tabs-left"><em class="x-tabs-inner">' +
6698                '<span unselectable="on"' + (this.disableTooltips ? '' : ' title="{text}"') +' class="x-tabs-text">{text}</span></em></span></a>'
6699             );
6700         }
6701         var el = this.tabTpl.overwrite(td, {"text": text});
6702         var inner = el.getElementsByTagName("em")[0];
6703         return {"el": el, "inner": inner};
6704     }
6705 };/*
6706  * Based on:
6707  * Ext JS Library 1.1.1
6708  * Copyright(c) 2006-2007, Ext JS, LLC.
6709  *
6710  * Originally Released Under LGPL - original licence link has changed is not relivant.
6711  *
6712  * Fork - LGPL
6713  * <script type="text/javascript">
6714  */
6715
6716 /**
6717  * @class Roo.Button
6718  * @extends Roo.util.Observable
6719  * Simple Button class
6720  * @cfg {String} text The button text
6721  * @cfg {String} icon The path to an image to display in the button (the image will be set as the background-image
6722  * CSS property of the button by default, so if you want a mixed icon/text button, set cls:"x-btn-text-icon")
6723  * @cfg {Function} handler A function called when the button is clicked (can be used instead of click event)
6724  * @cfg {Object} scope The scope of the handler
6725  * @cfg {Number} minWidth The minimum width for this button (used to give a set of buttons a common width)
6726  * @cfg {String/Object} tooltip The tooltip for the button - can be a string or QuickTips config object
6727  * @cfg {Boolean} hidden True to start hidden (defaults to false)
6728  * @cfg {Boolean} disabled True to start disabled (defaults to false)
6729  * @cfg {Boolean} pressed True to start pressed (only if enableToggle = true)
6730  * @cfg {String} toggleGroup The group this toggle button is a member of (only 1 per group can be pressed, only
6731    applies if enableToggle = true)
6732  * @cfg {String/HTMLElement/Element} renderTo The element to append the button to
6733  * @cfg {Boolean/Object} repeat True to repeat fire the click event while the mouse is down. This can also be
6734   an {@link Roo.util.ClickRepeater} config object (defaults to false).
6735  * @constructor
6736  * Create a new button
6737  * @param {Object} config The config object
6738  */
6739 Roo.Button = function(renderTo, config)
6740 {
6741     if (!config) {
6742         config = renderTo;
6743         renderTo = config.renderTo || false;
6744     }
6745     
6746     Roo.apply(this, config);
6747     this.addEvents({
6748         /**
6749              * @event click
6750              * Fires when this button is clicked
6751              * @param {Button} this
6752              * @param {EventObject} e The click event
6753              */
6754             "click" : true,
6755         /**
6756              * @event toggle
6757              * Fires when the "pressed" state of this button changes (only if enableToggle = true)
6758              * @param {Button} this
6759              * @param {Boolean} pressed
6760              */
6761             "toggle" : true,
6762         /**
6763              * @event mouseover
6764              * Fires when the mouse hovers over the button
6765              * @param {Button} this
6766              * @param {Event} e The event object
6767              */
6768         'mouseover' : true,
6769         /**
6770              * @event mouseout
6771              * Fires when the mouse exits the button
6772              * @param {Button} this
6773              * @param {Event} e The event object
6774              */
6775         'mouseout': true,
6776          /**
6777              * @event render
6778              * Fires when the button is rendered
6779              * @param {Button} this
6780              */
6781         'render': true
6782     });
6783     if(this.menu){
6784         this.menu = Roo.menu.MenuMgr.get(this.menu);
6785     }
6786     // register listeners first!!  - so render can be captured..
6787     Roo.util.Observable.call(this);
6788     if(renderTo){
6789         this.render(renderTo);
6790     }
6791     
6792   
6793 };
6794
6795 Roo.extend(Roo.Button, Roo.util.Observable, {
6796     /**
6797      * 
6798      */
6799     
6800     /**
6801      * Read-only. True if this button is hidden
6802      * @type Boolean
6803      */
6804     hidden : false,
6805     /**
6806      * Read-only. True if this button is disabled
6807      * @type Boolean
6808      */
6809     disabled : false,
6810     /**
6811      * Read-only. True if this button is pressed (only if enableToggle = true)
6812      * @type Boolean
6813      */
6814     pressed : false,
6815
6816     /**
6817      * @cfg {Number} tabIndex 
6818      * The DOM tabIndex for this button (defaults to undefined)
6819      */
6820     tabIndex : undefined,
6821
6822     /**
6823      * @cfg {Boolean} enableToggle
6824      * True to enable pressed/not pressed toggling (defaults to false)
6825      */
6826     enableToggle: false,
6827     /**
6828      * @cfg {Mixed} menu
6829      * Standard menu attribute consisting of a reference to a menu object, a menu id or a menu config blob (defaults to undefined).
6830      */
6831     menu : undefined,
6832     /**
6833      * @cfg {String} menuAlign
6834      * The position to align the menu to (see {@link Roo.Element#alignTo} for more details, defaults to 'tl-bl?').
6835      */
6836     menuAlign : "tl-bl?",
6837
6838     /**
6839      * @cfg {String} iconCls
6840      * A css class which sets a background image to be used as the icon for this button (defaults to undefined).
6841      */
6842     iconCls : undefined,
6843     /**
6844      * @cfg {String} type
6845      * The button's type, corresponding to the DOM input element type attribute.  Either "submit," "reset" or "button" (default).
6846      */
6847     type : 'button',
6848
6849     // private
6850     menuClassTarget: 'tr',
6851
6852     /**
6853      * @cfg {String} clickEvent
6854      * The type of event to map to the button's event handler (defaults to 'click')
6855      */
6856     clickEvent : 'click',
6857
6858     /**
6859      * @cfg {Boolean} handleMouseEvents
6860      * False to disable visual cues on mouseover, mouseout and mousedown (defaults to true)
6861      */
6862     handleMouseEvents : true,
6863
6864     /**
6865      * @cfg {String} tooltipType
6866      * The type of tooltip to use. Either "qtip" (default) for QuickTips or "title" for title attribute.
6867      */
6868     tooltipType : 'qtip',
6869
6870     /**
6871      * @cfg {String} cls
6872      * A CSS class to apply to the button's main element.
6873      */
6874     
6875     /**
6876      * @cfg {Roo.Template} template (Optional)
6877      * An {@link Roo.Template} with which to create the Button's main element. This Template must
6878      * contain numeric substitution parameter 0 if it is to display the tRoo property. Changing the template could
6879      * require code modifications if required elements (e.g. a button) aren't present.
6880      */
6881
6882     // private
6883     render : function(renderTo){
6884         var btn;
6885         if(this.hideParent){
6886             this.parentEl = Roo.get(renderTo);
6887         }
6888         if(!this.dhconfig){
6889             if(!this.template){
6890                 if(!Roo.Button.buttonTemplate){
6891                     // hideous table template
6892                     Roo.Button.buttonTemplate = new Roo.Template(
6893                         '<table border="0" cellpadding="0" cellspacing="0" class="x-btn-wrap"><tbody><tr>',
6894                         '<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>',
6895                         "</tr></tbody></table>");
6896                 }
6897                 this.template = Roo.Button.buttonTemplate;
6898             }
6899             btn = this.template.append(renderTo, [this.text || '&#160;', this.type], true);
6900             var btnEl = btn.child("button:first");
6901             btnEl.on('focus', this.onFocus, this);
6902             btnEl.on('blur', this.onBlur, this);
6903             if(this.cls){
6904                 btn.addClass(this.cls);
6905             }
6906             if(this.icon){
6907                 btnEl.setStyle('background-image', 'url(' +this.icon +')');
6908             }
6909             if(this.iconCls){
6910                 btnEl.addClass(this.iconCls);
6911                 if(!this.cls){
6912                     btn.addClass(this.text ? 'x-btn-text-icon' : 'x-btn-icon');
6913                 }
6914             }
6915             if(this.tabIndex !== undefined){
6916                 btnEl.dom.tabIndex = this.tabIndex;
6917             }
6918             if(this.tooltip){
6919                 if(typeof this.tooltip == 'object'){
6920                     Roo.QuickTips.tips(Roo.apply({
6921                           target: btnEl.id
6922                     }, this.tooltip));
6923                 } else {
6924                     btnEl.dom[this.tooltipType] = this.tooltip;
6925                 }
6926             }
6927         }else{
6928             btn = Roo.DomHelper.append(Roo.get(renderTo).dom, this.dhconfig, true);
6929         }
6930         this.el = btn;
6931         if(this.id){
6932             this.el.dom.id = this.el.id = this.id;
6933         }
6934         if(this.menu){
6935             this.el.child(this.menuClassTarget).addClass("x-btn-with-menu");
6936             this.menu.on("show", this.onMenuShow, this);
6937             this.menu.on("hide", this.onMenuHide, this);
6938         }
6939         btn.addClass("x-btn");
6940         if(Roo.isIE && !Roo.isIE7){
6941             this.autoWidth.defer(1, this);
6942         }else{
6943             this.autoWidth();
6944         }
6945         if(this.handleMouseEvents){
6946             btn.on("mouseover", this.onMouseOver, this);
6947             btn.on("mouseout", this.onMouseOut, this);
6948             btn.on("mousedown", this.onMouseDown, this);
6949         }
6950         btn.on(this.clickEvent, this.onClick, this);
6951         //btn.on("mouseup", this.onMouseUp, this);
6952         if(this.hidden){
6953             this.hide();
6954         }
6955         if(this.disabled){
6956             this.disable();
6957         }
6958         Roo.ButtonToggleMgr.register(this);
6959         if(this.pressed){
6960             this.el.addClass("x-btn-pressed");
6961         }
6962         if(this.repeat){
6963             var repeater = new Roo.util.ClickRepeater(btn,
6964                 typeof this.repeat == "object" ? this.repeat : {}
6965             );
6966             repeater.on("click", this.onClick,  this);
6967         }
6968         
6969         this.fireEvent('render', this);
6970         
6971     },
6972     /**
6973      * Returns the button's underlying element
6974      * @return {Roo.Element} The element
6975      */
6976     getEl : function(){
6977         return this.el;  
6978     },
6979     
6980     /**
6981      * Destroys this Button and removes any listeners.
6982      */
6983     destroy : function(){
6984         Roo.ButtonToggleMgr.unregister(this);
6985         this.el.removeAllListeners();
6986         this.purgeListeners();
6987         this.el.remove();
6988     },
6989
6990     // private
6991     autoWidth : function(){
6992         if(this.el){
6993             this.el.setWidth("auto");
6994             if(Roo.isIE7 && Roo.isStrict){
6995                 var ib = this.el.child('button');
6996                 if(ib && ib.getWidth() > 20){
6997                     ib.clip();
6998                     ib.setWidth(Roo.util.TextMetrics.measure(ib, this.text).width+ib.getFrameWidth('lr'));
6999                 }
7000             }
7001             if(this.minWidth){
7002                 if(this.hidden){
7003                     this.el.beginMeasure();
7004                 }
7005                 if(this.el.getWidth() < this.minWidth){
7006                     this.el.setWidth(this.minWidth);
7007                 }
7008                 if(this.hidden){
7009                     this.el.endMeasure();
7010                 }
7011             }
7012         }
7013     },
7014
7015     /**
7016      * Assigns this button's click handler
7017      * @param {Function} handler The function to call when the button is clicked
7018      * @param {Object} scope (optional) Scope for the function passed in
7019      */
7020     setHandler : function(handler, scope){
7021         this.handler = handler;
7022         this.scope = scope;  
7023     },
7024     
7025     /**
7026      * Sets this button's text
7027      * @param {String} text The button text
7028      */
7029     setText : function(text){
7030         this.text = text;
7031         if(this.el){
7032             this.el.child("td.x-btn-center button.x-btn-text").update(text);
7033         }
7034         this.autoWidth();
7035     },
7036     
7037     /**
7038      * Gets the text for this button
7039      * @return {String} The button text
7040      */
7041     getText : function(){
7042         return this.text;  
7043     },
7044     
7045     /**
7046      * Show this button
7047      */
7048     show: function(){
7049         this.hidden = false;
7050         if(this.el){
7051             this[this.hideParent? 'parentEl' : 'el'].setStyle("display", "");
7052         }
7053     },
7054     
7055     /**
7056      * Hide this button
7057      */
7058     hide: function(){
7059         this.hidden = true;
7060         if(this.el){
7061             this[this.hideParent? 'parentEl' : 'el'].setStyle("display", "none");
7062         }
7063     },
7064     
7065     /**
7066      * Convenience function for boolean show/hide
7067      * @param {Boolean} visible True to show, false to hide
7068      */
7069     setVisible: function(visible){
7070         if(visible) {
7071             this.show();
7072         }else{
7073             this.hide();
7074         }
7075     },
7076     
7077     /**
7078      * If a state it passed, it becomes the pressed state otherwise the current state is toggled.
7079      * @param {Boolean} state (optional) Force a particular state
7080      */
7081     toggle : function(state){
7082         state = state === undefined ? !this.pressed : state;
7083         if(state != this.pressed){
7084             if(state){
7085                 this.el.addClass("x-btn-pressed");
7086                 this.pressed = true;
7087                 this.fireEvent("toggle", this, true);
7088             }else{
7089                 this.el.removeClass("x-btn-pressed");
7090                 this.pressed = false;
7091                 this.fireEvent("toggle", this, false);
7092             }
7093             if(this.toggleHandler){
7094                 this.toggleHandler.call(this.scope || this, this, state);
7095             }
7096         }
7097     },
7098     
7099     /**
7100      * Focus the button
7101      */
7102     focus : function(){
7103         this.el.child('button:first').focus();
7104     },
7105     
7106     /**
7107      * Disable this button
7108      */
7109     disable : function(){
7110         if(this.el){
7111             this.el.addClass("x-btn-disabled");
7112         }
7113         this.disabled = true;
7114     },
7115     
7116     /**
7117      * Enable this button
7118      */
7119     enable : function(){
7120         if(this.el){
7121             this.el.removeClass("x-btn-disabled");
7122         }
7123         this.disabled = false;
7124     },
7125
7126     /**
7127      * Convenience function for boolean enable/disable
7128      * @param {Boolean} enabled True to enable, false to disable
7129      */
7130     setDisabled : function(v){
7131         this[v !== true ? "enable" : "disable"]();
7132     },
7133
7134     // private
7135     onClick : function(e)
7136     {
7137         if(e){
7138             e.preventDefault();
7139         }
7140         if(e.button != 0){
7141             return;
7142         }
7143         if(!this.disabled){
7144             if(this.enableToggle){
7145                 this.toggle();
7146             }
7147             if(this.menu && !this.menu.isVisible()){
7148                 this.menu.show(this.el, this.menuAlign);
7149             }
7150             this.fireEvent("click", this, e);
7151             if(this.handler){
7152                 this.el.removeClass("x-btn-over");
7153                 this.handler.call(this.scope || this, this, e);
7154             }
7155         }
7156     },
7157     // private
7158     onMouseOver : function(e){
7159         if(!this.disabled){
7160             this.el.addClass("x-btn-over");
7161             this.fireEvent('mouseover', this, e);
7162         }
7163     },
7164     // private
7165     onMouseOut : function(e){
7166         if(!e.within(this.el,  true)){
7167             this.el.removeClass("x-btn-over");
7168             this.fireEvent('mouseout', this, e);
7169         }
7170     },
7171     // private
7172     onFocus : function(e){
7173         if(!this.disabled){
7174             this.el.addClass("x-btn-focus");
7175         }
7176     },
7177     // private
7178     onBlur : function(e){
7179         this.el.removeClass("x-btn-focus");
7180     },
7181     // private
7182     onMouseDown : function(e){
7183         if(!this.disabled && e.button == 0){
7184             this.el.addClass("x-btn-click");
7185             Roo.get(document).on('mouseup', this.onMouseUp, this);
7186         }
7187     },
7188     // private
7189     onMouseUp : function(e){
7190         if(e.button == 0){
7191             this.el.removeClass("x-btn-click");
7192             Roo.get(document).un('mouseup', this.onMouseUp, this);
7193         }
7194     },
7195     // private
7196     onMenuShow : function(e){
7197         this.el.addClass("x-btn-menu-active");
7198     },
7199     // private
7200     onMenuHide : function(e){
7201         this.el.removeClass("x-btn-menu-active");
7202     }   
7203 });
7204
7205 // Private utility class used by Button
7206 Roo.ButtonToggleMgr = function(){
7207    var groups = {};
7208    
7209    function toggleGroup(btn, state){
7210        if(state){
7211            var g = groups[btn.toggleGroup];
7212            for(var i = 0, l = g.length; i < l; i++){
7213                if(g[i] != btn){
7214                    g[i].toggle(false);
7215                }
7216            }
7217        }
7218    }
7219    
7220    return {
7221        register : function(btn){
7222            if(!btn.toggleGroup){
7223                return;
7224            }
7225            var g = groups[btn.toggleGroup];
7226            if(!g){
7227                g = groups[btn.toggleGroup] = [];
7228            }
7229            g.push(btn);
7230            btn.on("toggle", toggleGroup);
7231        },
7232        
7233        unregister : function(btn){
7234            if(!btn.toggleGroup){
7235                return;
7236            }
7237            var g = groups[btn.toggleGroup];
7238            if(g){
7239                g.remove(btn);
7240                btn.un("toggle", toggleGroup);
7241            }
7242        }
7243    };
7244 }();/*
7245  * Based on:
7246  * Ext JS Library 1.1.1
7247  * Copyright(c) 2006-2007, Ext JS, LLC.
7248  *
7249  * Originally Released Under LGPL - original licence link has changed is not relivant.
7250  *
7251  * Fork - LGPL
7252  * <script type="text/javascript">
7253  */
7254  
7255 /**
7256  * @class Roo.SplitButton
7257  * @extends Roo.Button
7258  * A split button that provides a built-in dropdown arrow that can fire an event separately from the default
7259  * click event of the button.  Typically this would be used to display a dropdown menu that provides additional
7260  * options to the primary button action, but any custom handler can provide the arrowclick implementation.
7261  * @cfg {Function} arrowHandler A function called when the arrow button is clicked (can be used instead of click event)
7262  * @cfg {String} arrowTooltip The title attribute of the arrow
7263  * @constructor
7264  * Create a new menu button
7265  * @param {String/HTMLElement/Element} renderTo The element to append the button to
7266  * @param {Object} config The config object
7267  */
7268 Roo.SplitButton = function(renderTo, config){
7269     Roo.SplitButton.superclass.constructor.call(this, renderTo, config);
7270     /**
7271      * @event arrowclick
7272      * Fires when this button's arrow is clicked
7273      * @param {SplitButton} this
7274      * @param {EventObject} e The click event
7275      */
7276     this.addEvents({"arrowclick":true});
7277 };
7278
7279 Roo.extend(Roo.SplitButton, Roo.Button, {
7280     render : function(renderTo){
7281         // this is one sweet looking template!
7282         var tpl = new Roo.Template(
7283             '<table cellspacing="0" class="x-btn-menu-wrap x-btn"><tr><td>',
7284             '<table cellspacing="0" class="x-btn-wrap x-btn-menu-text-wrap"><tbody>',
7285             '<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>',
7286             "</tbody></table></td><td>",
7287             '<table cellspacing="0" class="x-btn-wrap x-btn-menu-arrow-wrap"><tbody>',
7288             '<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>',
7289             "</tbody></table></td></tr></table>"
7290         );
7291         var btn = tpl.append(renderTo, [this.text, this.type], true);
7292         var btnEl = btn.child("button");
7293         if(this.cls){
7294             btn.addClass(this.cls);
7295         }
7296         if(this.icon){
7297             btnEl.setStyle('background-image', 'url(' +this.icon +')');
7298         }
7299         if(this.iconCls){
7300             btnEl.addClass(this.iconCls);
7301             if(!this.cls){
7302                 btn.addClass(this.text ? 'x-btn-text-icon' : 'x-btn-icon');
7303             }
7304         }
7305         this.el = btn;
7306         if(this.handleMouseEvents){
7307             btn.on("mouseover", this.onMouseOver, this);
7308             btn.on("mouseout", this.onMouseOut, this);
7309             btn.on("mousedown", this.onMouseDown, this);
7310             btn.on("mouseup", this.onMouseUp, this);
7311         }
7312         btn.on(this.clickEvent, this.onClick, this);
7313         if(this.tooltip){
7314             if(typeof this.tooltip == 'object'){
7315                 Roo.QuickTips.tips(Roo.apply({
7316                       target: btnEl.id
7317                 }, this.tooltip));
7318             } else {
7319                 btnEl.dom[this.tooltipType] = this.tooltip;
7320             }
7321         }
7322         if(this.arrowTooltip){
7323             btn.child("button:nth(2)").dom[this.tooltipType] = this.arrowTooltip;
7324         }
7325         if(this.hidden){
7326             this.hide();
7327         }
7328         if(this.disabled){
7329             this.disable();
7330         }
7331         if(this.pressed){
7332             this.el.addClass("x-btn-pressed");
7333         }
7334         if(Roo.isIE && !Roo.isIE7){
7335             this.autoWidth.defer(1, this);
7336         }else{
7337             this.autoWidth();
7338         }
7339         if(this.menu){
7340             this.menu.on("show", this.onMenuShow, this);
7341             this.menu.on("hide", this.onMenuHide, this);
7342         }
7343         this.fireEvent('render', this);
7344     },
7345
7346     // private
7347     autoWidth : function(){
7348         if(this.el){
7349             var tbl = this.el.child("table:first");
7350             var tbl2 = this.el.child("table:last");
7351             this.el.setWidth("auto");
7352             tbl.setWidth("auto");
7353             if(Roo.isIE7 && Roo.isStrict){
7354                 var ib = this.el.child('button:first');
7355                 if(ib && ib.getWidth() > 20){
7356                     ib.clip();
7357                     ib.setWidth(Roo.util.TextMetrics.measure(ib, this.text).width+ib.getFrameWidth('lr'));
7358                 }
7359             }
7360             if(this.minWidth){
7361                 if(this.hidden){
7362                     this.el.beginMeasure();
7363                 }
7364                 if((tbl.getWidth()+tbl2.getWidth()) < this.minWidth){
7365                     tbl.setWidth(this.minWidth-tbl2.getWidth());
7366                 }
7367                 if(this.hidden){
7368                     this.el.endMeasure();
7369                 }
7370             }
7371             this.el.setWidth(tbl.getWidth()+tbl2.getWidth());
7372         } 
7373     },
7374     /**
7375      * Sets this button's click handler
7376      * @param {Function} handler The function to call when the button is clicked
7377      * @param {Object} scope (optional) Scope for the function passed above
7378      */
7379     setHandler : function(handler, scope){
7380         this.handler = handler;
7381         this.scope = scope;  
7382     },
7383     
7384     /**
7385      * Sets this button's arrow click handler
7386      * @param {Function} handler The function to call when the arrow is clicked
7387      * @param {Object} scope (optional) Scope for the function passed above
7388      */
7389     setArrowHandler : function(handler, scope){
7390         this.arrowHandler = handler;
7391         this.scope = scope;  
7392     },
7393     
7394     /**
7395      * Focus the button
7396      */
7397     focus : function(){
7398         if(this.el){
7399             this.el.child("button:first").focus();
7400         }
7401     },
7402
7403     // private
7404     onClick : function(e){
7405         e.preventDefault();
7406         if(!this.disabled){
7407             if(e.getTarget(".x-btn-menu-arrow-wrap")){
7408                 if(this.menu && !this.menu.isVisible()){
7409                     this.menu.show(this.el, this.menuAlign);
7410                 }
7411                 this.fireEvent("arrowclick", this, e);
7412                 if(this.arrowHandler){
7413                     this.arrowHandler.call(this.scope || this, this, e);
7414                 }
7415             }else{
7416                 this.fireEvent("click", this, e);
7417                 if(this.handler){
7418                     this.handler.call(this.scope || this, this, e);
7419                 }
7420             }
7421         }
7422     },
7423     // private
7424     onMouseDown : function(e){
7425         if(!this.disabled){
7426             Roo.fly(e.getTarget("table")).addClass("x-btn-click");
7427         }
7428     },
7429     // private
7430     onMouseUp : function(e){
7431         Roo.fly(e.getTarget("table")).removeClass("x-btn-click");
7432     }   
7433 });
7434
7435
7436 // backwards compat
7437 Roo.MenuButton = Roo.SplitButton;/*
7438  * Based on:
7439  * Ext JS Library 1.1.1
7440  * Copyright(c) 2006-2007, Ext JS, LLC.
7441  *
7442  * Originally Released Under LGPL - original licence link has changed is not relivant.
7443  *
7444  * Fork - LGPL
7445  * <script type="text/javascript">
7446  */
7447
7448 /**
7449  * @class Roo.Toolbar
7450  * Basic Toolbar class.
7451  * @constructor
7452  * Creates a new Toolbar
7453  * @param {Object} container The config object
7454  */ 
7455 Roo.Toolbar = function(container, buttons, config)
7456 {
7457     /// old consturctor format still supported..
7458     if(container instanceof Array){ // omit the container for later rendering
7459         buttons = container;
7460         config = buttons;
7461         container = null;
7462     }
7463     if (typeof(container) == 'object' && container.xtype) {
7464         config = container;
7465         container = config.container;
7466         buttons = config.buttons || []; // not really - use items!!
7467     }
7468     var xitems = [];
7469     if (config && config.items) {
7470         xitems = config.items;
7471         delete config.items;
7472     }
7473     Roo.apply(this, config);
7474     this.buttons = buttons;
7475     
7476     if(container){
7477         this.render(container);
7478     }
7479     this.xitems = xitems;
7480     Roo.each(xitems, function(b) {
7481         this.add(b);
7482     }, this);
7483     
7484 };
7485
7486 Roo.Toolbar.prototype = {
7487     /**
7488      * @cfg {Array} items
7489      * array of button configs or elements to add (will be converted to a MixedCollection)
7490      */
7491     
7492     /**
7493      * @cfg {String/HTMLElement/Element} container
7494      * The id or element that will contain the toolbar
7495      */
7496     // private
7497     render : function(ct){
7498         this.el = Roo.get(ct);
7499         if(this.cls){
7500             this.el.addClass(this.cls);
7501         }
7502         // using a table allows for vertical alignment
7503         // 100% width is needed by Safari...
7504         this.el.update('<div class="x-toolbar x-small-editor"><table cellspacing="0"><tr></tr></table></div>');
7505         this.tr = this.el.child("tr", true);
7506         var autoId = 0;
7507         this.items = new Roo.util.MixedCollection(false, function(o){
7508             return o.id || ("item" + (++autoId));
7509         });
7510         if(this.buttons){
7511             this.add.apply(this, this.buttons);
7512             delete this.buttons;
7513         }
7514     },
7515
7516     /**
7517      * Adds element(s) to the toolbar -- this function takes a variable number of 
7518      * arguments of mixed type and adds them to the toolbar.
7519      * @param {Mixed} arg1 The following types of arguments are all valid:<br />
7520      * <ul>
7521      * <li>{@link Roo.Toolbar.Button} config: A valid button config object (equivalent to {@link #addButton})</li>
7522      * <li>HtmlElement: Any standard HTML element (equivalent to {@link #addElement})</li>
7523      * <li>Field: Any form field (equivalent to {@link #addField})</li>
7524      * <li>Item: Any subclass of {@link Roo.Toolbar.Item} (equivalent to {@link #addItem})</li>
7525      * <li>String: Any generic string (gets wrapped in a {@link Roo.Toolbar.TextItem}, equivalent to {@link #addText}).
7526      * Note that there are a few special strings that are treated differently as explained nRoo.</li>
7527      * <li>'separator' or '-': Creates a separator element (equivalent to {@link #addSeparator})</li>
7528      * <li>' ': Creates a spacer element (equivalent to {@link #addSpacer})</li>
7529      * <li>'->': Creates a fill element (equivalent to {@link #addFill})</li>
7530      * </ul>
7531      * @param {Mixed} arg2
7532      * @param {Mixed} etc.
7533      */
7534     add : function(){
7535         var a = arguments, l = a.length;
7536         for(var i = 0; i < l; i++){
7537             this._add(a[i]);
7538         }
7539     },
7540     // private..
7541     _add : function(el) {
7542         
7543         if (el.xtype) {
7544             el = Roo.factory(el, typeof(Roo.Toolbar[el.xtype]) == 'undefined' ? Roo.form : Roo.Toolbar);
7545         }
7546         
7547         if (el.applyTo){ // some kind of form field
7548             return this.addField(el);
7549         } 
7550         if (el.render){ // some kind of Toolbar.Item
7551             return this.addItem(el);
7552         }
7553         if (typeof el == "string"){ // string
7554             if(el == "separator" || el == "-"){
7555                 return this.addSeparator();
7556             }
7557             if (el == " "){
7558                 return this.addSpacer();
7559             }
7560             if(el == "->"){
7561                 return this.addFill();
7562             }
7563             return this.addText(el);
7564             
7565         }
7566         if(el.tagName){ // element
7567             return this.addElement(el);
7568         }
7569         if(typeof el == "object"){ // must be button config?
7570             return this.addButton(el);
7571         }
7572         // and now what?!?!
7573         return false;
7574         
7575     },
7576     
7577     /**
7578      * Add an Xtype element
7579      * @param {Object} xtype Xtype Object
7580      * @return {Object} created Object
7581      */
7582     addxtype : function(e){
7583         return this.add(e);  
7584     },
7585     
7586     /**
7587      * Returns the Element for this toolbar.
7588      * @return {Roo.Element}
7589      */
7590     getEl : function(){
7591         return this.el;  
7592     },
7593     
7594     /**
7595      * Adds a separator
7596      * @return {Roo.Toolbar.Item} The separator item
7597      */
7598     addSeparator : function(){
7599         return this.addItem(new Roo.Toolbar.Separator());
7600     },
7601
7602     /**
7603      * Adds a spacer element
7604      * @return {Roo.Toolbar.Spacer} The spacer item
7605      */
7606     addSpacer : function(){
7607         return this.addItem(new Roo.Toolbar.Spacer());
7608     },
7609
7610     /**
7611      * Adds a fill element that forces subsequent additions to the right side of the toolbar
7612      * @return {Roo.Toolbar.Fill} The fill item
7613      */
7614     addFill : function(){
7615         return this.addItem(new Roo.Toolbar.Fill());
7616     },
7617
7618     /**
7619      * Adds any standard HTML element to the toolbar
7620      * @param {String/HTMLElement/Element} el The element or id of the element to add
7621      * @return {Roo.Toolbar.Item} The element's item
7622      */
7623     addElement : function(el){
7624         return this.addItem(new Roo.Toolbar.Item(el));
7625     },
7626     /**
7627      * Collection of items on the toolbar.. (only Toolbar Items, so use fields to retrieve fields)
7628      * @type Roo.util.MixedCollection  
7629      */
7630     items : false,
7631      
7632     /**
7633      * Adds any Toolbar.Item or subclass
7634      * @param {Roo.Toolbar.Item} item
7635      * @return {Roo.Toolbar.Item} The item
7636      */
7637     addItem : function(item){
7638         var td = this.nextBlock();
7639         item.render(td);
7640         this.items.add(item);
7641         return item;
7642     },
7643     
7644     /**
7645      * Adds a button (or buttons). See {@link Roo.Toolbar.Button} for more info on the config.
7646      * @param {Object/Array} config A button config or array of configs
7647      * @return {Roo.Toolbar.Button/Array}
7648      */
7649     addButton : function(config){
7650         if(config instanceof Array){
7651             var buttons = [];
7652             for(var i = 0, len = config.length; i < len; i++) {
7653                 buttons.push(this.addButton(config[i]));
7654             }
7655             return buttons;
7656         }
7657         var b = config;
7658         if(!(config instanceof Roo.Toolbar.Button)){
7659             b = config.split ?
7660                 new Roo.Toolbar.SplitButton(config) :
7661                 new Roo.Toolbar.Button(config);
7662         }
7663         var td = this.nextBlock();
7664         b.render(td);
7665         this.items.add(b);
7666         return b;
7667     },
7668     
7669     /**
7670      * Adds text to the toolbar
7671      * @param {String} text The text to add
7672      * @return {Roo.Toolbar.Item} The element's item
7673      */
7674     addText : function(text){
7675         return this.addItem(new Roo.Toolbar.TextItem(text));
7676     },
7677     
7678     /**
7679      * Inserts any {@link Roo.Toolbar.Item}/{@link Roo.Toolbar.Button} at the specified index.
7680      * @param {Number} index The index where the item is to be inserted
7681      * @param {Object/Roo.Toolbar.Item/Roo.Toolbar.Button (may be Array)} item The button, or button config object to be inserted.
7682      * @return {Roo.Toolbar.Button/Item}
7683      */
7684     insertButton : function(index, item){
7685         if(item instanceof Array){
7686             var buttons = [];
7687             for(var i = 0, len = item.length; i < len; i++) {
7688                buttons.push(this.insertButton(index + i, item[i]));
7689             }
7690             return buttons;
7691         }
7692         if (!(item instanceof Roo.Toolbar.Button)){
7693            item = new Roo.Toolbar.Button(item);
7694         }
7695         var td = document.createElement("td");
7696         this.tr.insertBefore(td, this.tr.childNodes[index]);
7697         item.render(td);
7698         this.items.insert(index, item);
7699         return item;
7700     },
7701     
7702     /**
7703      * Adds a new element to the toolbar from the passed {@link Roo.DomHelper} config.
7704      * @param {Object} config
7705      * @return {Roo.Toolbar.Item} The element's item
7706      */
7707     addDom : function(config, returnEl){
7708         var td = this.nextBlock();
7709         Roo.DomHelper.overwrite(td, config);
7710         var ti = new Roo.Toolbar.Item(td.firstChild);
7711         ti.render(td);
7712         this.items.add(ti);
7713         return ti;
7714     },
7715
7716     /**
7717      * Collection of fields on the toolbar.. usefull for quering (value is false if there are no fields)
7718      * @type Roo.util.MixedCollection  
7719      */
7720     fields : false,
7721     
7722     /**
7723      * Adds a dynamically rendered Roo.form field (TextField, ComboBox, etc).
7724      * Note: the field should not have been rendered yet. For a field that has already been
7725      * rendered, use {@link #addElement}.
7726      * @param {Roo.form.Field} field
7727      * @return {Roo.ToolbarItem}
7728      */
7729      
7730       
7731     addField : function(field) {
7732         if (!this.fields) {
7733             var autoId = 0;
7734             this.fields = new Roo.util.MixedCollection(false, function(o){
7735                 return o.id || ("item" + (++autoId));
7736             });
7737
7738         }
7739         
7740         var td = this.nextBlock();
7741         field.render(td);
7742         var ti = new Roo.Toolbar.Item(td.firstChild);
7743         ti.render(td);
7744         this.items.add(ti);
7745         this.fields.add(field);
7746         return ti;
7747     },
7748     /**
7749      * Hide the toolbar
7750      * @method hide
7751      */
7752      
7753       
7754     hide : function()
7755     {
7756         this.el.child('div').setVisibilityMode(Roo.Element.DISPLAY);
7757         this.el.child('div').hide();
7758     },
7759     /**
7760      * Show the toolbar
7761      * @method show
7762      */
7763     show : function()
7764     {
7765         this.el.child('div').show();
7766     },
7767       
7768     // private
7769     nextBlock : function(){
7770         var td = document.createElement("td");
7771         this.tr.appendChild(td);
7772         return td;
7773     },
7774
7775     // private
7776     destroy : function(){
7777         if(this.items){ // rendered?
7778             Roo.destroy.apply(Roo, this.items.items);
7779         }
7780         if(this.fields){ // rendered?
7781             Roo.destroy.apply(Roo, this.fields.items);
7782         }
7783         Roo.Element.uncache(this.el, this.tr);
7784     }
7785 };
7786
7787 /**
7788  * @class Roo.Toolbar.Item
7789  * The base class that other classes should extend in order to get some basic common toolbar item functionality.
7790  * @constructor
7791  * Creates a new Item
7792  * @param {HTMLElement} el 
7793  */
7794 Roo.Toolbar.Item = function(el){
7795     var cfg = {};
7796     if (typeof (el.xtype) != 'undefined') {
7797         cfg = el;
7798         el = cfg.el;
7799     }
7800     
7801     this.el = Roo.getDom(el);
7802     this.id = Roo.id(this.el);
7803     this.hidden = false;
7804     
7805     this.addEvents({
7806          /**
7807              * @event render
7808              * Fires when the button is rendered
7809              * @param {Button} this
7810              */
7811         'render': true
7812     });
7813     Roo.Toolbar.Item.superclass.constructor.call(this,cfg);
7814 };
7815 Roo.extend(Roo.Toolbar.Item, Roo.util.Observable, {
7816 //Roo.Toolbar.Item.prototype = {
7817     
7818     /**
7819      * Get this item's HTML Element
7820      * @return {HTMLElement}
7821      */
7822     getEl : function(){
7823        return this.el;  
7824     },
7825
7826     // private
7827     render : function(td){
7828         
7829          this.td = td;
7830         td.appendChild(this.el);
7831         
7832         this.fireEvent('render', this);
7833     },
7834     
7835     /**
7836      * Removes and destroys this item.
7837      */
7838     destroy : function(){
7839         this.td.parentNode.removeChild(this.td);
7840     },
7841     
7842     /**
7843      * Shows this item.
7844      */
7845     show: function(){
7846         this.hidden = false;
7847         this.td.style.display = "";
7848     },
7849     
7850     /**
7851      * Hides this item.
7852      */
7853     hide: function(){
7854         this.hidden = true;
7855         this.td.style.display = "none";
7856     },
7857     
7858     /**
7859      * Convenience function for boolean show/hide.
7860      * @param {Boolean} visible true to show/false to hide
7861      */
7862     setVisible: function(visible){
7863         if(visible) {
7864             this.show();
7865         }else{
7866             this.hide();
7867         }
7868     },
7869     
7870     /**
7871      * Try to focus this item.
7872      */
7873     focus : function(){
7874         Roo.fly(this.el).focus();
7875     },
7876     
7877     /**
7878      * Disables this item.
7879      */
7880     disable : function(){
7881         Roo.fly(this.td).addClass("x-item-disabled");
7882         this.disabled = true;
7883         this.el.disabled = true;
7884     },
7885     
7886     /**
7887      * Enables this item.
7888      */
7889     enable : function(){
7890         Roo.fly(this.td).removeClass("x-item-disabled");
7891         this.disabled = false;
7892         this.el.disabled = false;
7893     }
7894 });
7895
7896
7897 /**
7898  * @class Roo.Toolbar.Separator
7899  * @extends Roo.Toolbar.Item
7900  * A simple toolbar separator class
7901  * @constructor
7902  * Creates a new Separator
7903  */
7904 Roo.Toolbar.Separator = function(cfg){
7905     
7906     var s = document.createElement("span");
7907     s.className = "ytb-sep";
7908     if (cfg) {
7909         cfg.el = s;
7910     }
7911     
7912     Roo.Toolbar.Separator.superclass.constructor.call(this, cfg || s);
7913 };
7914 Roo.extend(Roo.Toolbar.Separator, Roo.Toolbar.Item, {
7915     enable:Roo.emptyFn,
7916     disable:Roo.emptyFn,
7917     focus:Roo.emptyFn
7918 });
7919
7920 /**
7921  * @class Roo.Toolbar.Spacer
7922  * @extends Roo.Toolbar.Item
7923  * A simple element that adds extra horizontal space to a toolbar.
7924  * @constructor
7925  * Creates a new Spacer
7926  */
7927 Roo.Toolbar.Spacer = function(cfg){
7928     var s = document.createElement("div");
7929     s.className = "ytb-spacer";
7930     if (cfg) {
7931         cfg.el = s;
7932     }
7933     Roo.Toolbar.Spacer.superclass.constructor.call(this, cfg || s);
7934 };
7935 Roo.extend(Roo.Toolbar.Spacer, Roo.Toolbar.Item, {
7936     enable:Roo.emptyFn,
7937     disable:Roo.emptyFn,
7938     focus:Roo.emptyFn
7939 });
7940
7941 /**
7942  * @class Roo.Toolbar.Fill
7943  * @extends Roo.Toolbar.Spacer
7944  * A simple element that adds a greedy (100% width) horizontal space to a toolbar.
7945  * @constructor
7946  * Creates a new Spacer
7947  */
7948 Roo.Toolbar.Fill = Roo.extend(Roo.Toolbar.Spacer, {
7949     // private
7950     render : function(td){
7951         td.style.width = '100%';
7952         Roo.Toolbar.Fill.superclass.render.call(this, td);
7953     }
7954 });
7955
7956 /**
7957  * @class Roo.Toolbar.TextItem
7958  * @extends Roo.Toolbar.Item
7959  * A simple class that renders text directly into a toolbar.
7960  * @constructor
7961  * Creates a new TextItem
7962  * @param {String} text
7963  */
7964 Roo.Toolbar.TextItem = function(cfg){
7965     var  text = cfg || "";
7966     if (typeof(cfg) == 'object') {
7967         text = cfg.text || "";
7968     }  else {
7969         cfg = null;
7970     }
7971     var s = document.createElement("span");
7972     s.className = "ytb-text";
7973     s.innerHTML = text;
7974     if (cfg) {
7975         cfg.el  = s;
7976     }
7977     
7978     Roo.Toolbar.TextItem.superclass.constructor.call(this, cfg ||  s);
7979 };
7980 Roo.extend(Roo.Toolbar.TextItem, Roo.Toolbar.Item, {
7981     
7982      
7983     enable:Roo.emptyFn,
7984     disable:Roo.emptyFn,
7985     focus:Roo.emptyFn
7986 });
7987
7988 /**
7989  * @class Roo.Toolbar.Button
7990  * @extends Roo.Button
7991  * A button that renders into a toolbar.
7992  * @constructor
7993  * Creates a new Button
7994  * @param {Object} config A standard {@link Roo.Button} config object
7995  */
7996 Roo.Toolbar.Button = function(config){
7997     Roo.Toolbar.Button.superclass.constructor.call(this, null, config);
7998 };
7999 Roo.extend(Roo.Toolbar.Button, Roo.Button, {
8000     render : function(td){
8001         this.td = td;
8002         Roo.Toolbar.Button.superclass.render.call(this, td);
8003     },
8004     
8005     /**
8006      * Removes and destroys this button
8007      */
8008     destroy : function(){
8009         Roo.Toolbar.Button.superclass.destroy.call(this);
8010         this.td.parentNode.removeChild(this.td);
8011     },
8012     
8013     /**
8014      * Shows this button
8015      */
8016     show: function(){
8017         this.hidden = false;
8018         this.td.style.display = "";
8019     },
8020     
8021     /**
8022      * Hides this button
8023      */
8024     hide: function(){
8025         this.hidden = true;
8026         this.td.style.display = "none";
8027     },
8028
8029     /**
8030      * Disables this item
8031      */
8032     disable : function(){
8033         Roo.fly(this.td).addClass("x-item-disabled");
8034         this.disabled = true;
8035     },
8036
8037     /**
8038      * Enables this item
8039      */
8040     enable : function(){
8041         Roo.fly(this.td).removeClass("x-item-disabled");
8042         this.disabled = false;
8043     }
8044 });
8045 // backwards compat
8046 Roo.ToolbarButton = Roo.Toolbar.Button;
8047
8048 /**
8049  * @class Roo.Toolbar.SplitButton
8050  * @extends Roo.SplitButton
8051  * A menu button that renders into a toolbar.
8052  * @constructor
8053  * Creates a new SplitButton
8054  * @param {Object} config A standard {@link Roo.SplitButton} config object
8055  */
8056 Roo.Toolbar.SplitButton = function(config){
8057     Roo.Toolbar.SplitButton.superclass.constructor.call(this, null, config);
8058 };
8059 Roo.extend(Roo.Toolbar.SplitButton, Roo.SplitButton, {
8060     render : function(td){
8061         this.td = td;
8062         Roo.Toolbar.SplitButton.superclass.render.call(this, td);
8063     },
8064     
8065     /**
8066      * Removes and destroys this button
8067      */
8068     destroy : function(){
8069         Roo.Toolbar.SplitButton.superclass.destroy.call(this);
8070         this.td.parentNode.removeChild(this.td);
8071     },
8072     
8073     /**
8074      * Shows this button
8075      */
8076     show: function(){
8077         this.hidden = false;
8078         this.td.style.display = "";
8079     },
8080     
8081     /**
8082      * Hides this button
8083      */
8084     hide: function(){
8085         this.hidden = true;
8086         this.td.style.display = "none";
8087     }
8088 });
8089
8090 // backwards compat
8091 Roo.Toolbar.MenuButton = Roo.Toolbar.SplitButton;/*
8092  * Based on:
8093  * Ext JS Library 1.1.1
8094  * Copyright(c) 2006-2007, Ext JS, LLC.
8095  *
8096  * Originally Released Under LGPL - original licence link has changed is not relivant.
8097  *
8098  * Fork - LGPL
8099  * <script type="text/javascript">
8100  */
8101  
8102 /**
8103  * @class Roo.PagingToolbar
8104  * @extends Roo.Toolbar
8105  * A specialized toolbar that is bound to a {@link Roo.data.Store} and provides automatic paging controls.
8106  * @constructor
8107  * Create a new PagingToolbar
8108  * @param {Object} config The config object
8109  */
8110 Roo.PagingToolbar = function(el, ds, config)
8111 {
8112     // old args format still supported... - xtype is prefered..
8113     if (typeof(el) == 'object' && el.xtype) {
8114         // created from xtype...
8115         config = el;
8116         ds = el.dataSource;
8117         el = config.container;
8118     }
8119     var items = [];
8120     if (config.items) {
8121         items = config.items;
8122         config.items = [];
8123     }
8124     
8125     Roo.PagingToolbar.superclass.constructor.call(this, el, null, config);
8126     this.ds = ds;
8127     this.cursor = 0;
8128     this.renderButtons(this.el);
8129     this.bind(ds);
8130     
8131     // supprot items array.
8132    
8133     Roo.each(items, function(e) {
8134         this.add(Roo.factory(e));
8135     },this);
8136     
8137 };
8138
8139 Roo.extend(Roo.PagingToolbar, Roo.Toolbar, {
8140     /**
8141      * @cfg {Roo.data.Store} dataSource
8142      * The underlying data store providing the paged data
8143      */
8144     /**
8145      * @cfg {String/HTMLElement/Element} container
8146      * container The id or element that will contain the toolbar
8147      */
8148     /**
8149      * @cfg {Boolean} displayInfo
8150      * True to display the displayMsg (defaults to false)
8151      */
8152     /**
8153      * @cfg {Number} pageSize
8154      * The number of records to display per page (defaults to 20)
8155      */
8156     pageSize: 20,
8157     /**
8158      * @cfg {String} displayMsg
8159      * The paging status message to display (defaults to "Displaying {start} - {end} of {total}")
8160      */
8161     displayMsg : 'Displaying {0} - {1} of {2}',
8162     /**
8163      * @cfg {String} emptyMsg
8164      * The message to display when no records are found (defaults to "No data to display")
8165      */
8166     emptyMsg : 'No data to display',
8167     /**
8168      * Customizable piece of the default paging text (defaults to "Page")
8169      * @type String
8170      */
8171     beforePageText : "Page",
8172     /**
8173      * Customizable piece of the default paging text (defaults to "of %0")
8174      * @type String
8175      */
8176     afterPageText : "of {0}",
8177     /**
8178      * Customizable piece of the default paging text (defaults to "First Page")
8179      * @type String
8180      */
8181     firstText : "First Page",
8182     /**
8183      * Customizable piece of the default paging text (defaults to "Previous Page")
8184      * @type String
8185      */
8186     prevText : "Previous Page",
8187     /**
8188      * Customizable piece of the default paging text (defaults to "Next Page")
8189      * @type String
8190      */
8191     nextText : "Next Page",
8192     /**
8193      * Customizable piece of the default paging text (defaults to "Last Page")
8194      * @type String
8195      */
8196     lastText : "Last Page",
8197     /**
8198      * Customizable piece of the default paging text (defaults to "Refresh")
8199      * @type String
8200      */
8201     refreshText : "Refresh",
8202
8203     // private
8204     renderButtons : function(el){
8205         Roo.PagingToolbar.superclass.render.call(this, el);
8206         this.first = this.addButton({
8207             tooltip: this.firstText,
8208             cls: "x-btn-icon x-grid-page-first",
8209             disabled: true,
8210             handler: this.onClick.createDelegate(this, ["first"])
8211         });
8212         this.prev = this.addButton({
8213             tooltip: this.prevText,
8214             cls: "x-btn-icon x-grid-page-prev",
8215             disabled: true,
8216             handler: this.onClick.createDelegate(this, ["prev"])
8217         });
8218         //this.addSeparator();
8219         this.add(this.beforePageText);
8220         this.field = Roo.get(this.addDom({
8221            tag: "input",
8222            type: "text",
8223            size: "3",
8224            value: "1",
8225            cls: "x-grid-page-number"
8226         }).el);
8227         this.field.on("keydown", this.onPagingKeydown, this);
8228         this.field.on("focus", function(){this.dom.select();});
8229         this.afterTextEl = this.addText(String.format(this.afterPageText, 1));
8230         this.field.setHeight(18);
8231         //this.addSeparator();
8232         this.next = this.addButton({
8233             tooltip: this.nextText,
8234             cls: "x-btn-icon x-grid-page-next",
8235             disabled: true,
8236             handler: this.onClick.createDelegate(this, ["next"])
8237         });
8238         this.last = this.addButton({
8239             tooltip: this.lastText,
8240             cls: "x-btn-icon x-grid-page-last",
8241             disabled: true,
8242             handler: this.onClick.createDelegate(this, ["last"])
8243         });
8244         //this.addSeparator();
8245         this.loading = this.addButton({
8246             tooltip: this.refreshText,
8247             cls: "x-btn-icon x-grid-loading",
8248             handler: this.onClick.createDelegate(this, ["refresh"])
8249         });
8250
8251         if(this.displayInfo){
8252             this.displayEl = Roo.fly(this.el.dom.firstChild).createChild({cls:'x-paging-info'});
8253         }
8254     },
8255
8256     // private
8257     updateInfo : function(){
8258         if(this.displayEl){
8259             var count = this.ds.getCount();
8260             var msg = count == 0 ?
8261                 this.emptyMsg :
8262                 String.format(
8263                     this.displayMsg,
8264                     this.cursor+1, this.cursor+count, this.ds.getTotalCount()    
8265                 );
8266             this.displayEl.update(msg);
8267         }
8268     },
8269
8270     // private
8271     onLoad : function(ds, r, o){
8272        this.cursor = o.params ? o.params.start : 0;
8273        var d = this.getPageData(), ap = d.activePage, ps = d.pages;
8274
8275        this.afterTextEl.el.innerHTML = String.format(this.afterPageText, d.pages);
8276        this.field.dom.value = ap;
8277        this.first.setDisabled(ap == 1);
8278        this.prev.setDisabled(ap == 1);
8279        this.next.setDisabled(ap == ps);
8280        this.last.setDisabled(ap == ps);
8281        this.loading.enable();
8282        this.updateInfo();
8283     },
8284
8285     // private
8286     getPageData : function(){
8287         var total = this.ds.getTotalCount();
8288         return {
8289             total : total,
8290             activePage : Math.ceil((this.cursor+this.pageSize)/this.pageSize),
8291             pages :  total < this.pageSize ? 1 : Math.ceil(total/this.pageSize)
8292         };
8293     },
8294
8295     // private
8296     onLoadError : function(){
8297         this.loading.enable();
8298     },
8299
8300     // private
8301     onPagingKeydown : function(e){
8302         var k = e.getKey();
8303         var d = this.getPageData();
8304         if(k == e.RETURN){
8305             var v = this.field.dom.value, pageNum;
8306             if(!v || isNaN(pageNum = parseInt(v, 10))){
8307                 this.field.dom.value = d.activePage;
8308                 return;
8309             }
8310             pageNum = Math.min(Math.max(1, pageNum), d.pages) - 1;
8311             this.ds.load({params:{start: pageNum * this.pageSize, limit: this.pageSize}});
8312             e.stopEvent();
8313         }
8314         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))
8315         {
8316           var pageNum = (k == e.HOME || (k == e.DOWN && e.ctrlKey) || (k == e.LEFT && e.ctrlKey) || (k == e.PAGEDOWN && e.ctrlKey)) ? 1 : d.pages;
8317           this.field.dom.value = pageNum;
8318           this.ds.load({params:{start: (pageNum - 1) * this.pageSize, limit: this.pageSize}});
8319           e.stopEvent();
8320         }
8321         else if(k == e.UP || k == e.RIGHT || k == e.PAGEUP || k == e.DOWN || k == e.LEFT || k == e.PAGEDOWN)
8322         {
8323           var v = this.field.dom.value, pageNum; 
8324           var increment = (e.shiftKey) ? 10 : 1;
8325           if(k == e.DOWN || k == e.LEFT || k == e.PAGEDOWN) {
8326             increment *= -1;
8327           }
8328           if(!v || isNaN(pageNum = parseInt(v, 10))) {
8329             this.field.dom.value = d.activePage;
8330             return;
8331           }
8332           else if(parseInt(v, 10) + increment >= 1 & parseInt(v, 10) + increment <= d.pages)
8333           {
8334             this.field.dom.value = parseInt(v, 10) + increment;
8335             pageNum = Math.min(Math.max(1, pageNum + increment), d.pages) - 1;
8336             this.ds.load({params:{start: pageNum * this.pageSize, limit: this.pageSize}});
8337           }
8338           e.stopEvent();
8339         }
8340     },
8341
8342     // private
8343     beforeLoad : function(){
8344         if(this.loading){
8345             this.loading.disable();
8346         }
8347     },
8348
8349     // private
8350     onClick : function(which){
8351         var ds = this.ds;
8352         switch(which){
8353             case "first":
8354                 ds.load({params:{start: 0, limit: this.pageSize}});
8355             break;
8356             case "prev":
8357                 ds.load({params:{start: Math.max(0, this.cursor-this.pageSize), limit: this.pageSize}});
8358             break;
8359             case "next":
8360                 ds.load({params:{start: this.cursor+this.pageSize, limit: this.pageSize}});
8361             break;
8362             case "last":
8363                 var total = ds.getTotalCount();
8364                 var extra = total % this.pageSize;
8365                 var lastStart = extra ? (total - extra) : total-this.pageSize;
8366                 ds.load({params:{start: lastStart, limit: this.pageSize}});
8367             break;
8368             case "refresh":
8369                 ds.load({params:{start: this.cursor, limit: this.pageSize}});
8370             break;
8371         }
8372     },
8373
8374     /**
8375      * Unbinds the paging toolbar from the specified {@link Roo.data.Store}
8376      * @param {Roo.data.Store} store The data store to unbind
8377      */
8378     unbind : function(ds){
8379         ds.un("beforeload", this.beforeLoad, this);
8380         ds.un("load", this.onLoad, this);
8381         ds.un("loadexception", this.onLoadError, this);
8382         ds.un("remove", this.updateInfo, this);
8383         ds.un("add", this.updateInfo, this);
8384         this.ds = undefined;
8385     },
8386
8387     /**
8388      * Binds the paging toolbar to the specified {@link Roo.data.Store}
8389      * @param {Roo.data.Store} store The data store to bind
8390      */
8391     bind : function(ds){
8392         ds.on("beforeload", this.beforeLoad, this);
8393         ds.on("load", this.onLoad, this);
8394         ds.on("loadexception", this.onLoadError, this);
8395         ds.on("remove", this.updateInfo, this);
8396         ds.on("add", this.updateInfo, this);
8397         this.ds = ds;
8398     }
8399 });/*
8400  * Based on:
8401  * Ext JS Library 1.1.1
8402  * Copyright(c) 2006-2007, Ext JS, LLC.
8403  *
8404  * Originally Released Under LGPL - original licence link has changed is not relivant.
8405  *
8406  * Fork - LGPL
8407  * <script type="text/javascript">
8408  */
8409
8410 /**
8411  * @class Roo.Resizable
8412  * @extends Roo.util.Observable
8413  * <p>Applies drag handles to an element to make it resizable. The drag handles are inserted into the element
8414  * and positioned absolute. Some elements, such as a textarea or image, don't support this. To overcome that, you can wrap
8415  * 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
8416  * the element will be wrapped for you automatically.</p>
8417  * <p>Here is the list of valid resize handles:</p>
8418  * <pre>
8419 Value   Description
8420 ------  -------------------
8421  'n'     north
8422  's'     south
8423  'e'     east
8424  'w'     west
8425  'nw'    northwest
8426  'sw'    southwest
8427  'se'    southeast
8428  'ne'    northeast
8429  'hd'    horizontal drag
8430  'all'   all
8431 </pre>
8432  * <p>Here's an example showing the creation of a typical Resizable:</p>
8433  * <pre><code>
8434 var resizer = new Roo.Resizable("element-id", {
8435     handles: 'all',
8436     minWidth: 200,
8437     minHeight: 100,
8438     maxWidth: 500,
8439     maxHeight: 400,
8440     pinned: true
8441 });
8442 resizer.on("resize", myHandler);
8443 </code></pre>
8444  * <p>To hide a particular handle, set its display to none in CSS, or through script:<br>
8445  * resizer.east.setDisplayed(false);</p>
8446  * @cfg {Boolean/String/Element} resizeChild True to resize the first child, or id/element to resize (defaults to false)
8447  * @cfg {Array/String} adjustments String "auto" or an array [width, height] with values to be <b>added</b> to the
8448  * resize operation's new size (defaults to [0, 0])
8449  * @cfg {Number} minWidth The minimum width for the element (defaults to 5)
8450  * @cfg {Number} minHeight The minimum height for the element (defaults to 5)
8451  * @cfg {Number} maxWidth The maximum width for the element (defaults to 10000)
8452  * @cfg {Number} maxHeight The maximum height for the element (defaults to 10000)
8453  * @cfg {Boolean} enabled False to disable resizing (defaults to true)
8454  * @cfg {Boolean} wrap True to wrap an element with a div if needed (required for textareas and images, defaults to false)
8455  * @cfg {Number} width The width of the element in pixels (defaults to null)
8456  * @cfg {Number} height The height of the element in pixels (defaults to null)
8457  * @cfg {Boolean} animate True to animate the resize (not compatible with dynamic sizing, defaults to false)
8458  * @cfg {Number} duration Animation duration if animate = true (defaults to .35)
8459  * @cfg {Boolean} dynamic True to resize the element while dragging instead of using a proxy (defaults to false)
8460  * @cfg {String} handles String consisting of the resize handles to display (defaults to undefined)
8461  * @cfg {Boolean} multiDirectional <b>Deprecated</b>.  The old style of adding multi-direction resize handles, deprecated
8462  * in favor of the handles config option (defaults to false)
8463  * @cfg {Boolean} disableTrackOver True to disable mouse tracking. This is only applied at config time. (defaults to false)
8464  * @cfg {String} easing Animation easing if animate = true (defaults to 'easingOutStrong')
8465  * @cfg {Number} widthIncrement The increment to snap the width resize in pixels (dynamic must be true, defaults to 0)
8466  * @cfg {Number} heightIncrement The increment to snap the height resize in pixels (dynamic must be true, defaults to 0)
8467  * @cfg {Boolean} pinned True to ensure that the resize handles are always visible, false to display them only when the
8468  * user mouses over the resizable borders. This is only applied at config time. (defaults to false)
8469  * @cfg {Boolean} preserveRatio True to preserve the original ratio between height and width during resize (defaults to false)
8470  * @cfg {Boolean} transparent True for transparent handles. This is only applied at config time. (defaults to false)
8471  * @cfg {Number} minX The minimum allowed page X for the element (only used for west resizing, defaults to 0)
8472  * @cfg {Number} minY The minimum allowed page Y for the element (only used for north resizing, defaults to 0)
8473  * @cfg {Boolean} draggable Convenience to initialize drag drop (defaults to false)
8474  * @constructor
8475  * Create a new resizable component
8476  * @param {String/HTMLElement/Roo.Element} el The id or element to resize
8477  * @param {Object} config configuration options
8478   */
8479 Roo.Resizable = function(el, config)
8480 {
8481     this.el = Roo.get(el);
8482
8483     if(config && config.wrap){
8484         config.resizeChild = this.el;
8485         this.el = this.el.wrap(typeof config.wrap == "object" ? config.wrap : {cls:"xresizable-wrap"});
8486         this.el.id = this.el.dom.id = config.resizeChild.id + "-rzwrap";
8487         this.el.setStyle("overflow", "hidden");
8488         this.el.setPositioning(config.resizeChild.getPositioning());
8489         config.resizeChild.clearPositioning();
8490         if(!config.width || !config.height){
8491             var csize = config.resizeChild.getSize();
8492             this.el.setSize(csize.width, csize.height);
8493         }
8494         if(config.pinned && !config.adjustments){
8495             config.adjustments = "auto";
8496         }
8497     }
8498
8499     this.proxy = this.el.createProxy({tag: "div", cls: "x-resizable-proxy", id: this.el.id + "-rzproxy"});
8500     this.proxy.unselectable();
8501     this.proxy.enableDisplayMode('block');
8502
8503     Roo.apply(this, config);
8504
8505     if(this.pinned){
8506         this.disableTrackOver = true;
8507         this.el.addClass("x-resizable-pinned");
8508     }
8509     // if the element isn't positioned, make it relative
8510     var position = this.el.getStyle("position");
8511     if(position != "absolute" && position != "fixed"){
8512         this.el.setStyle("position", "relative");
8513     }
8514     if(!this.handles){ // no handles passed, must be legacy style
8515         this.handles = 's,e,se';
8516         if(this.multiDirectional){
8517             this.handles += ',n,w';
8518         }
8519     }
8520     if(this.handles == "all"){
8521         this.handles = "n s e w ne nw se sw";
8522     }
8523     var hs = this.handles.split(/\s*?[,;]\s*?| /);
8524     var ps = Roo.Resizable.positions;
8525     for(var i = 0, len = hs.length; i < len; i++){
8526         if(hs[i] && ps[hs[i]]){
8527             var pos = ps[hs[i]];
8528             this[pos] = new Roo.Resizable.Handle(this, pos, this.disableTrackOver, this.transparent);
8529         }
8530     }
8531     // legacy
8532     this.corner = this.southeast;
8533     
8534     // updateBox = the box can move..
8535     if(this.handles.indexOf("n") != -1 || this.handles.indexOf("w") != -1 || this.handles.indexOf("hd") != -1) {
8536         this.updateBox = true;
8537     }
8538
8539     this.activeHandle = null;
8540
8541     if(this.resizeChild){
8542         if(typeof this.resizeChild == "boolean"){
8543             this.resizeChild = Roo.get(this.el.dom.firstChild, true);
8544         }else{
8545             this.resizeChild = Roo.get(this.resizeChild, true);
8546         }
8547     }
8548     
8549     if(this.adjustments == "auto"){
8550         var rc = this.resizeChild;
8551         var hw = this.west, he = this.east, hn = this.north, hs = this.south;
8552         if(rc && (hw || hn)){
8553             rc.position("relative");
8554             rc.setLeft(hw ? hw.el.getWidth() : 0);
8555             rc.setTop(hn ? hn.el.getHeight() : 0);
8556         }
8557         this.adjustments = [
8558             (he ? -he.el.getWidth() : 0) + (hw ? -hw.el.getWidth() : 0),
8559             (hn ? -hn.el.getHeight() : 0) + (hs ? -hs.el.getHeight() : 0) -1
8560         ];
8561     }
8562
8563     if(this.draggable){
8564         this.dd = this.dynamic ?
8565             this.el.initDD(null) : this.el.initDDProxy(null, {dragElId: this.proxy.id});
8566         this.dd.setHandleElId(this.resizeChild ? this.resizeChild.id : this.el.id);
8567     }
8568
8569     // public events
8570     this.addEvents({
8571         /**
8572          * @event beforeresize
8573          * Fired before resize is allowed. Set enabled to false to cancel resize.
8574          * @param {Roo.Resizable} this
8575          * @param {Roo.EventObject} e The mousedown event
8576          */
8577         "beforeresize" : true,
8578         /**
8579          * @event resizing
8580          * Fired a resizing.
8581          * @param {Roo.Resizable} this
8582          * @param {Number} x The new x position
8583          * @param {Number} y The new y position
8584          * @param {Number} w The new w width
8585          * @param {Number} h The new h hight
8586          * @param {Roo.EventObject} e The mouseup event
8587          */
8588         "resizing" : true,
8589         /**
8590          * @event resize
8591          * Fired after a resize.
8592          * @param {Roo.Resizable} this
8593          * @param {Number} width The new width
8594          * @param {Number} height The new height
8595          * @param {Roo.EventObject} e The mouseup event
8596          */
8597         "resize" : true
8598     });
8599
8600     if(this.width !== null && this.height !== null){
8601         this.resizeTo(this.width, this.height);
8602     }else{
8603         this.updateChildSize();
8604     }
8605     if(Roo.isIE){
8606         this.el.dom.style.zoom = 1;
8607     }
8608     Roo.Resizable.superclass.constructor.call(this);
8609 };
8610
8611 Roo.extend(Roo.Resizable, Roo.util.Observable, {
8612         resizeChild : false,
8613         adjustments : [0, 0],
8614         minWidth : 5,
8615         minHeight : 5,
8616         maxWidth : 10000,
8617         maxHeight : 10000,
8618         enabled : true,
8619         animate : false,
8620         duration : .35,
8621         dynamic : false,
8622         handles : false,
8623         multiDirectional : false,
8624         disableTrackOver : false,
8625         easing : 'easeOutStrong',
8626         widthIncrement : 0,
8627         heightIncrement : 0,
8628         pinned : false,
8629         width : null,
8630         height : null,
8631         preserveRatio : false,
8632         transparent: false,
8633         minX: 0,
8634         minY: 0,
8635         draggable: false,
8636
8637         /**
8638          * @cfg {String/HTMLElement/Element} constrainTo Constrain the resize to a particular element
8639          */
8640         constrainTo: undefined,
8641         /**
8642          * @cfg {Roo.lib.Region} resizeRegion Constrain the resize to a particular region
8643          */
8644         resizeRegion: undefined,
8645
8646
8647     /**
8648      * Perform a manual resize
8649      * @param {Number} width
8650      * @param {Number} height
8651      */
8652     resizeTo : function(width, height){
8653         this.el.setSize(width, height);
8654         this.updateChildSize();
8655         this.fireEvent("resize", this, width, height, null);
8656     },
8657
8658     // private
8659     startSizing : function(e, handle){
8660         this.fireEvent("beforeresize", this, e);
8661         if(this.enabled){ // 2nd enabled check in case disabled before beforeresize handler
8662
8663             if(!this.overlay){
8664                 this.overlay = this.el.createProxy({tag: "div", cls: "x-resizable-overlay", html: "&#160;"});
8665                 this.overlay.unselectable();
8666                 this.overlay.enableDisplayMode("block");
8667                 this.overlay.on("mousemove", this.onMouseMove, this);
8668                 this.overlay.on("mouseup", this.onMouseUp, this);
8669             }
8670             this.overlay.setStyle("cursor", handle.el.getStyle("cursor"));
8671
8672             this.resizing = true;
8673             this.startBox = this.el.getBox();
8674             this.startPoint = e.getXY();
8675             this.offsets = [(this.startBox.x + this.startBox.width) - this.startPoint[0],
8676                             (this.startBox.y + this.startBox.height) - this.startPoint[1]];
8677
8678             this.overlay.setSize(Roo.lib.Dom.getViewWidth(true), Roo.lib.Dom.getViewHeight(true));
8679             this.overlay.show();
8680
8681             if(this.constrainTo) {
8682                 var ct = Roo.get(this.constrainTo);
8683                 this.resizeRegion = ct.getRegion().adjust(
8684                     ct.getFrameWidth('t'),
8685                     ct.getFrameWidth('l'),
8686                     -ct.getFrameWidth('b'),
8687                     -ct.getFrameWidth('r')
8688                 );
8689             }
8690
8691             this.proxy.setStyle('visibility', 'hidden'); // workaround display none
8692             this.proxy.show();
8693             this.proxy.setBox(this.startBox);
8694             if(!this.dynamic){
8695                 this.proxy.setStyle('visibility', 'visible');
8696             }
8697         }
8698     },
8699
8700     // private
8701     onMouseDown : function(handle, e){
8702         if(this.enabled){
8703             e.stopEvent();
8704             this.activeHandle = handle;
8705             this.startSizing(e, handle);
8706         }
8707     },
8708
8709     // private
8710     onMouseUp : function(e){
8711         var size = this.resizeElement();
8712         this.resizing = false;
8713         this.handleOut();
8714         this.overlay.hide();
8715         this.proxy.hide();
8716         this.fireEvent("resize", this, size.width, size.height, e);
8717     },
8718
8719     // private
8720     updateChildSize : function(){
8721         
8722         if(this.resizeChild){
8723             var el = this.el;
8724             var child = this.resizeChild;
8725             var adj = this.adjustments;
8726             if(el.dom.offsetWidth){
8727                 var b = el.getSize(true);
8728                 child.setSize(b.width+adj[0], b.height+adj[1]);
8729             }
8730             // Second call here for IE
8731             // The first call enables instant resizing and
8732             // the second call corrects scroll bars if they
8733             // exist
8734             if(Roo.isIE){
8735                 setTimeout(function(){
8736                     if(el.dom.offsetWidth){
8737                         var b = el.getSize(true);
8738                         child.setSize(b.width+adj[0], b.height+adj[1]);
8739                     }
8740                 }, 10);
8741             }
8742         }
8743     },
8744
8745     // private
8746     snap : function(value, inc, min){
8747         if(!inc || !value) {
8748             return value;
8749         }
8750         var newValue = value;
8751         var m = value % inc;
8752         if(m > 0){
8753             if(m > (inc/2)){
8754                 newValue = value + (inc-m);
8755             }else{
8756                 newValue = value - m;
8757             }
8758         }
8759         return Math.max(min, newValue);
8760     },
8761
8762     // private
8763     resizeElement : function(){
8764         var box = this.proxy.getBox();
8765         if(this.updateBox){
8766             this.el.setBox(box, false, this.animate, this.duration, null, this.easing);
8767         }else{
8768             this.el.setSize(box.width, box.height, this.animate, this.duration, null, this.easing);
8769         }
8770         this.updateChildSize();
8771         if(!this.dynamic){
8772             this.proxy.hide();
8773         }
8774         return box;
8775     },
8776
8777     // private
8778     constrain : function(v, diff, m, mx){
8779         if(v - diff < m){
8780             diff = v - m;
8781         }else if(v - diff > mx){
8782             diff = mx - v;
8783         }
8784         return diff;
8785     },
8786
8787     // private
8788     onMouseMove : function(e){
8789         
8790         if(this.enabled){
8791             try{// try catch so if something goes wrong the user doesn't get hung
8792
8793             if(this.resizeRegion && !this.resizeRegion.contains(e.getPoint())) {
8794                 return;
8795             }
8796
8797             //var curXY = this.startPoint;
8798             var curSize = this.curSize || this.startBox;
8799             var x = this.startBox.x, y = this.startBox.y;
8800             var ox = x, oy = y;
8801             var w = curSize.width, h = curSize.height;
8802             var ow = w, oh = h;
8803             var mw = this.minWidth, mh = this.minHeight;
8804             var mxw = this.maxWidth, mxh = this.maxHeight;
8805             var wi = this.widthIncrement;
8806             var hi = this.heightIncrement;
8807
8808             var eventXY = e.getXY();
8809             var diffX = -(this.startPoint[0] - Math.max(this.minX, eventXY[0]));
8810             var diffY = -(this.startPoint[1] - Math.max(this.minY, eventXY[1]));
8811
8812             var pos = this.activeHandle.position;
8813
8814             switch(pos){
8815                 case "east":
8816                     w += diffX;
8817                     w = Math.min(Math.max(mw, w), mxw);
8818                     break;
8819              
8820                 case "south":
8821                     h += diffY;
8822                     h = Math.min(Math.max(mh, h), mxh);
8823                     break;
8824                 case "southeast":
8825                     w += diffX;
8826                     h += diffY;
8827                     w = Math.min(Math.max(mw, w), mxw);
8828                     h = Math.min(Math.max(mh, h), mxh);
8829                     break;
8830                 case "north":
8831                     diffY = this.constrain(h, diffY, mh, mxh);
8832                     y += diffY;
8833                     h -= diffY;
8834                     break;
8835                 case "hdrag":
8836                     
8837                     if (wi) {
8838                         var adiffX = Math.abs(diffX);
8839                         var sub = (adiffX % wi); // how much 
8840                         if (sub > (wi/2)) { // far enough to snap
8841                             diffX = (diffX > 0) ? diffX-sub + wi : diffX+sub - wi;
8842                         } else {
8843                             // remove difference.. 
8844                             diffX = (diffX > 0) ? diffX-sub : diffX+sub;
8845                         }
8846                     }
8847                     x += diffX;
8848                     x = Math.max(this.minX, x);
8849                     break;
8850                 case "west":
8851                     diffX = this.constrain(w, diffX, mw, mxw);
8852                     x += diffX;
8853                     w -= diffX;
8854                     break;
8855                 case "northeast":
8856                     w += diffX;
8857                     w = Math.min(Math.max(mw, w), mxw);
8858                     diffY = this.constrain(h, diffY, mh, mxh);
8859                     y += diffY;
8860                     h -= diffY;
8861                     break;
8862                 case "northwest":
8863                     diffX = this.constrain(w, diffX, mw, mxw);
8864                     diffY = this.constrain(h, diffY, mh, mxh);
8865                     y += diffY;
8866                     h -= diffY;
8867                     x += diffX;
8868                     w -= diffX;
8869                     break;
8870                case "southwest":
8871                     diffX = this.constrain(w, diffX, mw, mxw);
8872                     h += diffY;
8873                     h = Math.min(Math.max(mh, h), mxh);
8874                     x += diffX;
8875                     w -= diffX;
8876                     break;
8877             }
8878
8879             var sw = this.snap(w, wi, mw);
8880             var sh = this.snap(h, hi, mh);
8881             if(sw != w || sh != h){
8882                 switch(pos){
8883                     case "northeast":
8884                         y -= sh - h;
8885                     break;
8886                     case "north":
8887                         y -= sh - h;
8888                         break;
8889                     case "southwest":
8890                         x -= sw - w;
8891                     break;
8892                     case "west":
8893                         x -= sw - w;
8894                         break;
8895                     case "northwest":
8896                         x -= sw - w;
8897                         y -= sh - h;
8898                     break;
8899                 }
8900                 w = sw;
8901                 h = sh;
8902             }
8903
8904             if(this.preserveRatio){
8905                 switch(pos){
8906                     case "southeast":
8907                     case "east":
8908                         h = oh * (w/ow);
8909                         h = Math.min(Math.max(mh, h), mxh);
8910                         w = ow * (h/oh);
8911                        break;
8912                     case "south":
8913                         w = ow * (h/oh);
8914                         w = Math.min(Math.max(mw, w), mxw);
8915                         h = oh * (w/ow);
8916                         break;
8917                     case "northeast":
8918                         w = ow * (h/oh);
8919                         w = Math.min(Math.max(mw, w), mxw);
8920                         h = oh * (w/ow);
8921                     break;
8922                     case "north":
8923                         var tw = w;
8924                         w = ow * (h/oh);
8925                         w = Math.min(Math.max(mw, w), mxw);
8926                         h = oh * (w/ow);
8927                         x += (tw - w) / 2;
8928                         break;
8929                     case "southwest":
8930                         h = oh * (w/ow);
8931                         h = Math.min(Math.max(mh, h), mxh);
8932                         var tw = w;
8933                         w = ow * (h/oh);
8934                         x += tw - w;
8935                         break;
8936                     case "west":
8937                         var th = h;
8938                         h = oh * (w/ow);
8939                         h = Math.min(Math.max(mh, h), mxh);
8940                         y += (th - h) / 2;
8941                         var tw = w;
8942                         w = ow * (h/oh);
8943                         x += tw - w;
8944                        break;
8945                     case "northwest":
8946                         var tw = w;
8947                         var th = h;
8948                         h = oh * (w/ow);
8949                         h = Math.min(Math.max(mh, h), mxh);
8950                         w = ow * (h/oh);
8951                         y += th - h;
8952                         x += tw - w;
8953                        break;
8954
8955                 }
8956             }
8957             if (pos == 'hdrag') {
8958                 w = ow;
8959             }
8960             this.proxy.setBounds(x, y, w, h);
8961             if(this.dynamic){
8962                 this.resizeElement();
8963             }
8964             }catch(e){}
8965         }
8966         this.fireEvent("resizing", this, x, y, w, h, e);
8967     },
8968
8969     // private
8970     handleOver : function(){
8971         if(this.enabled){
8972             this.el.addClass("x-resizable-over");
8973         }
8974     },
8975
8976     // private
8977     handleOut : function(){
8978         if(!this.resizing){
8979             this.el.removeClass("x-resizable-over");
8980         }
8981     },
8982
8983     /**
8984      * Returns the element this component is bound to.
8985      * @return {Roo.Element}
8986      */
8987     getEl : function(){
8988         return this.el;
8989     },
8990
8991     /**
8992      * Returns the resizeChild element (or null).
8993      * @return {Roo.Element}
8994      */
8995     getResizeChild : function(){
8996         return this.resizeChild;
8997     },
8998     groupHandler : function()
8999     {
9000         
9001     },
9002     /**
9003      * Destroys this resizable. If the element was wrapped and
9004      * removeEl is not true then the element remains.
9005      * @param {Boolean} removeEl (optional) true to remove the element from the DOM
9006      */
9007     destroy : function(removeEl){
9008         this.proxy.remove();
9009         if(this.overlay){
9010             this.overlay.removeAllListeners();
9011             this.overlay.remove();
9012         }
9013         var ps = Roo.Resizable.positions;
9014         for(var k in ps){
9015             if(typeof ps[k] != "function" && this[ps[k]]){
9016                 var h = this[ps[k]];
9017                 h.el.removeAllListeners();
9018                 h.el.remove();
9019             }
9020         }
9021         if(removeEl){
9022             this.el.update("");
9023             this.el.remove();
9024         }
9025     }
9026 });
9027
9028 // private
9029 // hash to map config positions to true positions
9030 Roo.Resizable.positions = {
9031     n: "north", s: "south", e: "east", w: "west", se: "southeast", sw: "southwest", nw: "northwest", ne: "northeast", 
9032     hd: "hdrag"
9033 };
9034
9035 // private
9036 Roo.Resizable.Handle = function(rz, pos, disableTrackOver, transparent){
9037     if(!this.tpl){
9038         // only initialize the template if resizable is used
9039         var tpl = Roo.DomHelper.createTemplate(
9040             {tag: "div", cls: "x-resizable-handle x-resizable-handle-{0}"}
9041         );
9042         tpl.compile();
9043         Roo.Resizable.Handle.prototype.tpl = tpl;
9044     }
9045     this.position = pos;
9046     this.rz = rz;
9047     // show north drag fro topdra
9048     var handlepos = pos == 'hdrag' ? 'north' : pos;
9049     
9050     this.el = this.tpl.append(rz.el.dom, [handlepos], true);
9051     if (pos == 'hdrag') {
9052         this.el.setStyle('cursor', 'pointer');
9053     }
9054     this.el.unselectable();
9055     if(transparent){
9056         this.el.setOpacity(0);
9057     }
9058     this.el.on("mousedown", this.onMouseDown, this);
9059     if(!disableTrackOver){
9060         this.el.on("mouseover", this.onMouseOver, this);
9061         this.el.on("mouseout", this.onMouseOut, this);
9062     }
9063 };
9064
9065 // private
9066 Roo.Resizable.Handle.prototype = {
9067     afterResize : function(rz){
9068         Roo.log('after?');
9069         // do nothing
9070     },
9071     // private
9072     onMouseDown : function(e){
9073         this.rz.onMouseDown(this, e);
9074     },
9075     // private
9076     onMouseOver : function(e){
9077         this.rz.handleOver(this, e);
9078     },
9079     // private
9080     onMouseOut : function(e){
9081         this.rz.handleOut(this, e);
9082     }
9083 };/*
9084  * Based on:
9085  * Ext JS Library 1.1.1
9086  * Copyright(c) 2006-2007, Ext JS, LLC.
9087  *
9088  * Originally Released Under LGPL - original licence link has changed is not relivant.
9089  *
9090  * Fork - LGPL
9091  * <script type="text/javascript">
9092  */
9093
9094 /**
9095  * @class Roo.Editor
9096  * @extends Roo.Component
9097  * A base editor field that handles displaying/hiding on demand and has some built-in sizing and event handling logic.
9098  * @constructor
9099  * Create a new Editor
9100  * @param {Roo.form.Field} field The Field object (or descendant)
9101  * @param {Object} config The config object
9102  */
9103 Roo.Editor = function(field, config){
9104     Roo.Editor.superclass.constructor.call(this, config);
9105     this.field = field;
9106     this.addEvents({
9107         /**
9108              * @event beforestartedit
9109              * Fires when editing is initiated, but before the value changes.  Editing can be canceled by returning
9110              * false from the handler of this event.
9111              * @param {Editor} this
9112              * @param {Roo.Element} boundEl The underlying element bound to this editor
9113              * @param {Mixed} value The field value being set
9114              */
9115         "beforestartedit" : true,
9116         /**
9117              * @event startedit
9118              * Fires when this editor is displayed
9119              * @param {Roo.Element} boundEl The underlying element bound to this editor
9120              * @param {Mixed} value The starting field value
9121              */
9122         "startedit" : true,
9123         /**
9124              * @event beforecomplete
9125              * Fires after a change has been made to the field, but before the change is reflected in the underlying
9126              * field.  Saving the change to the field can be canceled by returning false from the handler of this event.
9127              * Note that if the value has not changed and ignoreNoChange = true, the editing will still end but this
9128              * event will not fire since no edit actually occurred.
9129              * @param {Editor} this
9130              * @param {Mixed} value The current field value
9131              * @param {Mixed} startValue The original field value
9132              */
9133         "beforecomplete" : true,
9134         /**
9135              * @event complete
9136              * Fires after editing is complete and any changed value has been written to the underlying field.
9137              * @param {Editor} this
9138              * @param {Mixed} value The current field value
9139              * @param {Mixed} startValue The original field value
9140              */
9141         "complete" : true,
9142         /**
9143          * @event specialkey
9144          * Fires when any key related to navigation (arrows, tab, enter, esc, etc.) is pressed.  You can check
9145          * {@link Roo.EventObject#getKey} to determine which key was pressed.
9146          * @param {Roo.form.Field} this
9147          * @param {Roo.EventObject} e The event object
9148          */
9149         "specialkey" : true
9150     });
9151 };
9152
9153 Roo.extend(Roo.Editor, Roo.Component, {
9154     /**
9155      * @cfg {Boolean/String} autosize
9156      * True for the editor to automatically adopt the size of the underlying field, "width" to adopt the width only,
9157      * or "height" to adopt the height only (defaults to false)
9158      */
9159     /**
9160      * @cfg {Boolean} revertInvalid
9161      * True to automatically revert the field value and cancel the edit when the user completes an edit and the field
9162      * validation fails (defaults to true)
9163      */
9164     /**
9165      * @cfg {Boolean} ignoreNoChange
9166      * True to skip the the edit completion process (no save, no events fired) if the user completes an edit and
9167      * the value has not changed (defaults to false).  Applies only to string values - edits for other data types
9168      * will never be ignored.
9169      */
9170     /**
9171      * @cfg {Boolean} hideEl
9172      * False to keep the bound element visible while the editor is displayed (defaults to true)
9173      */
9174     /**
9175      * @cfg {Mixed} value
9176      * The data value of the underlying field (defaults to "")
9177      */
9178     value : "",
9179     /**
9180      * @cfg {String} alignment
9181      * The position to align to (see {@link Roo.Element#alignTo} for more details, defaults to "c-c?").
9182      */
9183     alignment: "c-c?",
9184     /**
9185      * @cfg {Boolean/String} shadow "sides" for sides/bottom only, "frame" for 4-way shadow, and "drop"
9186      * for bottom-right shadow (defaults to "frame")
9187      */
9188     shadow : "frame",
9189     /**
9190      * @cfg {Boolean} constrain True to constrain the editor to the viewport
9191      */
9192     constrain : false,
9193     /**
9194      * @cfg {Boolean} completeOnEnter True to complete the edit when the enter key is pressed (defaults to false)
9195      */
9196     completeOnEnter : false,
9197     /**
9198      * @cfg {Boolean} cancelOnEsc True to cancel the edit when the escape key is pressed (defaults to false)
9199      */
9200     cancelOnEsc : false,
9201     /**
9202      * @cfg {Boolean} updateEl True to update the innerHTML of the bound element when the update completes (defaults to false)
9203      */
9204     updateEl : false,
9205
9206     // private
9207     onRender : function(ct, position){
9208         this.el = new Roo.Layer({
9209             shadow: this.shadow,
9210             cls: "x-editor",
9211             parentEl : ct,
9212             shim : this.shim,
9213             shadowOffset:4,
9214             id: this.id,
9215             constrain: this.constrain
9216         });
9217         this.el.setStyle("overflow", Roo.isGecko ? "auto" : "hidden");
9218         if(this.field.msgTarget != 'title'){
9219             this.field.msgTarget = 'qtip';
9220         }
9221         this.field.render(this.el);
9222         if(Roo.isGecko){
9223             this.field.el.dom.setAttribute('autocomplete', 'off');
9224         }
9225         this.field.on("specialkey", this.onSpecialKey, this);
9226         if(this.swallowKeys){
9227             this.field.el.swallowEvent(['keydown','keypress']);
9228         }
9229         this.field.show();
9230         this.field.on("blur", this.onBlur, this);
9231         if(this.field.grow){
9232             this.field.on("autosize", this.el.sync,  this.el, {delay:1});
9233         }
9234     },
9235
9236     onSpecialKey : function(field, e)
9237     {
9238         //Roo.log('editor onSpecialKey');
9239         if(this.completeOnEnter && e.getKey() == e.ENTER){
9240             e.stopEvent();
9241             this.completeEdit();
9242             return;
9243         }
9244         // do not fire special key otherwise it might hide close the editor...
9245         if(e.getKey() == e.ENTER){    
9246             return;
9247         }
9248         if(this.cancelOnEsc && e.getKey() == e.ESC){
9249             this.cancelEdit();
9250             return;
9251         } 
9252         this.fireEvent('specialkey', field, e);
9253     
9254     },
9255
9256     /**
9257      * Starts the editing process and shows the editor.
9258      * @param {String/HTMLElement/Element} el The element to edit
9259      * @param {String} value (optional) A value to initialize the editor with. If a value is not provided, it defaults
9260       * to the innerHTML of el.
9261      */
9262     startEdit : function(el, value){
9263         if(this.editing){
9264             this.completeEdit();
9265         }
9266         this.boundEl = Roo.get(el);
9267         var v = value !== undefined ? value : this.boundEl.dom.innerHTML;
9268         if(!this.rendered){
9269             this.render(this.parentEl || document.body);
9270         }
9271         if(this.fireEvent("beforestartedit", this, this.boundEl, v) === false){
9272             return;
9273         }
9274         this.startValue = v;
9275         this.field.setValue(v);
9276         if(this.autoSize){
9277             var sz = this.boundEl.getSize();
9278             switch(this.autoSize){
9279                 case "width":
9280                 this.setSize(sz.width,  "");
9281                 break;
9282                 case "height":
9283                 this.setSize("",  sz.height);
9284                 break;
9285                 default:
9286                 this.setSize(sz.width,  sz.height);
9287             }
9288         }
9289         this.el.alignTo(this.boundEl, this.alignment);
9290         this.editing = true;
9291         if(Roo.QuickTips){
9292             Roo.QuickTips.disable();
9293         }
9294         this.show();
9295     },
9296
9297     /**
9298      * Sets the height and width of this editor.
9299      * @param {Number} width The new width
9300      * @param {Number} height The new height
9301      */
9302     setSize : function(w, h){
9303         this.field.setSize(w, h);
9304         if(this.el){
9305             this.el.sync();
9306         }
9307     },
9308
9309     /**
9310      * Realigns the editor to the bound field based on the current alignment config value.
9311      */
9312     realign : function(){
9313         this.el.alignTo(this.boundEl, this.alignment);
9314     },
9315
9316     /**
9317      * Ends the editing process, persists the changed value to the underlying field, and hides the editor.
9318      * @param {Boolean} remainVisible Override the default behavior and keep the editor visible after edit (defaults to false)
9319      */
9320     completeEdit : function(remainVisible){
9321         if(!this.editing){
9322             return;
9323         }
9324         var v = this.getValue();
9325         if(this.revertInvalid !== false && !this.field.isValid()){
9326             v = this.startValue;
9327             this.cancelEdit(true);
9328         }
9329         if(String(v) === String(this.startValue) && this.ignoreNoChange){
9330             this.editing = false;
9331             this.hide();
9332             return;
9333         }
9334         if(this.fireEvent("beforecomplete", this, v, this.startValue) !== false){
9335             this.editing = false;
9336             if(this.updateEl && this.boundEl){
9337                 this.boundEl.update(v);
9338             }
9339             if(remainVisible !== true){
9340                 this.hide();
9341             }
9342             this.fireEvent("complete", this, v, this.startValue);
9343         }
9344     },
9345
9346     // private
9347     onShow : function(){
9348         this.el.show();
9349         if(this.hideEl !== false){
9350             this.boundEl.hide();
9351         }
9352         this.field.show();
9353         if(Roo.isIE && !this.fixIEFocus){ // IE has problems with focusing the first time
9354             this.fixIEFocus = true;
9355             this.deferredFocus.defer(50, this);
9356         }else{
9357             this.field.focus();
9358         }
9359         this.fireEvent("startedit", this.boundEl, this.startValue);
9360     },
9361
9362     deferredFocus : function(){
9363         if(this.editing){
9364             this.field.focus();
9365         }
9366     },
9367
9368     /**
9369      * Cancels the editing process and hides the editor without persisting any changes.  The field value will be
9370      * reverted to the original starting value.
9371      * @param {Boolean} remainVisible Override the default behavior and keep the editor visible after
9372      * cancel (defaults to false)
9373      */
9374     cancelEdit : function(remainVisible){
9375         if(this.editing){
9376             this.setValue(this.startValue);
9377             if(remainVisible !== true){
9378                 this.hide();
9379             }
9380         }
9381     },
9382
9383     // private
9384     onBlur : function(){
9385         if(this.allowBlur !== true && this.editing){
9386             this.completeEdit();
9387         }
9388     },
9389
9390     // private
9391     onHide : function(){
9392         if(this.editing){
9393             this.completeEdit();
9394             return;
9395         }
9396         this.field.blur();
9397         if(this.field.collapse){
9398             this.field.collapse();
9399         }
9400         this.el.hide();
9401         if(this.hideEl !== false){
9402             this.boundEl.show();
9403         }
9404         if(Roo.QuickTips){
9405             Roo.QuickTips.enable();
9406         }
9407     },
9408
9409     /**
9410      * Sets the data value of the editor
9411      * @param {Mixed} value Any valid value supported by the underlying field
9412      */
9413     setValue : function(v){
9414         this.field.setValue(v);
9415     },
9416
9417     /**
9418      * Gets the data value of the editor
9419      * @return {Mixed} The data value
9420      */
9421     getValue : function(){
9422         return this.field.getValue();
9423     }
9424 });/*
9425  * Based on:
9426  * Ext JS Library 1.1.1
9427  * Copyright(c) 2006-2007, Ext JS, LLC.
9428  *
9429  * Originally Released Under LGPL - original licence link has changed is not relivant.
9430  *
9431  * Fork - LGPL
9432  * <script type="text/javascript">
9433  */
9434  
9435 /**
9436  * @class Roo.BasicDialog
9437  * @extends Roo.util.Observable
9438  * Lightweight Dialog Class.  The code below shows the creation of a typical dialog using existing HTML markup:
9439  * <pre><code>
9440 var dlg = new Roo.BasicDialog("my-dlg", {
9441     height: 200,
9442     width: 300,
9443     minHeight: 100,
9444     minWidth: 150,
9445     modal: true,
9446     proxyDrag: true,
9447     shadow: true
9448 });
9449 dlg.addKeyListener(27, dlg.hide, dlg); // ESC can also close the dialog
9450 dlg.addButton('OK', dlg.hide, dlg);    // Could call a save function instead of hiding
9451 dlg.addButton('Cancel', dlg.hide, dlg);
9452 dlg.show();
9453 </code></pre>
9454   <b>A Dialog should always be a direct child of the body element.</b>
9455  * @cfg {Boolean/DomHelper} autoCreate True to auto create from scratch, or using a DomHelper Object (defaults to false)
9456  * @cfg {String} title Default text to display in the title bar (defaults to null)
9457  * @cfg {Number} width Width of the dialog in pixels (can also be set via CSS).  Determined by browser if unspecified.
9458  * @cfg {Number} height Height of the dialog in pixels (can also be set via CSS).  Determined by browser if unspecified.
9459  * @cfg {Number} x The default left page coordinate of the dialog (defaults to center screen)
9460  * @cfg {Number} y The default top page coordinate of the dialog (defaults to center screen)
9461  * @cfg {String/Element} animateTarget Id or element from which the dialog should animate while opening
9462  * (defaults to null with no animation)
9463  * @cfg {Boolean} resizable False to disable manual dialog resizing (defaults to true)
9464  * @cfg {String} resizeHandles Which resize handles to display - see the {@link Roo.Resizable} handles config
9465  * property for valid values (defaults to 'all')
9466  * @cfg {Number} minHeight The minimum allowable height for a resizable dialog (defaults to 80)
9467  * @cfg {Number} minWidth The minimum allowable width for a resizable dialog (defaults to 200)
9468  * @cfg {Boolean} modal True to show the dialog modally, preventing user interaction with the rest of the page (defaults to false)
9469  * @cfg {Boolean} autoScroll True to allow the dialog body contents to overflow and display scrollbars (defaults to false)
9470  * @cfg {Boolean} closable False to remove the built-in top-right corner close button (defaults to true)
9471  * @cfg {Boolean} collapsible False to remove the built-in top-right corner collapse button (defaults to true)
9472  * @cfg {Boolean} constraintoviewport True to keep the dialog constrained within the visible viewport boundaries (defaults to true)
9473  * @cfg {Boolean} syncHeightBeforeShow True to cause the dimensions to be recalculated before the dialog is shown (defaults to false)
9474  * @cfg {Boolean} draggable False to disable dragging of the dialog within the viewport (defaults to true)
9475  * @cfg {Boolean} autoTabs If true, all elements with class 'x-dlg-tab' will get automatically converted to tabs (defaults to false)
9476  * @cfg {String} tabTag The tag name of tab elements, used when autoTabs = true (defaults to 'div')
9477  * @cfg {Boolean} proxyDrag True to drag a lightweight proxy element rather than the dialog itself, used when
9478  * draggable = true (defaults to false)
9479  * @cfg {Boolean} fixedcenter True to ensure that anytime the dialog is shown or resized it gets centered (defaults to false)
9480  * @cfg {Boolean/String} shadow True or "sides" for the default effect, "frame" for 4-way shadow, and "drop" for bottom-right
9481  * shadow (defaults to false)
9482  * @cfg {Number} shadowOffset The number of pixels to offset the shadow if displayed (defaults to 5)
9483  * @cfg {String} buttonAlign Valid values are "left," "center" and "right" (defaults to "right")
9484  * @cfg {Number} minButtonWidth Minimum width of all dialog buttons (defaults to 75)
9485  * @cfg {Array} buttons Array of buttons
9486  * @cfg {Boolean} shim True to create an iframe shim that prevents selects from showing through (defaults to false)
9487  * @constructor
9488  * Create a new BasicDialog.
9489  * @param {String/HTMLElement/Roo.Element} el The container element or DOM node, or its id
9490  * @param {Object} config Configuration options
9491  */
9492 Roo.BasicDialog = function(el, config){
9493     this.el = Roo.get(el);
9494     var dh = Roo.DomHelper;
9495     if(!this.el && config && config.autoCreate){
9496         if(typeof config.autoCreate == "object"){
9497             if(!config.autoCreate.id){
9498                 config.autoCreate.id = el;
9499             }
9500             this.el = dh.append(document.body,
9501                         config.autoCreate, true);
9502         }else{
9503             this.el = dh.append(document.body,
9504                         {tag: "div", id: el, style:'visibility:hidden;'}, true);
9505         }
9506     }
9507     el = this.el;
9508     el.setDisplayed(true);
9509     el.hide = this.hideAction;
9510     this.id = el.id;
9511     el.addClass("x-dlg");
9512
9513     Roo.apply(this, config);
9514
9515     this.proxy = el.createProxy("x-dlg-proxy");
9516     this.proxy.hide = this.hideAction;
9517     this.proxy.setOpacity(.5);
9518     this.proxy.hide();
9519
9520     if(config.width){
9521         el.setWidth(config.width);
9522     }
9523     if(config.height){
9524         el.setHeight(config.height);
9525     }
9526     this.size = el.getSize();
9527     if(typeof config.x != "undefined" && typeof config.y != "undefined"){
9528         this.xy = [config.x,config.y];
9529     }else{
9530         this.xy = el.getCenterXY(true);
9531     }
9532     /** The header element @type Roo.Element */
9533     this.header = el.child("> .x-dlg-hd");
9534     /** The body element @type Roo.Element */
9535     this.body = el.child("> .x-dlg-bd");
9536     /** The footer element @type Roo.Element */
9537     this.footer = el.child("> .x-dlg-ft");
9538
9539     if(!this.header){
9540         this.header = el.createChild({tag: "div", cls:"x-dlg-hd", html: "&#160;"}, this.body ? this.body.dom : null);
9541     }
9542     if(!this.body){
9543         this.body = el.createChild({tag: "div", cls:"x-dlg-bd"});
9544     }
9545
9546     this.header.unselectable();
9547     if(this.title){
9548         this.header.update(this.title);
9549     }
9550     // this element allows the dialog to be focused for keyboard event
9551     this.focusEl = el.createChild({tag: "a", href:"#", cls:"x-dlg-focus", tabIndex:"-1"});
9552     this.focusEl.swallowEvent("click", true);
9553
9554     this.header.wrap({cls:"x-dlg-hd-right"}).wrap({cls:"x-dlg-hd-left"}, true);
9555
9556     // wrap the body and footer for special rendering
9557     this.bwrap = this.body.wrap({tag: "div", cls:"x-dlg-dlg-body"});
9558     if(this.footer){
9559         this.bwrap.dom.appendChild(this.footer.dom);
9560     }
9561
9562     this.bg = this.el.createChild({
9563         tag: "div", cls:"x-dlg-bg",
9564         html: '<div class="x-dlg-bg-left"><div class="x-dlg-bg-right"><div class="x-dlg-bg-center">&#160;</div></div></div>'
9565     });
9566     this.centerBg = this.bg.child("div.x-dlg-bg-center");
9567
9568
9569     if(this.autoScroll !== false && !this.autoTabs){
9570         this.body.setStyle("overflow", "auto");
9571     }
9572
9573     this.toolbox = this.el.createChild({cls: "x-dlg-toolbox"});
9574
9575     if(this.closable !== false){
9576         this.el.addClass("x-dlg-closable");
9577         this.close = this.toolbox.createChild({cls:"x-dlg-close"});
9578         this.close.on("click", this.closeClick, this);
9579         this.close.addClassOnOver("x-dlg-close-over");
9580     }
9581     if(this.collapsible !== false){
9582         this.collapseBtn = this.toolbox.createChild({cls:"x-dlg-collapse"});
9583         this.collapseBtn.on("click", this.collapseClick, this);
9584         this.collapseBtn.addClassOnOver("x-dlg-collapse-over");
9585         this.header.on("dblclick", this.collapseClick, this);
9586     }
9587     if(this.resizable !== false){
9588         this.el.addClass("x-dlg-resizable");
9589         this.resizer = new Roo.Resizable(el, {
9590             minWidth: this.minWidth || 80,
9591             minHeight:this.minHeight || 80,
9592             handles: this.resizeHandles || "all",
9593             pinned: true
9594         });
9595         this.resizer.on("beforeresize", this.beforeResize, this);
9596         this.resizer.on("resize", this.onResize, this);
9597     }
9598     if(this.draggable !== false){
9599         el.addClass("x-dlg-draggable");
9600         if (!this.proxyDrag) {
9601             var dd = new Roo.dd.DD(el.dom.id, "WindowDrag");
9602         }
9603         else {
9604             var dd = new Roo.dd.DDProxy(el.dom.id, "WindowDrag", {dragElId: this.proxy.id});
9605         }
9606         dd.setHandleElId(this.header.id);
9607         dd.endDrag = this.endMove.createDelegate(this);
9608         dd.startDrag = this.startMove.createDelegate(this);
9609         dd.onDrag = this.onDrag.createDelegate(this);
9610         dd.scroll = false;
9611         this.dd = dd;
9612     }
9613     if(this.modal){
9614         this.mask = dh.append(document.body, {tag: "div", cls:"x-dlg-mask"}, true);
9615         this.mask.enableDisplayMode("block");
9616         this.mask.hide();
9617         this.el.addClass("x-dlg-modal");
9618     }
9619     if(this.shadow){
9620         this.shadow = new Roo.Shadow({
9621             mode : typeof this.shadow == "string" ? this.shadow : "sides",
9622             offset : this.shadowOffset
9623         });
9624     }else{
9625         this.shadowOffset = 0;
9626     }
9627     if(Roo.useShims && this.shim !== false){
9628         this.shim = this.el.createShim();
9629         this.shim.hide = this.hideAction;
9630         this.shim.hide();
9631     }else{
9632         this.shim = false;
9633     }
9634     if(this.autoTabs){
9635         this.initTabs();
9636     }
9637     if (this.buttons) { 
9638         var bts= this.buttons;
9639         this.buttons = [];
9640         Roo.each(bts, function(b) {
9641             this.addButton(b);
9642         }, this);
9643     }
9644     
9645     
9646     this.addEvents({
9647         /**
9648          * @event keydown
9649          * Fires when a key is pressed
9650          * @param {Roo.BasicDialog} this
9651          * @param {Roo.EventObject} e
9652          */
9653         "keydown" : true,
9654         /**
9655          * @event move
9656          * Fires when this dialog is moved by the user.
9657          * @param {Roo.BasicDialog} this
9658          * @param {Number} x The new page X
9659          * @param {Number} y The new page Y
9660          */
9661         "move" : true,
9662         /**
9663          * @event resize
9664          * Fires when this dialog is resized by the user.
9665          * @param {Roo.BasicDialog} this
9666          * @param {Number} width The new width
9667          * @param {Number} height The new height
9668          */
9669         "resize" : true,
9670         /**
9671          * @event beforehide
9672          * Fires before this dialog is hidden.
9673          * @param {Roo.BasicDialog} this
9674          */
9675         "beforehide" : true,
9676         /**
9677          * @event hide
9678          * Fires when this dialog is hidden.
9679          * @param {Roo.BasicDialog} this
9680          */
9681         "hide" : true,
9682         /**
9683          * @event beforeshow
9684          * Fires before this dialog is shown.
9685          * @param {Roo.BasicDialog} this
9686          */
9687         "beforeshow" : true,
9688         /**
9689          * @event show
9690          * Fires when this dialog is shown.
9691          * @param {Roo.BasicDialog} this
9692          */
9693         "show" : true
9694     });
9695     el.on("keydown", this.onKeyDown, this);
9696     el.on("mousedown", this.toFront, this);
9697     Roo.EventManager.onWindowResize(this.adjustViewport, this, true);
9698     this.el.hide();
9699     Roo.DialogManager.register(this);
9700     Roo.BasicDialog.superclass.constructor.call(this);
9701 };
9702
9703 Roo.extend(Roo.BasicDialog, Roo.util.Observable, {
9704     shadowOffset: Roo.isIE ? 6 : 5,
9705     minHeight: 80,
9706     minWidth: 200,
9707     minButtonWidth: 75,
9708     defaultButton: null,
9709     buttonAlign: "right",
9710     tabTag: 'div',
9711     firstShow: true,
9712
9713     /**
9714      * Sets the dialog title text
9715      * @param {String} text The title text to display
9716      * @return {Roo.BasicDialog} this
9717      */
9718     setTitle : function(text){
9719         this.header.update(text);
9720         return this;
9721     },
9722
9723     // private
9724     closeClick : function(){
9725         this.hide();
9726     },
9727
9728     // private
9729     collapseClick : function(){
9730         this[this.collapsed ? "expand" : "collapse"]();
9731     },
9732
9733     /**
9734      * Collapses the dialog to its minimized state (only the title bar is visible).
9735      * Equivalent to the user clicking the collapse dialog button.
9736      */
9737     collapse : function(){
9738         if(!this.collapsed){
9739             this.collapsed = true;
9740             this.el.addClass("x-dlg-collapsed");
9741             this.restoreHeight = this.el.getHeight();
9742             this.resizeTo(this.el.getWidth(), this.header.getHeight());
9743         }
9744     },
9745
9746     /**
9747      * Expands a collapsed dialog back to its normal state.  Equivalent to the user
9748      * clicking the expand dialog button.
9749      */
9750     expand : function(){
9751         if(this.collapsed){
9752             this.collapsed = false;
9753             this.el.removeClass("x-dlg-collapsed");
9754             this.resizeTo(this.el.getWidth(), this.restoreHeight);
9755         }
9756     },
9757
9758     /**
9759      * Reinitializes the tabs component, clearing out old tabs and finding new ones.
9760      * @return {Roo.TabPanel} The tabs component
9761      */
9762     initTabs : function(){
9763         var tabs = this.getTabs();
9764         while(tabs.getTab(0)){
9765             tabs.removeTab(0);
9766         }
9767         this.el.select(this.tabTag+'.x-dlg-tab').each(function(el){
9768             var dom = el.dom;
9769             tabs.addTab(Roo.id(dom), dom.title);
9770             dom.title = "";
9771         });
9772         tabs.activate(0);
9773         return tabs;
9774     },
9775
9776     // private
9777     beforeResize : function(){
9778         this.resizer.minHeight = Math.max(this.minHeight, this.getHeaderFooterHeight(true)+40);
9779     },
9780
9781     // private
9782     onResize : function(){
9783         this.refreshSize();
9784         this.syncBodyHeight();
9785         this.adjustAssets();
9786         this.focus();
9787         this.fireEvent("resize", this, this.size.width, this.size.height);
9788     },
9789
9790     // private
9791     onKeyDown : function(e){
9792         if(this.isVisible()){
9793             this.fireEvent("keydown", this, e);
9794         }
9795     },
9796
9797     /**
9798      * Resizes the dialog.
9799      * @param {Number} width
9800      * @param {Number} height
9801      * @return {Roo.BasicDialog} this
9802      */
9803     resizeTo : function(width, height){
9804         this.el.setSize(width, height);
9805         this.size = {width: width, height: height};
9806         this.syncBodyHeight();
9807         if(this.fixedcenter){
9808             this.center();
9809         }
9810         if(this.isVisible()){
9811             this.constrainXY();
9812             this.adjustAssets();
9813         }
9814         this.fireEvent("resize", this, width, height);
9815         return this;
9816     },
9817
9818
9819     /**
9820      * Resizes the dialog to fit the specified content size.
9821      * @param {Number} width
9822      * @param {Number} height
9823      * @return {Roo.BasicDialog} this
9824      */
9825     setContentSize : function(w, h){
9826         h += this.getHeaderFooterHeight() + this.body.getMargins("tb");
9827         w += this.body.getMargins("lr") + this.bwrap.getMargins("lr") + this.centerBg.getPadding("lr");
9828         //if(!this.el.isBorderBox()){
9829             h +=  this.body.getPadding("tb") + this.bwrap.getBorderWidth("tb") + this.body.getBorderWidth("tb") + this.el.getBorderWidth("tb");
9830             w += this.body.getPadding("lr") + this.bwrap.getBorderWidth("lr") + this.body.getBorderWidth("lr") + this.bwrap.getPadding("lr") + this.el.getBorderWidth("lr");
9831         //}
9832         if(this.tabs){
9833             h += this.tabs.stripWrap.getHeight() + this.tabs.bodyEl.getMargins("tb") + this.tabs.bodyEl.getPadding("tb");
9834             w += this.tabs.bodyEl.getMargins("lr") + this.tabs.bodyEl.getPadding("lr");
9835         }
9836         this.resizeTo(w, h);
9837         return this;
9838     },
9839
9840     /**
9841      * Adds a key listener for when this dialog is displayed.  This allows you to hook in a function that will be
9842      * executed in response to a particular key being pressed while the dialog is active.
9843      * @param {Number/Array/Object} key Either the numeric key code, array of key codes or an object with the following options:
9844      *                                  {key: (number or array), shift: (true/false), ctrl: (true/false), alt: (true/false)}
9845      * @param {Function} fn The function to call
9846      * @param {Object} scope (optional) The scope of the function
9847      * @return {Roo.BasicDialog} this
9848      */
9849     addKeyListener : function(key, fn, scope){
9850         var keyCode, shift, ctrl, alt;
9851         if(typeof key == "object" && !(key instanceof Array)){
9852             keyCode = key["key"];
9853             shift = key["shift"];
9854             ctrl = key["ctrl"];
9855             alt = key["alt"];
9856         }else{
9857             keyCode = key;
9858         }
9859         var handler = function(dlg, e){
9860             if((!shift || e.shiftKey) && (!ctrl || e.ctrlKey) &&  (!alt || e.altKey)){
9861                 var k = e.getKey();
9862                 if(keyCode instanceof Array){
9863                     for(var i = 0, len = keyCode.length; i < len; i++){
9864                         if(keyCode[i] == k){
9865                           fn.call(scope || window, dlg, k, e);
9866                           return;
9867                         }
9868                     }
9869                 }else{
9870                     if(k == keyCode){
9871                         fn.call(scope || window, dlg, k, e);
9872                     }
9873                 }
9874             }
9875         };
9876         this.on("keydown", handler);
9877         return this;
9878     },
9879
9880     /**
9881      * Returns the TabPanel component (creates it if it doesn't exist).
9882      * Note: If you wish to simply check for the existence of tabs without creating them,
9883      * check for a null 'tabs' property.
9884      * @return {Roo.TabPanel} The tabs component
9885      */
9886     getTabs : function(){
9887         if(!this.tabs){
9888             this.el.addClass("x-dlg-auto-tabs");
9889             this.body.addClass(this.tabPosition == "bottom" ? "x-tabs-bottom" : "x-tabs-top");
9890             this.tabs = new Roo.TabPanel(this.body.dom, this.tabPosition == "bottom");
9891         }
9892         return this.tabs;
9893     },
9894
9895     /**
9896      * Adds a button to the footer section of the dialog.
9897      * @param {String/Object} config A string becomes the button text, an object can either be a Button config
9898      * object or a valid Roo.DomHelper element config
9899      * @param {Function} handler The function called when the button is clicked
9900      * @param {Object} scope (optional) The scope of the handler function (accepts position as a property)
9901      * @return {Roo.Button} The new button
9902      */
9903     addButton : function(config, handler, scope){
9904         var dh = Roo.DomHelper;
9905         if(!this.footer){
9906             this.footer = dh.append(this.bwrap, {tag: "div", cls:"x-dlg-ft"}, true);
9907         }
9908         if(!this.btnContainer){
9909             var tb = this.footer.createChild({
9910
9911                 cls:"x-dlg-btns x-dlg-btns-"+this.buttonAlign,
9912                 html:'<table cellspacing="0"><tbody><tr></tr></tbody></table><div class="x-clear"></div>'
9913             }, null, true);
9914             this.btnContainer = tb.firstChild.firstChild.firstChild;
9915         }
9916         var bconfig = {
9917             handler: handler,
9918             scope: scope,
9919             minWidth: this.minButtonWidth,
9920             hideParent:true
9921         };
9922         if(typeof config == "string"){
9923             bconfig.text = config;
9924         }else{
9925             if(config.tag){
9926                 bconfig.dhconfig = config;
9927             }else{
9928                 Roo.apply(bconfig, config);
9929             }
9930         }
9931         var fc = false;
9932         if ((typeof(bconfig.position) != 'undefined') && bconfig.position < this.btnContainer.childNodes.length-1) {
9933             bconfig.position = Math.max(0, bconfig.position);
9934             fc = this.btnContainer.childNodes[bconfig.position];
9935         }
9936          
9937         var btn = new Roo.Button(
9938             fc ? 
9939                 this.btnContainer.insertBefore(document.createElement("td"),fc)
9940                 : this.btnContainer.appendChild(document.createElement("td")),
9941             //Roo.get(this.btnContainer).createChild( { tag: 'td'},  fc ),
9942             bconfig
9943         );
9944         this.syncBodyHeight();
9945         if(!this.buttons){
9946             /**
9947              * Array of all the buttons that have been added to this dialog via addButton
9948              * @type Array
9949              */
9950             this.buttons = [];
9951         }
9952         this.buttons.push(btn);
9953         return btn;
9954     },
9955
9956     /**
9957      * Sets the default button to be focused when the dialog is displayed.
9958      * @param {Roo.BasicDialog.Button} btn The button object returned by {@link #addButton}
9959      * @return {Roo.BasicDialog} this
9960      */
9961     setDefaultButton : function(btn){
9962         this.defaultButton = btn;
9963         return this;
9964     },
9965
9966     // private
9967     getHeaderFooterHeight : function(safe){
9968         var height = 0;
9969         if(this.header){
9970            height += this.header.getHeight();
9971         }
9972         if(this.footer){
9973            var fm = this.footer.getMargins();
9974             height += (this.footer.getHeight()+fm.top+fm.bottom);
9975         }
9976         height += this.bwrap.getPadding("tb")+this.bwrap.getBorderWidth("tb");
9977         height += this.centerBg.getPadding("tb");
9978         return height;
9979     },
9980
9981     // private
9982     syncBodyHeight : function()
9983     {
9984         var bd = this.body, // the text
9985             cb = this.centerBg, // wrapper around bottom.. but does not seem to be used..
9986             bw = this.bwrap;
9987         var height = this.size.height - this.getHeaderFooterHeight(false);
9988         bd.setHeight(height-bd.getMargins("tb"));
9989         var hh = this.header.getHeight();
9990         var h = this.size.height-hh;
9991         cb.setHeight(h);
9992         
9993         bw.setLeftTop(cb.getPadding("l"), hh+cb.getPadding("t"));
9994         bw.setHeight(h-cb.getPadding("tb"));
9995         
9996         bw.setWidth(this.el.getWidth(true)-cb.getPadding("lr"));
9997         bd.setWidth(bw.getWidth(true));
9998         if(this.tabs){
9999             this.tabs.syncHeight();
10000             if(Roo.isIE){
10001                 this.tabs.el.repaint();
10002             }
10003         }
10004     },
10005
10006     /**
10007      * Restores the previous state of the dialog if Roo.state is configured.
10008      * @return {Roo.BasicDialog} this
10009      */
10010     restoreState : function(){
10011         var box = Roo.state.Manager.get(this.stateId || (this.el.id + "-state"));
10012         if(box && box.width){
10013             this.xy = [box.x, box.y];
10014             this.resizeTo(box.width, box.height);
10015         }
10016         return this;
10017     },
10018
10019     // private
10020     beforeShow : function(){
10021         this.expand();
10022         if(this.fixedcenter){
10023             this.xy = this.el.getCenterXY(true);
10024         }
10025         if(this.modal){
10026             Roo.get(document.body).addClass("x-body-masked");
10027             this.mask.setSize(Roo.lib.Dom.getViewWidth(true), Roo.lib.Dom.getViewHeight(true));
10028             this.mask.show();
10029         }
10030         this.constrainXY();
10031     },
10032
10033     // private
10034     animShow : function(){
10035         var b = Roo.get(this.animateTarget).getBox();
10036         this.proxy.setSize(b.width, b.height);
10037         this.proxy.setLocation(b.x, b.y);
10038         this.proxy.show();
10039         this.proxy.setBounds(this.xy[0], this.xy[1], this.size.width, this.size.height,
10040                     true, .35, this.showEl.createDelegate(this));
10041     },
10042
10043     /**
10044      * Shows the dialog.
10045      * @param {String/HTMLElement/Roo.Element} animateTarget (optional) Reset the animation target
10046      * @return {Roo.BasicDialog} this
10047      */
10048     show : function(animateTarget){
10049         if (this.fireEvent("beforeshow", this) === false){
10050             return;
10051         }
10052         if(this.syncHeightBeforeShow){
10053             this.syncBodyHeight();
10054         }else if(this.firstShow){
10055             this.firstShow = false;
10056             this.syncBodyHeight(); // sync the height on the first show instead of in the constructor
10057         }
10058         this.animateTarget = animateTarget || this.animateTarget;
10059         if(!this.el.isVisible()){
10060             this.beforeShow();
10061             if(this.animateTarget && Roo.get(this.animateTarget)){
10062                 this.animShow();
10063             }else{
10064                 this.showEl();
10065             }
10066         }
10067         return this;
10068     },
10069
10070     // private
10071     showEl : function(){
10072         this.proxy.hide();
10073         this.el.setXY(this.xy);
10074         this.el.show();
10075         this.adjustAssets(true);
10076         this.toFront();
10077         this.focus();
10078         // IE peekaboo bug - fix found by Dave Fenwick
10079         if(Roo.isIE){
10080             this.el.repaint();
10081         }
10082         this.fireEvent("show", this);
10083     },
10084
10085     /**
10086      * Focuses the dialog.  If a defaultButton is set, it will receive focus, otherwise the
10087      * dialog itself will receive focus.
10088      */
10089     focus : function(){
10090         if(this.defaultButton){
10091             this.defaultButton.focus();
10092         }else{
10093             this.focusEl.focus();
10094         }
10095     },
10096
10097     // private
10098     constrainXY : function(){
10099         if(this.constraintoviewport !== false){
10100             if(!this.viewSize){
10101                 if(this.container){
10102                     var s = this.container.getSize();
10103                     this.viewSize = [s.width, s.height];
10104                 }else{
10105                     this.viewSize = [Roo.lib.Dom.getViewWidth(),Roo.lib.Dom.getViewHeight()];
10106                 }
10107             }
10108             var s = Roo.get(this.container||document).getScroll();
10109
10110             var x = this.xy[0], y = this.xy[1];
10111             var w = this.size.width, h = this.size.height;
10112             var vw = this.viewSize[0], vh = this.viewSize[1];
10113             // only move it if it needs it
10114             var moved = false;
10115             // first validate right/bottom
10116             if(x + w > vw+s.left){
10117                 x = vw - w;
10118                 moved = true;
10119             }
10120             if(y + h > vh+s.top){
10121                 y = vh - h;
10122                 moved = true;
10123             }
10124             // then make sure top/left isn't negative
10125             if(x < s.left){
10126                 x = s.left;
10127                 moved = true;
10128             }
10129             if(y < s.top){
10130                 y = s.top;
10131                 moved = true;
10132             }
10133             if(moved){
10134                 // cache xy
10135                 this.xy = [x, y];
10136                 if(this.isVisible()){
10137                     this.el.setLocation(x, y);
10138                     this.adjustAssets();
10139                 }
10140             }
10141         }
10142     },
10143
10144     // private
10145     onDrag : function(){
10146         if(!this.proxyDrag){
10147             this.xy = this.el.getXY();
10148             this.adjustAssets();
10149         }
10150     },
10151
10152     // private
10153     adjustAssets : function(doShow){
10154         var x = this.xy[0], y = this.xy[1];
10155         var w = this.size.width, h = this.size.height;
10156         if(doShow === true){
10157             if(this.shadow){
10158                 this.shadow.show(this.el);
10159             }
10160             if(this.shim){
10161                 this.shim.show();
10162             }
10163         }
10164         if(this.shadow && this.shadow.isVisible()){
10165             this.shadow.show(this.el);
10166         }
10167         if(this.shim && this.shim.isVisible()){
10168             this.shim.setBounds(x, y, w, h);
10169         }
10170     },
10171
10172     // private
10173     adjustViewport : function(w, h){
10174         if(!w || !h){
10175             w = Roo.lib.Dom.getViewWidth();
10176             h = Roo.lib.Dom.getViewHeight();
10177         }
10178         // cache the size
10179         this.viewSize = [w, h];
10180         if(this.modal && this.mask.isVisible()){
10181             this.mask.setSize(w, h); // first make sure the mask isn't causing overflow
10182             this.mask.setSize(Roo.lib.Dom.getViewWidth(true), Roo.lib.Dom.getViewHeight(true));
10183         }
10184         if(this.isVisible()){
10185             this.constrainXY();
10186         }
10187     },
10188
10189     /**
10190      * Destroys this dialog and all its supporting elements (including any tabs, shim,
10191      * shadow, proxy, mask, etc.)  Also removes all event listeners.
10192      * @param {Boolean} removeEl (optional) true to remove the element from the DOM
10193      */
10194     destroy : function(removeEl){
10195         if(this.isVisible()){
10196             this.animateTarget = null;
10197             this.hide();
10198         }
10199         Roo.EventManager.removeResizeListener(this.adjustViewport, this);
10200         if(this.tabs){
10201             this.tabs.destroy(removeEl);
10202         }
10203         Roo.destroy(
10204              this.shim,
10205              this.proxy,
10206              this.resizer,
10207              this.close,
10208              this.mask
10209         );
10210         if(this.dd){
10211             this.dd.unreg();
10212         }
10213         if(this.buttons){
10214            for(var i = 0, len = this.buttons.length; i < len; i++){
10215                this.buttons[i].destroy();
10216            }
10217         }
10218         this.el.removeAllListeners();
10219         if(removeEl === true){
10220             this.el.update("");
10221             this.el.remove();
10222         }
10223         Roo.DialogManager.unregister(this);
10224     },
10225
10226     // private
10227     startMove : function(){
10228         if(this.proxyDrag){
10229             this.proxy.show();
10230         }
10231         if(this.constraintoviewport !== false){
10232             this.dd.constrainTo(document.body, {right: this.shadowOffset, bottom: this.shadowOffset});
10233         }
10234     },
10235
10236     // private
10237     endMove : function(){
10238         if(!this.proxyDrag){
10239             Roo.dd.DD.prototype.endDrag.apply(this.dd, arguments);
10240         }else{
10241             Roo.dd.DDProxy.prototype.endDrag.apply(this.dd, arguments);
10242             this.proxy.hide();
10243         }
10244         this.refreshSize();
10245         this.adjustAssets();
10246         this.focus();
10247         this.fireEvent("move", this, this.xy[0], this.xy[1]);
10248     },
10249
10250     /**
10251      * Brings this dialog to the front of any other visible dialogs
10252      * @return {Roo.BasicDialog} this
10253      */
10254     toFront : function(){
10255         Roo.DialogManager.bringToFront(this);
10256         return this;
10257     },
10258
10259     /**
10260      * Sends this dialog to the back (under) of any other visible dialogs
10261      * @return {Roo.BasicDialog} this
10262      */
10263     toBack : function(){
10264         Roo.DialogManager.sendToBack(this);
10265         return this;
10266     },
10267
10268     /**
10269      * Centers this dialog in the viewport
10270      * @return {Roo.BasicDialog} this
10271      */
10272     center : function(){
10273         var xy = this.el.getCenterXY(true);
10274         this.moveTo(xy[0], xy[1]);
10275         return this;
10276     },
10277
10278     /**
10279      * Moves the dialog's top-left corner to the specified point
10280      * @param {Number} x
10281      * @param {Number} y
10282      * @return {Roo.BasicDialog} this
10283      */
10284     moveTo : function(x, y){
10285         this.xy = [x,y];
10286         if(this.isVisible()){
10287             this.el.setXY(this.xy);
10288             this.adjustAssets();
10289         }
10290         return this;
10291     },
10292
10293     /**
10294      * Aligns the dialog to the specified element
10295      * @param {String/HTMLElement/Roo.Element} element The element to align to.
10296      * @param {String} position The position to align to (see {@link Roo.Element#alignTo} for more details).
10297      * @param {Array} offsets (optional) Offset the positioning by [x, y]
10298      * @return {Roo.BasicDialog} this
10299      */
10300     alignTo : function(element, position, offsets){
10301         this.xy = this.el.getAlignToXY(element, position, offsets);
10302         if(this.isVisible()){
10303             this.el.setXY(this.xy);
10304             this.adjustAssets();
10305         }
10306         return this;
10307     },
10308
10309     /**
10310      * Anchors an element to another element and realigns it when the window is resized.
10311      * @param {String/HTMLElement/Roo.Element} element The element to align to.
10312      * @param {String} position The position to align to (see {@link Roo.Element#alignTo} for more details)
10313      * @param {Array} offsets (optional) Offset the positioning by [x, y]
10314      * @param {Boolean/Number} monitorScroll (optional) true to monitor body scroll and reposition. If this parameter
10315      * is a number, it is used as the buffer delay (defaults to 50ms).
10316      * @return {Roo.BasicDialog} this
10317      */
10318     anchorTo : function(el, alignment, offsets, monitorScroll){
10319         var action = function(){
10320             this.alignTo(el, alignment, offsets);
10321         };
10322         Roo.EventManager.onWindowResize(action, this);
10323         var tm = typeof monitorScroll;
10324         if(tm != 'undefined'){
10325             Roo.EventManager.on(window, 'scroll', action, this,
10326                 {buffer: tm == 'number' ? monitorScroll : 50});
10327         }
10328         action.call(this);
10329         return this;
10330     },
10331
10332     /**
10333      * Returns true if the dialog is visible
10334      * @return {Boolean}
10335      */
10336     isVisible : function(){
10337         return this.el.isVisible();
10338     },
10339
10340     // private
10341     animHide : function(callback){
10342         var b = Roo.get(this.animateTarget).getBox();
10343         this.proxy.show();
10344         this.proxy.setBounds(this.xy[0], this.xy[1], this.size.width, this.size.height);
10345         this.el.hide();
10346         this.proxy.setBounds(b.x, b.y, b.width, b.height, true, .35,
10347                     this.hideEl.createDelegate(this, [callback]));
10348     },
10349
10350     /**
10351      * Hides the dialog.
10352      * @param {Function} callback (optional) Function to call when the dialog is hidden
10353      * @return {Roo.BasicDialog} this
10354      */
10355     hide : function(callback){
10356         if (this.fireEvent("beforehide", this) === false){
10357             return;
10358         }
10359         if(this.shadow){
10360             this.shadow.hide();
10361         }
10362         if(this.shim) {
10363           this.shim.hide();
10364         }
10365         // sometimes animateTarget seems to get set.. causing problems...
10366         // this just double checks..
10367         if(this.animateTarget && Roo.get(this.animateTarget)) {
10368            this.animHide(callback);
10369         }else{
10370             this.el.hide();
10371             this.hideEl(callback);
10372         }
10373         return this;
10374     },
10375
10376     // private
10377     hideEl : function(callback){
10378         this.proxy.hide();
10379         if(this.modal){
10380             this.mask.hide();
10381             Roo.get(document.body).removeClass("x-body-masked");
10382         }
10383         this.fireEvent("hide", this);
10384         if(typeof callback == "function"){
10385             callback();
10386         }
10387     },
10388
10389     // private
10390     hideAction : function(){
10391         this.setLeft("-10000px");
10392         this.setTop("-10000px");
10393         this.setStyle("visibility", "hidden");
10394     },
10395
10396     // private
10397     refreshSize : function(){
10398         this.size = this.el.getSize();
10399         this.xy = this.el.getXY();
10400         Roo.state.Manager.set(this.stateId || this.el.id + "-state", this.el.getBox());
10401     },
10402
10403     // private
10404     // z-index is managed by the DialogManager and may be overwritten at any time
10405     setZIndex : function(index){
10406         if(this.modal){
10407             this.mask.setStyle("z-index", index);
10408         }
10409         if(this.shim){
10410             this.shim.setStyle("z-index", ++index);
10411         }
10412         if(this.shadow){
10413             this.shadow.setZIndex(++index);
10414         }
10415         this.el.setStyle("z-index", ++index);
10416         if(this.proxy){
10417             this.proxy.setStyle("z-index", ++index);
10418         }
10419         if(this.resizer){
10420             this.resizer.proxy.setStyle("z-index", ++index);
10421         }
10422
10423         this.lastZIndex = index;
10424     },
10425
10426     /**
10427      * Returns the element for this dialog
10428      * @return {Roo.Element} The underlying dialog Element
10429      */
10430     getEl : function(){
10431         return this.el;
10432     }
10433 });
10434
10435 /**
10436  * @class Roo.DialogManager
10437  * Provides global access to BasicDialogs that have been created and
10438  * support for z-indexing (layering) multiple open dialogs.
10439  */
10440 Roo.DialogManager = function(){
10441     var list = {};
10442     var accessList = [];
10443     var front = null;
10444
10445     // private
10446     var sortDialogs = function(d1, d2){
10447         return (!d1._lastAccess || d1._lastAccess < d2._lastAccess) ? -1 : 1;
10448     };
10449
10450     // private
10451     var orderDialogs = function(){
10452         accessList.sort(sortDialogs);
10453         var seed = Roo.DialogManager.zseed;
10454         for(var i = 0, len = accessList.length; i < len; i++){
10455             var dlg = accessList[i];
10456             if(dlg){
10457                 dlg.setZIndex(seed + (i*10));
10458             }
10459         }
10460     };
10461
10462     return {
10463         /**
10464          * The starting z-index for BasicDialogs (defaults to 9000)
10465          * @type Number The z-index value
10466          */
10467         zseed : 9000,
10468
10469         // private
10470         register : function(dlg){
10471             list[dlg.id] = dlg;
10472             accessList.push(dlg);
10473         },
10474
10475         // private
10476         unregister : function(dlg){
10477             delete list[dlg.id];
10478             var i=0;
10479             var len=0;
10480             if(!accessList.indexOf){
10481                 for(  i = 0, len = accessList.length; i < len; i++){
10482                     if(accessList[i] == dlg){
10483                         accessList.splice(i, 1);
10484                         return;
10485                     }
10486                 }
10487             }else{
10488                  i = accessList.indexOf(dlg);
10489                 if(i != -1){
10490                     accessList.splice(i, 1);
10491                 }
10492             }
10493         },
10494
10495         /**
10496          * Gets a registered dialog by id
10497          * @param {String/Object} id The id of the dialog or a dialog
10498          * @return {Roo.BasicDialog} this
10499          */
10500         get : function(id){
10501             return typeof id == "object" ? id : list[id];
10502         },
10503
10504         /**
10505          * Brings the specified dialog to the front
10506          * @param {String/Object} dlg The id of the dialog or a dialog
10507          * @return {Roo.BasicDialog} this
10508          */
10509         bringToFront : function(dlg){
10510             dlg = this.get(dlg);
10511             if(dlg != front){
10512                 front = dlg;
10513                 dlg._lastAccess = new Date().getTime();
10514                 orderDialogs();
10515             }
10516             return dlg;
10517         },
10518
10519         /**
10520          * Sends the specified dialog to the back
10521          * @param {String/Object} dlg The id of the dialog or a dialog
10522          * @return {Roo.BasicDialog} this
10523          */
10524         sendToBack : function(dlg){
10525             dlg = this.get(dlg);
10526             dlg._lastAccess = -(new Date().getTime());
10527             orderDialogs();
10528             return dlg;
10529         },
10530
10531         /**
10532          * Hides all dialogs
10533          */
10534         hideAll : function(){
10535             for(var id in list){
10536                 if(list[id] && typeof list[id] != "function" && list[id].isVisible()){
10537                     list[id].hide();
10538                 }
10539             }
10540         }
10541     };
10542 }();
10543
10544 /**
10545  * @class Roo.LayoutDialog
10546  * @extends Roo.BasicDialog
10547  * Dialog which provides adjustments for working with a layout in a Dialog.
10548  * Add your necessary layout config options to the dialog's config.<br>
10549  * Example usage (including a nested layout):
10550  * <pre><code>
10551 if(!dialog){
10552     dialog = new Roo.LayoutDialog("download-dlg", {
10553         modal: true,
10554         width:600,
10555         height:450,
10556         shadow:true,
10557         minWidth:500,
10558         minHeight:350,
10559         autoTabs:true,
10560         proxyDrag:true,
10561         // layout config merges with the dialog config
10562         center:{
10563             tabPosition: "top",
10564             alwaysShowTabs: true
10565         }
10566     });
10567     dialog.addKeyListener(27, dialog.hide, dialog);
10568     dialog.setDefaultButton(dialog.addButton("Close", dialog.hide, dialog));
10569     dialog.addButton("Build It!", this.getDownload, this);
10570
10571     // we can even add nested layouts
10572     var innerLayout = new Roo.BorderLayout("dl-inner", {
10573         east: {
10574             initialSize: 200,
10575             autoScroll:true,
10576             split:true
10577         },
10578         center: {
10579             autoScroll:true
10580         }
10581     });
10582     innerLayout.beginUpdate();
10583     innerLayout.add("east", new Roo.ContentPanel("dl-details"));
10584     innerLayout.add("center", new Roo.ContentPanel("selection-panel"));
10585     innerLayout.endUpdate(true);
10586
10587     var layout = dialog.getLayout();
10588     layout.beginUpdate();
10589     layout.add("center", new Roo.ContentPanel("standard-panel",
10590                         {title: "Download the Source", fitToFrame:true}));
10591     layout.add("center", new Roo.NestedLayoutPanel(innerLayout,
10592                {title: "Build your own roo.js"}));
10593     layout.getRegion("center").showPanel(sp);
10594     layout.endUpdate();
10595 }
10596 </code></pre>
10597     * @constructor
10598     * @param {String/HTMLElement/Roo.Element} el The id of or container element, or config
10599     * @param {Object} config configuration options
10600   */
10601 Roo.LayoutDialog = function(el, cfg){
10602     
10603     var config=  cfg;
10604     if (typeof(cfg) == 'undefined') {
10605         config = Roo.apply({}, el);
10606         // not sure why we use documentElement here.. - it should always be body.
10607         // IE7 borks horribly if we use documentElement.
10608         // webkit also does not like documentElement - it creates a body element...
10609         el = Roo.get( document.body || document.documentElement ).createChild();
10610         //config.autoCreate = true;
10611     }
10612     
10613     
10614     config.autoTabs = false;
10615     Roo.LayoutDialog.superclass.constructor.call(this, el, config);
10616     this.body.setStyle({overflow:"hidden", position:"relative"});
10617     this.layout = new Roo.BorderLayout(this.body.dom, config);
10618     this.layout.monitorWindowResize = false;
10619     this.el.addClass("x-dlg-auto-layout");
10620     // fix case when center region overwrites center function
10621     this.center = Roo.BasicDialog.prototype.center;
10622     this.on("show", this.layout.layout, this.layout, true);
10623     if (config.items) {
10624         var xitems = config.items;
10625         delete config.items;
10626         Roo.each(xitems, this.addxtype, this);
10627     }
10628     
10629     
10630 };
10631 Roo.extend(Roo.LayoutDialog, Roo.BasicDialog, {
10632     /**
10633      * Ends update of the layout <strike>and resets display to none</strike>. Use standard beginUpdate/endUpdate on the layout.
10634      * @deprecated
10635      */
10636     endUpdate : function(){
10637         this.layout.endUpdate();
10638     },
10639
10640     /**
10641      * Begins an update of the layout <strike>and sets display to block and visibility to hidden</strike>. Use standard beginUpdate/endUpdate on the layout.
10642      *  @deprecated
10643      */
10644     beginUpdate : function(){
10645         this.layout.beginUpdate();
10646     },
10647
10648     /**
10649      * Get the BorderLayout for this dialog
10650      * @return {Roo.BorderLayout}
10651      */
10652     getLayout : function(){
10653         return this.layout;
10654     },
10655
10656     showEl : function(){
10657         Roo.LayoutDialog.superclass.showEl.apply(this, arguments);
10658         if(Roo.isIE7){
10659             this.layout.layout();
10660         }
10661     },
10662
10663     // private
10664     // Use the syncHeightBeforeShow config option to control this automatically
10665     syncBodyHeight : function(){
10666         Roo.LayoutDialog.superclass.syncBodyHeight.call(this);
10667         if(this.layout){this.layout.layout();}
10668     },
10669     
10670       /**
10671      * Add an xtype element (actually adds to the layout.)
10672      * @return {Object} xdata xtype object data.
10673      */
10674     
10675     addxtype : function(c) {
10676         return this.layout.addxtype(c);
10677     }
10678 });/*
10679  * Based on:
10680  * Ext JS Library 1.1.1
10681  * Copyright(c) 2006-2007, Ext JS, LLC.
10682  *
10683  * Originally Released Under LGPL - original licence link has changed is not relivant.
10684  *
10685  * Fork - LGPL
10686  * <script type="text/javascript">
10687  */
10688  
10689 /**
10690  * @class Roo.MessageBox
10691  * Utility class for generating different styles of message boxes.  The alias Roo.Msg can also be used.
10692  * Example usage:
10693  *<pre><code>
10694 // Basic alert:
10695 Roo.Msg.alert('Status', 'Changes saved successfully.');
10696
10697 // Prompt for user data:
10698 Roo.Msg.prompt('Name', 'Please enter your name:', function(btn, text){
10699     if (btn == 'ok'){
10700         // process text value...
10701     }
10702 });
10703
10704 // Show a dialog using config options:
10705 Roo.Msg.show({
10706    title:'Save Changes?',
10707    msg: 'Your are closing a tab that has unsaved changes. Would you like to save your changes?',
10708    buttons: Roo.Msg.YESNOCANCEL,
10709    fn: processResult,
10710    animEl: 'elId'
10711 });
10712 </code></pre>
10713  * @singleton
10714  */
10715 Roo.MessageBox = function(){
10716     var dlg, opt, mask, waitTimer;
10717     var bodyEl, msgEl, textboxEl, textareaEl, progressEl, pp;
10718     var buttons, activeTextEl, bwidth;
10719
10720     // private
10721     var handleButton = function(button){
10722         dlg.hide();
10723         Roo.callback(opt.fn, opt.scope||window, [button, activeTextEl.dom.value], 1);
10724     };
10725
10726     // private
10727     var handleHide = function(){
10728         if(opt && opt.cls){
10729             dlg.el.removeClass(opt.cls);
10730         }
10731         if(waitTimer){
10732             Roo.TaskMgr.stop(waitTimer);
10733             waitTimer = null;
10734         }
10735     };
10736
10737     // private
10738     var updateButtons = function(b){
10739         var width = 0;
10740         if(!b){
10741             buttons["ok"].hide();
10742             buttons["cancel"].hide();
10743             buttons["yes"].hide();
10744             buttons["no"].hide();
10745             dlg.footer.dom.style.display = 'none';
10746             return width;
10747         }
10748         dlg.footer.dom.style.display = '';
10749         for(var k in buttons){
10750             if(typeof buttons[k] != "function"){
10751                 if(b[k]){
10752                     buttons[k].show();
10753                     buttons[k].setText(typeof b[k] == "string" ? b[k] : Roo.MessageBox.buttonText[k]);
10754                     width += buttons[k].el.getWidth()+15;
10755                 }else{
10756                     buttons[k].hide();
10757                 }
10758             }
10759         }
10760         return width;
10761     };
10762
10763     // private
10764     var handleEsc = function(d, k, e){
10765         if(opt && opt.closable !== false){
10766             dlg.hide();
10767         }
10768         if(e){
10769             e.stopEvent();
10770         }
10771     };
10772
10773     return {
10774         /**
10775          * Returns a reference to the underlying {@link Roo.BasicDialog} element
10776          * @return {Roo.BasicDialog} The BasicDialog element
10777          */
10778         getDialog : function(){
10779            if(!dlg){
10780                 dlg = new Roo.BasicDialog("x-msg-box", {
10781                     autoCreate : true,
10782                     shadow: true,
10783                     draggable: true,
10784                     resizable:false,
10785                     constraintoviewport:false,
10786                     fixedcenter:true,
10787                     collapsible : false,
10788                     shim:true,
10789                     modal: true,
10790                     width:400, height:100,
10791                     buttonAlign:"center",
10792                     closeClick : function(){
10793                         if(opt && opt.buttons && opt.buttons.no && !opt.buttons.cancel){
10794                             handleButton("no");
10795                         }else{
10796                             handleButton("cancel");
10797                         }
10798                     }
10799                 });
10800                 dlg.on("hide", handleHide);
10801                 mask = dlg.mask;
10802                 dlg.addKeyListener(27, handleEsc);
10803                 buttons = {};
10804                 var bt = this.buttonText;
10805                 buttons["ok"] = dlg.addButton(bt["ok"], handleButton.createCallback("ok"));
10806                 buttons["yes"] = dlg.addButton(bt["yes"], handleButton.createCallback("yes"));
10807                 buttons["no"] = dlg.addButton(bt["no"], handleButton.createCallback("no"));
10808                 buttons["cancel"] = dlg.addButton(bt["cancel"], handleButton.createCallback("cancel"));
10809                 bodyEl = dlg.body.createChild({
10810
10811                     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>'
10812                 });
10813                 msgEl = bodyEl.dom.firstChild;
10814                 textboxEl = Roo.get(bodyEl.dom.childNodes[2]);
10815                 textboxEl.enableDisplayMode();
10816                 textboxEl.addKeyListener([10,13], function(){
10817                     if(dlg.isVisible() && opt && opt.buttons){
10818                         if(opt.buttons.ok){
10819                             handleButton("ok");
10820                         }else if(opt.buttons.yes){
10821                             handleButton("yes");
10822                         }
10823                     }
10824                 });
10825                 textareaEl = Roo.get(bodyEl.dom.childNodes[3]);
10826                 textareaEl.enableDisplayMode();
10827                 progressEl = Roo.get(bodyEl.dom.childNodes[4]);
10828                 progressEl.enableDisplayMode();
10829                 var pf = progressEl.dom.firstChild;
10830                 if (pf) {
10831                     pp = Roo.get(pf.firstChild);
10832                     pp.setHeight(pf.offsetHeight);
10833                 }
10834                 
10835             }
10836             return dlg;
10837         },
10838
10839         /**
10840          * Updates the message box body text
10841          * @param {String} text (optional) Replaces the message box element's innerHTML with the specified string (defaults to
10842          * the XHTML-compliant non-breaking space character '&amp;#160;')
10843          * @return {Roo.MessageBox} This message box
10844          */
10845         updateText : function(text){
10846             if(!dlg.isVisible() && !opt.width){
10847                 dlg.resizeTo(this.maxWidth, 100); // resize first so content is never clipped from previous shows
10848             }
10849             msgEl.innerHTML = text || '&#160;';
10850       
10851             var cw =  Math.max(msgEl.offsetWidth, msgEl.parentNode.scrollWidth);
10852             //Roo.log("guesed size: " + JSON.stringify([cw,msgEl.offsetWidth, msgEl.parentNode.scrollWidth]));
10853             var w = Math.max(
10854                     Math.min(opt.width || cw , this.maxWidth), 
10855                     Math.max(opt.minWidth || this.minWidth, bwidth)
10856             );
10857             if(opt.prompt){
10858                 activeTextEl.setWidth(w);
10859             }
10860             if(dlg.isVisible()){
10861                 dlg.fixedcenter = false;
10862             }
10863             // to big, make it scroll. = But as usual stupid IE does not support
10864             // !important..
10865             
10866             if ( bodyEl.getHeight() > (Roo.lib.Dom.getViewHeight() - 100)) {
10867                 bodyEl.setHeight ( Roo.lib.Dom.getViewHeight() - 100 );
10868                 bodyEl.dom.style.overflowY = 'auto' + ( Roo.isIE ? '' : ' !important');
10869             } else {
10870                 bodyEl.dom.style.height = '';
10871                 bodyEl.dom.style.overflowY = '';
10872             }
10873             if (cw > w) {
10874                 bodyEl.dom.style.get = 'auto' + ( Roo.isIE ? '' : ' !important');
10875             } else {
10876                 bodyEl.dom.style.overflowX = '';
10877             }
10878             
10879             dlg.setContentSize(w, bodyEl.getHeight());
10880             if(dlg.isVisible()){
10881                 dlg.fixedcenter = true;
10882             }
10883             return this;
10884         },
10885
10886         /**
10887          * Updates a progress-style message box's text and progress bar.  Only relevant on message boxes
10888          * initiated via {@link Roo.MessageBox#progress} or by calling {@link Roo.MessageBox#show} with progress: true.
10889          * @param {Number} value Any number between 0 and 1 (e.g., .5)
10890          * @param {String} text (optional) If defined, the message box's body text is replaced with the specified string (defaults to undefined)
10891          * @return {Roo.MessageBox} This message box
10892          */
10893         updateProgress : function(value, text){
10894             if(text){
10895                 this.updateText(text);
10896             }
10897             if (pp) { // weird bug on my firefox - for some reason this is not defined
10898                 pp.setWidth(Math.floor(value*progressEl.dom.firstChild.offsetWidth));
10899             }
10900             return this;
10901         },        
10902
10903         /**
10904          * Returns true if the message box is currently displayed
10905          * @return {Boolean} True if the message box is visible, else false
10906          */
10907         isVisible : function(){
10908             return dlg && dlg.isVisible();  
10909         },
10910
10911         /**
10912          * Hides the message box if it is displayed
10913          */
10914         hide : function(){
10915             if(this.isVisible()){
10916                 dlg.hide();
10917             }  
10918         },
10919
10920         /**
10921          * Displays a new message box, or reinitializes an existing message box, based on the config options
10922          * passed in. All functions (e.g. prompt, alert, etc) on MessageBox call this function internally.
10923          * The following config object properties are supported:
10924          * <pre>
10925 Property    Type             Description
10926 ----------  ---------------  ------------------------------------------------------------------------------------
10927 animEl            String/Element   An id or Element from which the message box should animate as it opens and
10928                                    closes (defaults to undefined)
10929 buttons           Object/Boolean   A button config object (e.g., Roo.MessageBox.OKCANCEL or {ok:'Foo',
10930                                    cancel:'Bar'}), or false to not show any buttons (defaults to false)
10931 closable          Boolean          False to hide the top-right close button (defaults to true).  Note that
10932                                    progress and wait dialogs will ignore this property and always hide the
10933                                    close button as they can only be closed programmatically.
10934 cls               String           A custom CSS class to apply to the message box element
10935 defaultTextHeight Number           The default height in pixels of the message box's multiline textarea if
10936                                    displayed (defaults to 75)
10937 fn                Function         A callback function to execute after closing the dialog.  The arguments to the
10938                                    function will be btn (the name of the button that was clicked, if applicable,
10939                                    e.g. "ok"), and text (the value of the active text field, if applicable).
10940                                    Progress and wait dialogs will ignore this option since they do not respond to
10941                                    user actions and can only be closed programmatically, so any required function
10942                                    should be called by the same code after it closes the dialog.
10943 icon              String           A CSS class that provides a background image to be used as an icon for
10944                                    the dialog (e.g., Roo.MessageBox.WARNING or 'custom-class', defaults to '')
10945 maxWidth          Number           The maximum width in pixels of the message box (defaults to 600)
10946 minWidth          Number           The minimum width in pixels of the message box (defaults to 100)
10947 modal             Boolean          False to allow user interaction with the page while the message box is
10948                                    displayed (defaults to true)
10949 msg               String           A string that will replace the existing message box body text (defaults
10950                                    to the XHTML-compliant non-breaking space character '&#160;')
10951 multiline         Boolean          True to prompt the user to enter multi-line text (defaults to false)
10952 progress          Boolean          True to display a progress bar (defaults to false)
10953 progressText      String           The text to display inside the progress bar if progress = true (defaults to '')
10954 prompt            Boolean          True to prompt the user to enter single-line text (defaults to false)
10955 proxyDrag         Boolean          True to display a lightweight proxy while dragging (defaults to false)
10956 title             String           The title text
10957 value             String           The string value to set into the active textbox element if displayed
10958 wait              Boolean          True to display a progress bar (defaults to false)
10959 width             Number           The width of the dialog in pixels
10960 </pre>
10961          *
10962          * Example usage:
10963          * <pre><code>
10964 Roo.Msg.show({
10965    title: 'Address',
10966    msg: 'Please enter your address:',
10967    width: 300,
10968    buttons: Roo.MessageBox.OKCANCEL,
10969    multiline: true,
10970    fn: saveAddress,
10971    animEl: 'addAddressBtn'
10972 });
10973 </code></pre>
10974          * @param {Object} config Configuration options
10975          * @return {Roo.MessageBox} This message box
10976          */
10977         show : function(options)
10978         {
10979             
10980             // this causes nightmares if you show one dialog after another
10981             // especially on callbacks..
10982              
10983             if(this.isVisible()){
10984                 
10985                 this.hide();
10986                 Roo.log("[Roo.Messagebox] Show called while message displayed:" );
10987                 Roo.log("Old Dialog Message:" +  msgEl.innerHTML );
10988                 Roo.log("New Dialog Message:" +  options.msg )
10989                 //this.alert("ERROR", "Multiple dialogs where displayed at the same time");
10990                 //throw "Roo.MessageBox ERROR : Multiple dialogs where displayed at the same time";
10991                 
10992             }
10993             var d = this.getDialog();
10994             opt = options;
10995             d.setTitle(opt.title || "&#160;");
10996             d.close.setDisplayed(opt.closable !== false);
10997             activeTextEl = textboxEl;
10998             opt.prompt = opt.prompt || (opt.multiline ? true : false);
10999             if(opt.prompt){
11000                 if(opt.multiline){
11001                     textboxEl.hide();
11002                     textareaEl.show();
11003                     textareaEl.setHeight(typeof opt.multiline == "number" ?
11004                         opt.multiline : this.defaultTextHeight);
11005                     activeTextEl = textareaEl;
11006                 }else{
11007                     textboxEl.show();
11008                     textareaEl.hide();
11009                 }
11010             }else{
11011                 textboxEl.hide();
11012                 textareaEl.hide();
11013             }
11014             progressEl.setDisplayed(opt.progress === true);
11015             this.updateProgress(0);
11016             activeTextEl.dom.value = opt.value || "";
11017             if(opt.prompt){
11018                 dlg.setDefaultButton(activeTextEl);
11019             }else{
11020                 var bs = opt.buttons;
11021                 var db = null;
11022                 if(bs && bs.ok){
11023                     db = buttons["ok"];
11024                 }else if(bs && bs.yes){
11025                     db = buttons["yes"];
11026                 }
11027                 dlg.setDefaultButton(db);
11028             }
11029             bwidth = updateButtons(opt.buttons);
11030             this.updateText(opt.msg);
11031             if(opt.cls){
11032                 d.el.addClass(opt.cls);
11033             }
11034             d.proxyDrag = opt.proxyDrag === true;
11035             d.modal = opt.modal !== false;
11036             d.mask = opt.modal !== false ? mask : false;
11037             if(!d.isVisible()){
11038                 // force it to the end of the z-index stack so it gets a cursor in FF
11039                 document.body.appendChild(dlg.el.dom);
11040                 d.animateTarget = null;
11041                 d.show(options.animEl);
11042             }
11043             return this;
11044         },
11045
11046         /**
11047          * Displays a message box with a progress bar.  This message box has no buttons and is not closeable by
11048          * the user.  You are responsible for updating the progress bar as needed via {@link Roo.MessageBox#updateProgress}
11049          * and closing the message box when the process is complete.
11050          * @param {String} title The title bar text
11051          * @param {String} msg The message box body text
11052          * @return {Roo.MessageBox} This message box
11053          */
11054         progress : function(title, msg){
11055             this.show({
11056                 title : title,
11057                 msg : msg,
11058                 buttons: false,
11059                 progress:true,
11060                 closable:false,
11061                 minWidth: this.minProgressWidth,
11062                 modal : true
11063             });
11064             return this;
11065         },
11066
11067         /**
11068          * Displays a standard read-only message box with an OK button (comparable to the basic JavaScript Window.alert).
11069          * If a callback function is passed it will be called after the user clicks the button, and the
11070          * id of the button that was clicked will be passed as the only parameter to the callback
11071          * (could also be the top-right close button).
11072          * @param {String} title The title bar text
11073          * @param {String} msg The message box body text
11074          * @param {Function} fn (optional) The callback function invoked after the message box is closed
11075          * @param {Object} scope (optional) The scope of the callback function
11076          * @return {Roo.MessageBox} This message box
11077          */
11078         alert : function(title, msg, fn, scope){
11079             this.show({
11080                 title : title,
11081                 msg : msg,
11082                 buttons: this.OK,
11083                 fn: fn,
11084                 scope : scope,
11085                 modal : true
11086             });
11087             return this;
11088         },
11089
11090         /**
11091          * Displays a message box with an infinitely auto-updating progress bar.  This can be used to block user
11092          * interaction while waiting for a long-running process to complete that does not have defined intervals.
11093          * You are responsible for closing the message box when the process is complete.
11094          * @param {String} msg The message box body text
11095          * @param {String} title (optional) The title bar text
11096          * @return {Roo.MessageBox} This message box
11097          */
11098         wait : function(msg, title){
11099             this.show({
11100                 title : title,
11101                 msg : msg,
11102                 buttons: false,
11103                 closable:false,
11104                 progress:true,
11105                 modal:true,
11106                 width:300,
11107                 wait:true
11108             });
11109             waitTimer = Roo.TaskMgr.start({
11110                 run: function(i){
11111                     Roo.MessageBox.updateProgress(((((i+20)%20)+1)*5)*.01);
11112                 },
11113                 interval: 1000
11114             });
11115             return this;
11116         },
11117
11118         /**
11119          * Displays a confirmation message box with Yes and No buttons (comparable to JavaScript's Window.confirm).
11120          * If a callback function is passed it will be called after the user clicks either button, and the id of the
11121          * button that was clicked will be passed as the only parameter to the callback (could also be the top-right close button).
11122          * @param {String} title The title bar text
11123          * @param {String} msg The message box body text
11124          * @param {Function} fn (optional) The callback function invoked after the message box is closed
11125          * @param {Object} scope (optional) The scope of the callback function
11126          * @return {Roo.MessageBox} This message box
11127          */
11128         confirm : function(title, msg, fn, scope){
11129             this.show({
11130                 title : title,
11131                 msg : msg,
11132                 buttons: this.YESNO,
11133                 fn: fn,
11134                 scope : scope,
11135                 modal : true
11136             });
11137             return this;
11138         },
11139
11140         /**
11141          * Displays a message box with OK and Cancel buttons prompting the user to enter some text (comparable to
11142          * JavaScript's Window.prompt).  The prompt can be a single-line or multi-line textbox.  If a callback function
11143          * is passed it will be called after the user clicks either button, and the id of the button that was clicked
11144          * (could also be the top-right close button) and the text that was entered will be passed as the two
11145          * parameters to the callback.
11146          * @param {String} title The title bar text
11147          * @param {String} msg The message box body text
11148          * @param {Function} fn (optional) The callback function invoked after the message box is closed
11149          * @param {Object} scope (optional) The scope of the callback function
11150          * @param {Boolean/Number} multiline (optional) True to create a multiline textbox using the defaultTextHeight
11151          * property, or the height in pixels to create the textbox (defaults to false / single-line)
11152          * @return {Roo.MessageBox} This message box
11153          */
11154         prompt : function(title, msg, fn, scope, multiline){
11155             this.show({
11156                 title : title,
11157                 msg : msg,
11158                 buttons: this.OKCANCEL,
11159                 fn: fn,
11160                 minWidth:250,
11161                 scope : scope,
11162                 prompt:true,
11163                 multiline: multiline,
11164                 modal : true
11165             });
11166             return this;
11167         },
11168
11169         /**
11170          * Button config that displays a single OK button
11171          * @type Object
11172          */
11173         OK : {ok:true},
11174         /**
11175          * Button config that displays Yes and No buttons
11176          * @type Object
11177          */
11178         YESNO : {yes:true, no:true},
11179         /**
11180          * Button config that displays OK and Cancel buttons
11181          * @type Object
11182          */
11183         OKCANCEL : {ok:true, cancel:true},
11184         /**
11185          * Button config that displays Yes, No and Cancel buttons
11186          * @type Object
11187          */
11188         YESNOCANCEL : {yes:true, no:true, cancel:true},
11189
11190         /**
11191          * The default height in pixels of the message box's multiline textarea if displayed (defaults to 75)
11192          * @type Number
11193          */
11194         defaultTextHeight : 75,
11195         /**
11196          * The maximum width in pixels of the message box (defaults to 600)
11197          * @type Number
11198          */
11199         maxWidth : 600,
11200         /**
11201          * The minimum width in pixels of the message box (defaults to 100)
11202          * @type Number
11203          */
11204         minWidth : 100,
11205         /**
11206          * The minimum width in pixels of the message box if it is a progress-style dialog.  This is useful
11207          * for setting a different minimum width than text-only dialogs may need (defaults to 250)
11208          * @type Number
11209          */
11210         minProgressWidth : 250,
11211         /**
11212          * An object containing the default button text strings that can be overriden for localized language support.
11213          * Supported properties are: ok, cancel, yes and no.
11214          * Customize the default text like so: Roo.MessageBox.buttonText.yes = "S?";
11215          * @type Object
11216          */
11217         buttonText : {
11218             ok : "OK",
11219             cancel : "Cancel",
11220             yes : "Yes",
11221             no : "No"
11222         }
11223     };
11224 }();
11225
11226 /**
11227  * Shorthand for {@link Roo.MessageBox}
11228  */
11229 Roo.Msg = Roo.MessageBox;/*
11230  * Based on:
11231  * Ext JS Library 1.1.1
11232  * Copyright(c) 2006-2007, Ext JS, LLC.
11233  *
11234  * Originally Released Under LGPL - original licence link has changed is not relivant.
11235  *
11236  * Fork - LGPL
11237  * <script type="text/javascript">
11238  */
11239 /**
11240  * @class Roo.QuickTips
11241  * Provides attractive and customizable tooltips for any element.
11242  * @singleton
11243  */
11244 Roo.QuickTips = function(){
11245     var el, tipBody, tipBodyText, tipTitle, tm, cfg, close, tagEls = {}, esc, removeCls = null, bdLeft, bdRight;
11246     var ce, bd, xy, dd;
11247     var visible = false, disabled = true, inited = false;
11248     var showProc = 1, hideProc = 1, dismissProc = 1, locks = [];
11249     
11250     var onOver = function(e){
11251         if(disabled){
11252             return;
11253         }
11254         var t = e.getTarget();
11255         if(!t || t.nodeType !== 1 || t == document || t == document.body){
11256             return;
11257         }
11258         if(ce && t == ce.el){
11259             clearTimeout(hideProc);
11260             return;
11261         }
11262         if(t && tagEls[t.id]){
11263             tagEls[t.id].el = t;
11264             showProc = show.defer(tm.showDelay, tm, [tagEls[t.id]]);
11265             return;
11266         }
11267         var ttp, et = Roo.fly(t);
11268         var ns = cfg.namespace;
11269         if(tm.interceptTitles && t.title){
11270             ttp = t.title;
11271             t.qtip = ttp;
11272             t.removeAttribute("title");
11273             e.preventDefault();
11274         }else{
11275             ttp = t.qtip || et.getAttributeNS(ns, cfg.attribute) || et.getAttributeNS(cfg.alt_namespace, cfg.attribute) ;
11276         }
11277         if(ttp){
11278             showProc = show.defer(tm.showDelay, tm, [{
11279                 el: t, 
11280                 text: ttp.replace(/\\n/g,'<br/>'),
11281                 width: et.getAttributeNS(ns, cfg.width),
11282                 autoHide: et.getAttributeNS(ns, cfg.hide) != "user",
11283                 title: et.getAttributeNS(ns, cfg.title),
11284                     cls: et.getAttributeNS(ns, cfg.cls)
11285             }]);
11286         }
11287     };
11288     
11289     var onOut = function(e){
11290         clearTimeout(showProc);
11291         var t = e.getTarget();
11292         if(t && ce && ce.el == t && (tm.autoHide && ce.autoHide !== false)){
11293             hideProc = setTimeout(hide, tm.hideDelay);
11294         }
11295     };
11296     
11297     var onMove = function(e){
11298         if(disabled){
11299             return;
11300         }
11301         xy = e.getXY();
11302         xy[1] += 18;
11303         if(tm.trackMouse && ce){
11304             el.setXY(xy);
11305         }
11306     };
11307     
11308     var onDown = function(e){
11309         clearTimeout(showProc);
11310         clearTimeout(hideProc);
11311         if(!e.within(el)){
11312             if(tm.hideOnClick){
11313                 hide();
11314                 tm.disable();
11315                 tm.enable.defer(100, tm);
11316             }
11317         }
11318     };
11319     
11320     var getPad = function(){
11321         return 2;//bdLeft.getPadding('l')+bdRight.getPadding('r');
11322     };
11323
11324     var show = function(o){
11325         if(disabled){
11326             return;
11327         }
11328         clearTimeout(dismissProc);
11329         ce = o;
11330         if(removeCls){ // in case manually hidden
11331             el.removeClass(removeCls);
11332             removeCls = null;
11333         }
11334         if(ce.cls){
11335             el.addClass(ce.cls);
11336             removeCls = ce.cls;
11337         }
11338         if(ce.title){
11339             tipTitle.update(ce.title);
11340             tipTitle.show();
11341         }else{
11342             tipTitle.update('');
11343             tipTitle.hide();
11344         }
11345         el.dom.style.width  = tm.maxWidth+'px';
11346         //tipBody.dom.style.width = '';
11347         tipBodyText.update(o.text);
11348         var p = getPad(), w = ce.width;
11349         if(!w){
11350             var td = tipBodyText.dom;
11351             var aw = Math.max(td.offsetWidth, td.clientWidth, td.scrollWidth);
11352             if(aw > tm.maxWidth){
11353                 w = tm.maxWidth;
11354             }else if(aw < tm.minWidth){
11355                 w = tm.minWidth;
11356             }else{
11357                 w = aw;
11358             }
11359         }
11360         //tipBody.setWidth(w);
11361         el.setWidth(parseInt(w, 10) + p);
11362         if(ce.autoHide === false){
11363             close.setDisplayed(true);
11364             if(dd){
11365                 dd.unlock();
11366             }
11367         }else{
11368             close.setDisplayed(false);
11369             if(dd){
11370                 dd.lock();
11371             }
11372         }
11373         if(xy){
11374             el.avoidY = xy[1]-18;
11375             el.setXY(xy);
11376         }
11377         if(tm.animate){
11378             el.setOpacity(.1);
11379             el.setStyle("visibility", "visible");
11380             el.fadeIn({callback: afterShow});
11381         }else{
11382             afterShow();
11383         }
11384     };
11385     
11386     var afterShow = function(){
11387         if(ce){
11388             el.show();
11389             esc.enable();
11390             if(tm.autoDismiss && ce.autoHide !== false){
11391                 dismissProc = setTimeout(hide, tm.autoDismissDelay);
11392             }
11393         }
11394     };
11395     
11396     var hide = function(noanim){
11397         clearTimeout(dismissProc);
11398         clearTimeout(hideProc);
11399         ce = null;
11400         if(el.isVisible()){
11401             esc.disable();
11402             if(noanim !== true && tm.animate){
11403                 el.fadeOut({callback: afterHide});
11404             }else{
11405                 afterHide();
11406             } 
11407         }
11408     };
11409     
11410     var afterHide = function(){
11411         el.hide();
11412         if(removeCls){
11413             el.removeClass(removeCls);
11414             removeCls = null;
11415         }
11416     };
11417     
11418     return {
11419         /**
11420         * @cfg {Number} minWidth
11421         * The minimum width of the quick tip (defaults to 40)
11422         */
11423        minWidth : 40,
11424         /**
11425         * @cfg {Number} maxWidth
11426         * The maximum width of the quick tip (defaults to 300)
11427         */
11428        maxWidth : 300,
11429         /**
11430         * @cfg {Boolean} interceptTitles
11431         * True to automatically use the element's DOM title value if available (defaults to false)
11432         */
11433        interceptTitles : false,
11434         /**
11435         * @cfg {Boolean} trackMouse
11436         * True to have the quick tip follow the mouse as it moves over the target element (defaults to false)
11437         */
11438        trackMouse : false,
11439         /**
11440         * @cfg {Boolean} hideOnClick
11441         * True to hide the quick tip if the user clicks anywhere in the document (defaults to true)
11442         */
11443        hideOnClick : true,
11444         /**
11445         * @cfg {Number} showDelay
11446         * Delay in milliseconds before the quick tip displays after the mouse enters the target element (defaults to 500)
11447         */
11448        showDelay : 500,
11449         /**
11450         * @cfg {Number} hideDelay
11451         * Delay in milliseconds before the quick tip hides when autoHide = true (defaults to 200)
11452         */
11453        hideDelay : 200,
11454         /**
11455         * @cfg {Boolean} autoHide
11456         * True to automatically hide the quick tip after the mouse exits the target element (defaults to true).
11457         * Used in conjunction with hideDelay.
11458         */
11459        autoHide : true,
11460         /**
11461         * @cfg {Boolean}
11462         * True to automatically hide the quick tip after a set period of time, regardless of the user's actions
11463         * (defaults to true).  Used in conjunction with autoDismissDelay.
11464         */
11465        autoDismiss : true,
11466         /**
11467         * @cfg {Number}
11468         * Delay in milliseconds before the quick tip hides when autoDismiss = true (defaults to 5000)
11469         */
11470        autoDismissDelay : 5000,
11471        /**
11472         * @cfg {Boolean} animate
11473         * True to turn on fade animation. Defaults to false (ClearType/scrollbar flicker issues in IE7).
11474         */
11475        animate : false,
11476
11477        /**
11478         * @cfg {String} title
11479         * Title text to display (defaults to '').  This can be any valid HTML markup.
11480         */
11481         title: '',
11482        /**
11483         * @cfg {String} text
11484         * Body text to display (defaults to '').  This can be any valid HTML markup.
11485         */
11486         text : '',
11487        /**
11488         * @cfg {String} cls
11489         * A CSS class to apply to the base quick tip element (defaults to '').
11490         */
11491         cls : '',
11492        /**
11493         * @cfg {Number} width
11494         * Width in pixels of the quick tip (defaults to auto).  Width will be ignored if it exceeds the bounds of
11495         * minWidth or maxWidth.
11496         */
11497         width : null,
11498
11499     /**
11500      * Initialize and enable QuickTips for first use.  This should be called once before the first attempt to access
11501      * or display QuickTips in a page.
11502      */
11503        init : function(){
11504           tm = Roo.QuickTips;
11505           cfg = tm.tagConfig;
11506           if(!inited){
11507               if(!Roo.isReady){ // allow calling of init() before onReady
11508                   Roo.onReady(Roo.QuickTips.init, Roo.QuickTips);
11509                   return;
11510               }
11511               el = new Roo.Layer({cls:"x-tip", shadow:"drop", shim: true, constrain:true, shadowOffset:4});
11512               el.fxDefaults = {stopFx: true};
11513               // maximum custom styling
11514               //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>');
11515               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>');              
11516               tipTitle = el.child('h3');
11517               tipTitle.enableDisplayMode("block");
11518               tipBody = el.child('div.x-tip-bd');
11519               tipBodyText = el.child('div.x-tip-bd-inner');
11520               //bdLeft = el.child('div.x-tip-bd-left');
11521               //bdRight = el.child('div.x-tip-bd-right');
11522               close = el.child('div.x-tip-close');
11523               close.enableDisplayMode("block");
11524               close.on("click", hide);
11525               var d = Roo.get(document);
11526               d.on("mousedown", onDown);
11527               d.on("mouseover", onOver);
11528               d.on("mouseout", onOut);
11529               d.on("mousemove", onMove);
11530               esc = d.addKeyListener(27, hide);
11531               esc.disable();
11532               if(Roo.dd.DD){
11533                   dd = el.initDD("default", null, {
11534                       onDrag : function(){
11535                           el.sync();  
11536                       }
11537                   });
11538                   dd.setHandleElId(tipTitle.id);
11539                   dd.lock();
11540               }
11541               inited = true;
11542           }
11543           this.enable(); 
11544        },
11545
11546     /**
11547      * Configures a new quick tip instance and assigns it to a target element.  The following config options
11548      * are supported:
11549      * <pre>
11550 Property    Type                   Description
11551 ----------  ---------------------  ------------------------------------------------------------------------
11552 target      Element/String/Array   An Element, id or array of ids that this quick tip should be tied to
11553      * </ul>
11554      * @param {Object} config The config object
11555      */
11556        register : function(config){
11557            var cs = config instanceof Array ? config : arguments;
11558            for(var i = 0, len = cs.length; i < len; i++) {
11559                var c = cs[i];
11560                var target = c.target;
11561                if(target){
11562                    if(target instanceof Array){
11563                        for(var j = 0, jlen = target.length; j < jlen; j++){
11564                            tagEls[target[j]] = c;
11565                        }
11566                    }else{
11567                        tagEls[typeof target == 'string' ? target : Roo.id(target)] = c;
11568                    }
11569                }
11570            }
11571        },
11572
11573     /**
11574      * Removes this quick tip from its element and destroys it.
11575      * @param {String/HTMLElement/Element} el The element from which the quick tip is to be removed.
11576      */
11577        unregister : function(el){
11578            delete tagEls[Roo.id(el)];
11579        },
11580
11581     /**
11582      * Enable this quick tip.
11583      */
11584        enable : function(){
11585            if(inited && disabled){
11586                locks.pop();
11587                if(locks.length < 1){
11588                    disabled = false;
11589                }
11590            }
11591        },
11592
11593     /**
11594      * Disable this quick tip.
11595      */
11596        disable : function(){
11597           disabled = true;
11598           clearTimeout(showProc);
11599           clearTimeout(hideProc);
11600           clearTimeout(dismissProc);
11601           if(ce){
11602               hide(true);
11603           }
11604           locks.push(1);
11605        },
11606
11607     /**
11608      * Returns true if the quick tip is enabled, else false.
11609      */
11610        isEnabled : function(){
11611             return !disabled;
11612        },
11613
11614         // private
11615        tagConfig : {
11616            namespace : "roo", // was ext?? this may break..
11617            alt_namespace : "ext",
11618            attribute : "qtip",
11619            width : "width",
11620            target : "target",
11621            title : "qtitle",
11622            hide : "hide",
11623            cls : "qclass"
11624        }
11625    };
11626 }();
11627
11628 // backwards compat
11629 Roo.QuickTips.tips = Roo.QuickTips.register;/*
11630  * Based on:
11631  * Ext JS Library 1.1.1
11632  * Copyright(c) 2006-2007, Ext JS, LLC.
11633  *
11634  * Originally Released Under LGPL - original licence link has changed is not relivant.
11635  *
11636  * Fork - LGPL
11637  * <script type="text/javascript">
11638  */
11639  
11640
11641 /**
11642  * @class Roo.tree.TreePanel
11643  * @extends Roo.data.Tree
11644
11645  * @cfg {Boolean} rootVisible false to hide the root node (defaults to true)
11646  * @cfg {Boolean} lines false to disable tree lines (defaults to true)
11647  * @cfg {Boolean} enableDD true to enable drag and drop
11648  * @cfg {Boolean} enableDrag true to enable just drag
11649  * @cfg {Boolean} enableDrop true to enable just drop
11650  * @cfg {Object} dragConfig Custom config to pass to the {@link Roo.tree.TreeDragZone} instance
11651  * @cfg {Object} dropConfig Custom config to pass to the {@link Roo.tree.TreeDropZone} instance
11652  * @cfg {String} ddGroup The DD group this TreePanel belongs to
11653  * @cfg {String} ddAppendOnly True if the tree should only allow append drops (use for trees which are sorted)
11654  * @cfg {Boolean} ddScroll true to enable YUI body scrolling
11655  * @cfg {Boolean} containerScroll true to register this container with ScrollManager
11656  * @cfg {Boolean} hlDrop false to disable node highlight on drop (defaults to the value of Roo.enableFx)
11657  * @cfg {String} hlColor The color of the node highlight (defaults to C3DAF9)
11658  * @cfg {Boolean} animate true to enable animated expand/collapse (defaults to the value of Roo.enableFx)
11659  * @cfg {Boolean} singleExpand true if only 1 node per branch may be expanded
11660  * @cfg {Boolean} selModel A tree selection model to use with this TreePanel (defaults to a {@link Roo.tree.DefaultSelectionModel})
11661  * @cfg {Boolean} loader A TreeLoader for use with this TreePanel
11662  * @cfg {Object|Roo.tree.TreeEditor} editor The TreeEditor or xtype data to display when clicked.
11663  * @cfg {String} pathSeparator The token used to separate sub-paths in path strings (defaults to '/')
11664  * @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>
11665  * @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>
11666  * 
11667  * @constructor
11668  * @param {String/HTMLElement/Element} el The container element
11669  * @param {Object} config
11670  */
11671 Roo.tree.TreePanel = function(el, config){
11672     var root = false;
11673     var loader = false;
11674     if (config.root) {
11675         root = config.root;
11676         delete config.root;
11677     }
11678     if (config.loader) {
11679         loader = config.loader;
11680         delete config.loader;
11681     }
11682     
11683     Roo.apply(this, config);
11684     Roo.tree.TreePanel.superclass.constructor.call(this);
11685     this.el = Roo.get(el);
11686     this.el.addClass('x-tree');
11687     //console.log(root);
11688     if (root) {
11689         this.setRootNode( Roo.factory(root, Roo.tree));
11690     }
11691     if (loader) {
11692         this.loader = Roo.factory(loader, Roo.tree);
11693     }
11694    /**
11695     * Read-only. The id of the container element becomes this TreePanel's id.
11696     */
11697     this.id = this.el.id;
11698     this.addEvents({
11699         /**
11700         * @event beforeload
11701         * Fires before a node is loaded, return false to cancel
11702         * @param {Node} node The node being loaded
11703         */
11704         "beforeload" : true,
11705         /**
11706         * @event load
11707         * Fires when a node is loaded
11708         * @param {Node} node The node that was loaded
11709         */
11710         "load" : true,
11711         /**
11712         * @event textchange
11713         * Fires when the text for a node is changed
11714         * @param {Node} node The node
11715         * @param {String} text The new text
11716         * @param {String} oldText The old text
11717         */
11718         "textchange" : true,
11719         /**
11720         * @event beforeexpand
11721         * Fires before a node is expanded, return false to cancel.
11722         * @param {Node} node The node
11723         * @param {Boolean} deep
11724         * @param {Boolean} anim
11725         */
11726         "beforeexpand" : true,
11727         /**
11728         * @event beforecollapse
11729         * Fires before a node is collapsed, return false to cancel.
11730         * @param {Node} node The node
11731         * @param {Boolean} deep
11732         * @param {Boolean} anim
11733         */
11734         "beforecollapse" : true,
11735         /**
11736         * @event expand
11737         * Fires when a node is expanded
11738         * @param {Node} node The node
11739         */
11740         "expand" : true,
11741         /**
11742         * @event disabledchange
11743         * Fires when the disabled status of a node changes
11744         * @param {Node} node The node
11745         * @param {Boolean} disabled
11746         */
11747         "disabledchange" : true,
11748         /**
11749         * @event collapse
11750         * Fires when a node is collapsed
11751         * @param {Node} node The node
11752         */
11753         "collapse" : true,
11754         /**
11755         * @event beforeclick
11756         * Fires before click processing on a node. Return false to cancel the default action.
11757         * @param {Node} node The node
11758         * @param {Roo.EventObject} e The event object
11759         */
11760         "beforeclick":true,
11761         /**
11762         * @event checkchange
11763         * Fires when a node with a checkbox's checked property changes
11764         * @param {Node} this This node
11765         * @param {Boolean} checked
11766         */
11767         "checkchange":true,
11768         /**
11769         * @event click
11770         * Fires when a node is clicked
11771         * @param {Node} node The node
11772         * @param {Roo.EventObject} e The event object
11773         */
11774         "click":true,
11775         /**
11776         * @event dblclick
11777         * Fires when a node is double clicked
11778         * @param {Node} node The node
11779         * @param {Roo.EventObject} e The event object
11780         */
11781         "dblclick":true,
11782         /**
11783         * @event contextmenu
11784         * Fires when a node is right clicked
11785         * @param {Node} node The node
11786         * @param {Roo.EventObject} e The event object
11787         */
11788         "contextmenu":true,
11789         /**
11790         * @event beforechildrenrendered
11791         * Fires right before the child nodes for a node are rendered
11792         * @param {Node} node The node
11793         */
11794         "beforechildrenrendered":true,
11795         /**
11796         * @event startdrag
11797         * Fires when a node starts being dragged
11798         * @param {Roo.tree.TreePanel} this
11799         * @param {Roo.tree.TreeNode} node
11800         * @param {event} e The raw browser event
11801         */ 
11802        "startdrag" : true,
11803        /**
11804         * @event enddrag
11805         * Fires when a drag operation is complete
11806         * @param {Roo.tree.TreePanel} this
11807         * @param {Roo.tree.TreeNode} node
11808         * @param {event} e The raw browser event
11809         */
11810        "enddrag" : true,
11811        /**
11812         * @event dragdrop
11813         * Fires when a dragged node is dropped on a valid DD target
11814         * @param {Roo.tree.TreePanel} this
11815         * @param {Roo.tree.TreeNode} node
11816         * @param {DD} dd The dd it was dropped on
11817         * @param {event} e The raw browser event
11818         */
11819        "dragdrop" : true,
11820        /**
11821         * @event beforenodedrop
11822         * Fires when a DD object is dropped on a node in this tree for preprocessing. Return false to cancel the drop. The dropEvent
11823         * passed to handlers has the following properties:<br />
11824         * <ul style="padding:5px;padding-left:16px;">
11825         * <li>tree - The TreePanel</li>
11826         * <li>target - The node being targeted for the drop</li>
11827         * <li>data - The drag data from the drag source</li>
11828         * <li>point - The point of the drop - append, above or below</li>
11829         * <li>source - The drag source</li>
11830         * <li>rawEvent - Raw mouse event</li>
11831         * <li>dropNode - Drop node(s) provided by the source <b>OR</b> you can supply node(s)
11832         * to be inserted by setting them on this object.</li>
11833         * <li>cancel - Set this to true to cancel the drop.</li>
11834         * </ul>
11835         * @param {Object} dropEvent
11836         */
11837        "beforenodedrop" : true,
11838        /**
11839         * @event nodedrop
11840         * Fires after a DD object is dropped on a node in this tree. The dropEvent
11841         * passed to handlers has the following properties:<br />
11842         * <ul style="padding:5px;padding-left:16px;">
11843         * <li>tree - The TreePanel</li>
11844         * <li>target - The node being targeted for the drop</li>
11845         * <li>data - The drag data from the drag source</li>
11846         * <li>point - The point of the drop - append, above or below</li>
11847         * <li>source - The drag source</li>
11848         * <li>rawEvent - Raw mouse event</li>
11849         * <li>dropNode - Dropped node(s).</li>
11850         * </ul>
11851         * @param {Object} dropEvent
11852         */
11853        "nodedrop" : true,
11854         /**
11855         * @event nodedragover
11856         * Fires when a tree node is being targeted for a drag drop, return false to signal drop not allowed. The dragOverEvent
11857         * passed to handlers has the following properties:<br />
11858         * <ul style="padding:5px;padding-left:16px;">
11859         * <li>tree - The TreePanel</li>
11860         * <li>target - The node being targeted for the drop</li>
11861         * <li>data - The drag data from the drag source</li>
11862         * <li>point - The point of the drop - append, above or below</li>
11863         * <li>source - The drag source</li>
11864         * <li>rawEvent - Raw mouse event</li>
11865         * <li>dropNode - Drop node(s) provided by the source.</li>
11866         * <li>cancel - Set this to true to signal drop not allowed.</li>
11867         * </ul>
11868         * @param {Object} dragOverEvent
11869         */
11870        "nodedragover" : true,
11871        /**
11872         * @event appendnode
11873         * Fires when append node to the tree
11874         * @param {Roo.tree.TreePanel} this
11875         * @param {Roo.tree.TreeNode} node
11876         * @param {Number} index The index of the newly appended node
11877         */
11878        "appendnode" : true
11879         
11880     });
11881     if(this.singleExpand){
11882        this.on("beforeexpand", this.restrictExpand, this);
11883     }
11884     if (this.editor) {
11885         this.editor.tree = this;
11886         this.editor = Roo.factory(this.editor, Roo.tree);
11887     }
11888     
11889     if (this.selModel) {
11890         this.selModel = Roo.factory(this.selModel, Roo.tree);
11891     }
11892    
11893 };
11894 Roo.extend(Roo.tree.TreePanel, Roo.data.Tree, {
11895     rootVisible : true,
11896     animate: Roo.enableFx,
11897     lines : true,
11898     enableDD : false,
11899     hlDrop : Roo.enableFx,
11900   
11901     renderer: false,
11902     
11903     rendererTip: false,
11904     // private
11905     restrictExpand : function(node){
11906         var p = node.parentNode;
11907         if(p){
11908             if(p.expandedChild && p.expandedChild.parentNode == p){
11909                 p.expandedChild.collapse();
11910             }
11911             p.expandedChild = node;
11912         }
11913     },
11914
11915     // private override
11916     setRootNode : function(node){
11917         Roo.tree.TreePanel.superclass.setRootNode.call(this, node);
11918         if(!this.rootVisible){
11919             node.ui = new Roo.tree.RootTreeNodeUI(node);
11920         }
11921         return node;
11922     },
11923
11924     /**
11925      * Returns the container element for this TreePanel
11926      */
11927     getEl : function(){
11928         return this.el;
11929     },
11930
11931     /**
11932      * Returns the default TreeLoader for this TreePanel
11933      */
11934     getLoader : function(){
11935         return this.loader;
11936     },
11937
11938     /**
11939      * Expand all nodes
11940      */
11941     expandAll : function(){
11942         this.root.expand(true);
11943     },
11944
11945     /**
11946      * Collapse all nodes
11947      */
11948     collapseAll : function(){
11949         this.root.collapse(true);
11950     },
11951
11952     /**
11953      * Returns the selection model used by this TreePanel
11954      */
11955     getSelectionModel : function(){
11956         if(!this.selModel){
11957             this.selModel = new Roo.tree.DefaultSelectionModel();
11958         }
11959         return this.selModel;
11960     },
11961
11962     /**
11963      * Retrieve an array of checked nodes, or an array of a specific attribute of checked nodes (e.g. "id")
11964      * @param {String} attribute (optional) Defaults to null (return the actual nodes)
11965      * @param {TreeNode} startNode (optional) The node to start from, defaults to the root
11966      * @return {Array}
11967      */
11968     getChecked : function(a, startNode){
11969         startNode = startNode || this.root;
11970         var r = [];
11971         var f = function(){
11972             if(this.attributes.checked){
11973                 r.push(!a ? this : (a == 'id' ? this.id : this.attributes[a]));
11974             }
11975         }
11976         startNode.cascade(f);
11977         return r;
11978     },
11979
11980     /**
11981      * Expands a specified path in this TreePanel. A path can be retrieved from a node with {@link Roo.data.Node#getPath}
11982      * @param {String} path
11983      * @param {String} attr (optional) The attribute used in the path (see {@link Roo.data.Node#getPath} for more info)
11984      * @param {Function} callback (optional) The callback to call when the expand is complete. The callback will be called with
11985      * (bSuccess, oLastNode) where bSuccess is if the expand was successful and oLastNode is the last node that was expanded.
11986      */
11987     expandPath : function(path, attr, callback){
11988         attr = attr || "id";
11989         var keys = path.split(this.pathSeparator);
11990         var curNode = this.root;
11991         if(curNode.attributes[attr] != keys[1]){ // invalid root
11992             if(callback){
11993                 callback(false, null);
11994             }
11995             return;
11996         }
11997         var index = 1;
11998         var f = function(){
11999             if(++index == keys.length){
12000                 if(callback){
12001                     callback(true, curNode);
12002                 }
12003                 return;
12004             }
12005             var c = curNode.findChild(attr, keys[index]);
12006             if(!c){
12007                 if(callback){
12008                     callback(false, curNode);
12009                 }
12010                 return;
12011             }
12012             curNode = c;
12013             c.expand(false, false, f);
12014         };
12015         curNode.expand(false, false, f);
12016     },
12017
12018     /**
12019      * Selects the node in this tree at the specified path. A path can be retrieved from a node with {@link Roo.data.Node#getPath}
12020      * @param {String} path
12021      * @param {String} attr (optional) The attribute used in the path (see {@link Roo.data.Node#getPath} for more info)
12022      * @param {Function} callback (optional) The callback to call when the selection is complete. The callback will be called with
12023      * (bSuccess, oSelNode) where bSuccess is if the selection was successful and oSelNode is the selected node.
12024      */
12025     selectPath : function(path, attr, callback){
12026         attr = attr || "id";
12027         var keys = path.split(this.pathSeparator);
12028         var v = keys.pop();
12029         if(keys.length > 0){
12030             var f = function(success, node){
12031                 if(success && node){
12032                     var n = node.findChild(attr, v);
12033                     if(n){
12034                         n.select();
12035                         if(callback){
12036                             callback(true, n);
12037                         }
12038                     }else if(callback){
12039                         callback(false, n);
12040                     }
12041                 }else{
12042                     if(callback){
12043                         callback(false, n);
12044                     }
12045                 }
12046             };
12047             this.expandPath(keys.join(this.pathSeparator), attr, f);
12048         }else{
12049             this.root.select();
12050             if(callback){
12051                 callback(true, this.root);
12052             }
12053         }
12054     },
12055
12056     getTreeEl : function(){
12057         return this.el;
12058     },
12059
12060     /**
12061      * Trigger rendering of this TreePanel
12062      */
12063     render : function(){
12064         if (this.innerCt) {
12065             return this; // stop it rendering more than once!!
12066         }
12067         
12068         this.innerCt = this.el.createChild({tag:"ul",
12069                cls:"x-tree-root-ct " +
12070                (this.lines ? "x-tree-lines" : "x-tree-no-lines")});
12071
12072         if(this.containerScroll){
12073             Roo.dd.ScrollManager.register(this.el);
12074         }
12075         if((this.enableDD || this.enableDrop) && !this.dropZone){
12076            /**
12077             * The dropZone used by this tree if drop is enabled
12078             * @type Roo.tree.TreeDropZone
12079             */
12080              this.dropZone = new Roo.tree.TreeDropZone(this, this.dropConfig || {
12081                ddGroup: this.ddGroup || "TreeDD", appendOnly: this.ddAppendOnly === true
12082            });
12083         }
12084         if((this.enableDD || this.enableDrag) && !this.dragZone){
12085            /**
12086             * The dragZone used by this tree if drag is enabled
12087             * @type Roo.tree.TreeDragZone
12088             */
12089             this.dragZone = new Roo.tree.TreeDragZone(this, this.dragConfig || {
12090                ddGroup: this.ddGroup || "TreeDD",
12091                scroll: this.ddScroll
12092            });
12093         }
12094         this.getSelectionModel().init(this);
12095         if (!this.root) {
12096             Roo.log("ROOT not set in tree");
12097             return this;
12098         }
12099         this.root.render();
12100         if(!this.rootVisible){
12101             this.root.renderChildren();
12102         }
12103         return this;
12104     }
12105 });/*
12106  * Based on:
12107  * Ext JS Library 1.1.1
12108  * Copyright(c) 2006-2007, Ext JS, LLC.
12109  *
12110  * Originally Released Under LGPL - original licence link has changed is not relivant.
12111  *
12112  * Fork - LGPL
12113  * <script type="text/javascript">
12114  */
12115  
12116
12117 /**
12118  * @class Roo.tree.DefaultSelectionModel
12119  * @extends Roo.util.Observable
12120  * The default single selection for a TreePanel.
12121  * @param {Object} cfg Configuration
12122  */
12123 Roo.tree.DefaultSelectionModel = function(cfg){
12124    this.selNode = null;
12125    
12126    
12127    
12128    this.addEvents({
12129        /**
12130         * @event selectionchange
12131         * Fires when the selected node changes
12132         * @param {DefaultSelectionModel} this
12133         * @param {TreeNode} node the new selection
12134         */
12135        "selectionchange" : true,
12136
12137        /**
12138         * @event beforeselect
12139         * Fires before the selected node changes, return false to cancel the change
12140         * @param {DefaultSelectionModel} this
12141         * @param {TreeNode} node the new selection
12142         * @param {TreeNode} node the old selection
12143         */
12144        "beforeselect" : true
12145    });
12146    
12147     Roo.tree.DefaultSelectionModel.superclass.constructor.call(this,cfg);
12148 };
12149
12150 Roo.extend(Roo.tree.DefaultSelectionModel, Roo.util.Observable, {
12151     init : function(tree){
12152         this.tree = tree;
12153         tree.getTreeEl().on("keydown", this.onKeyDown, this);
12154         tree.on("click", this.onNodeClick, this);
12155     },
12156     
12157     onNodeClick : function(node, e){
12158         if (e.ctrlKey && this.selNode == node)  {
12159             this.unselect(node);
12160             return;
12161         }
12162         this.select(node);
12163     },
12164     
12165     /**
12166      * Select a node.
12167      * @param {TreeNode} node The node to select
12168      * @return {TreeNode} The selected node
12169      */
12170     select : function(node){
12171         var last = this.selNode;
12172         if(last != node && this.fireEvent('beforeselect', this, node, last) !== false){
12173             if(last){
12174                 last.ui.onSelectedChange(false);
12175             }
12176             this.selNode = node;
12177             node.ui.onSelectedChange(true);
12178             this.fireEvent("selectionchange", this, node, last);
12179         }
12180         return node;
12181     },
12182     
12183     /**
12184      * Deselect a node.
12185      * @param {TreeNode} node The node to unselect
12186      */
12187     unselect : function(node){
12188         if(this.selNode == node){
12189             this.clearSelections();
12190         }    
12191     },
12192     
12193     /**
12194      * Clear all selections
12195      */
12196     clearSelections : function(){
12197         var n = this.selNode;
12198         if(n){
12199             n.ui.onSelectedChange(false);
12200             this.selNode = null;
12201             this.fireEvent("selectionchange", this, null);
12202         }
12203         return n;
12204     },
12205     
12206     /**
12207      * Get the selected node
12208      * @return {TreeNode} The selected node
12209      */
12210     getSelectedNode : function(){
12211         return this.selNode;    
12212     },
12213     
12214     /**
12215      * Returns true if the node is selected
12216      * @param {TreeNode} node The node to check
12217      * @return {Boolean}
12218      */
12219     isSelected : function(node){
12220         return this.selNode == node;  
12221     },
12222
12223     /**
12224      * Selects the node above the selected node in the tree, intelligently walking the nodes
12225      * @return TreeNode The new selection
12226      */
12227     selectPrevious : function(){
12228         var s = this.selNode || this.lastSelNode;
12229         if(!s){
12230             return null;
12231         }
12232         var ps = s.previousSibling;
12233         if(ps){
12234             if(!ps.isExpanded() || ps.childNodes.length < 1){
12235                 return this.select(ps);
12236             } else{
12237                 var lc = ps.lastChild;
12238                 while(lc && lc.isExpanded() && lc.childNodes.length > 0){
12239                     lc = lc.lastChild;
12240                 }
12241                 return this.select(lc);
12242             }
12243         } else if(s.parentNode && (this.tree.rootVisible || !s.parentNode.isRoot)){
12244             return this.select(s.parentNode);
12245         }
12246         return null;
12247     },
12248
12249     /**
12250      * Selects the node above the selected node in the tree, intelligently walking the nodes
12251      * @return TreeNode The new selection
12252      */
12253     selectNext : function(){
12254         var s = this.selNode || this.lastSelNode;
12255         if(!s){
12256             return null;
12257         }
12258         if(s.firstChild && s.isExpanded()){
12259              return this.select(s.firstChild);
12260          }else if(s.nextSibling){
12261              return this.select(s.nextSibling);
12262          }else if(s.parentNode){
12263             var newS = null;
12264             s.parentNode.bubble(function(){
12265                 if(this.nextSibling){
12266                     newS = this.getOwnerTree().selModel.select(this.nextSibling);
12267                     return false;
12268                 }
12269             });
12270             return newS;
12271          }
12272         return null;
12273     },
12274
12275     onKeyDown : function(e){
12276         var s = this.selNode || this.lastSelNode;
12277         // undesirable, but required
12278         var sm = this;
12279         if(!s){
12280             return;
12281         }
12282         var k = e.getKey();
12283         switch(k){
12284              case e.DOWN:
12285                  e.stopEvent();
12286                  this.selectNext();
12287              break;
12288              case e.UP:
12289                  e.stopEvent();
12290                  this.selectPrevious();
12291              break;
12292              case e.RIGHT:
12293                  e.preventDefault();
12294                  if(s.hasChildNodes()){
12295                      if(!s.isExpanded()){
12296                          s.expand();
12297                      }else if(s.firstChild){
12298                          this.select(s.firstChild, e);
12299                      }
12300                  }
12301              break;
12302              case e.LEFT:
12303                  e.preventDefault();
12304                  if(s.hasChildNodes() && s.isExpanded()){
12305                      s.collapse();
12306                  }else if(s.parentNode && (this.tree.rootVisible || s.parentNode != this.tree.getRootNode())){
12307                      this.select(s.parentNode, e);
12308                  }
12309              break;
12310         };
12311     }
12312 });
12313
12314 /**
12315  * @class Roo.tree.MultiSelectionModel
12316  * @extends Roo.util.Observable
12317  * Multi selection for a TreePanel.
12318  * @param {Object} cfg Configuration
12319  */
12320 Roo.tree.MultiSelectionModel = function(){
12321    this.selNodes = [];
12322    this.selMap = {};
12323    this.addEvents({
12324        /**
12325         * @event selectionchange
12326         * Fires when the selected nodes change
12327         * @param {MultiSelectionModel} this
12328         * @param {Array} nodes Array of the selected nodes
12329         */
12330        "selectionchange" : true
12331    });
12332    Roo.tree.MultiSelectionModel.superclass.constructor.call(this,cfg);
12333    
12334 };
12335
12336 Roo.extend(Roo.tree.MultiSelectionModel, Roo.util.Observable, {
12337     init : function(tree){
12338         this.tree = tree;
12339         tree.getTreeEl().on("keydown", this.onKeyDown, this);
12340         tree.on("click", this.onNodeClick, this);
12341     },
12342     
12343     onNodeClick : function(node, e){
12344         this.select(node, e, e.ctrlKey);
12345     },
12346     
12347     /**
12348      * Select a node.
12349      * @param {TreeNode} node The node to select
12350      * @param {EventObject} e (optional) An event associated with the selection
12351      * @param {Boolean} keepExisting True to retain existing selections
12352      * @return {TreeNode} The selected node
12353      */
12354     select : function(node, e, keepExisting){
12355         if(keepExisting !== true){
12356             this.clearSelections(true);
12357         }
12358         if(this.isSelected(node)){
12359             this.lastSelNode = node;
12360             return node;
12361         }
12362         this.selNodes.push(node);
12363         this.selMap[node.id] = node;
12364         this.lastSelNode = node;
12365         node.ui.onSelectedChange(true);
12366         this.fireEvent("selectionchange", this, this.selNodes);
12367         return node;
12368     },
12369     
12370     /**
12371      * Deselect a node.
12372      * @param {TreeNode} node The node to unselect
12373      */
12374     unselect : function(node){
12375         if(this.selMap[node.id]){
12376             node.ui.onSelectedChange(false);
12377             var sn = this.selNodes;
12378             var index = -1;
12379             if(sn.indexOf){
12380                 index = sn.indexOf(node);
12381             }else{
12382                 for(var i = 0, len = sn.length; i < len; i++){
12383                     if(sn[i] == node){
12384                         index = i;
12385                         break;
12386                     }
12387                 }
12388             }
12389             if(index != -1){
12390                 this.selNodes.splice(index, 1);
12391             }
12392             delete this.selMap[node.id];
12393             this.fireEvent("selectionchange", this, this.selNodes);
12394         }
12395     },
12396     
12397     /**
12398      * Clear all selections
12399      */
12400     clearSelections : function(suppressEvent){
12401         var sn = this.selNodes;
12402         if(sn.length > 0){
12403             for(var i = 0, len = sn.length; i < len; i++){
12404                 sn[i].ui.onSelectedChange(false);
12405             }
12406             this.selNodes = [];
12407             this.selMap = {};
12408             if(suppressEvent !== true){
12409                 this.fireEvent("selectionchange", this, this.selNodes);
12410             }
12411         }
12412     },
12413     
12414     /**
12415      * Returns true if the node is selected
12416      * @param {TreeNode} node The node to check
12417      * @return {Boolean}
12418      */
12419     isSelected : function(node){
12420         return this.selMap[node.id] ? true : false;  
12421     },
12422     
12423     /**
12424      * Returns an array of the selected nodes
12425      * @return {Array}
12426      */
12427     getSelectedNodes : function(){
12428         return this.selNodes;    
12429     },
12430
12431     onKeyDown : Roo.tree.DefaultSelectionModel.prototype.onKeyDown,
12432
12433     selectNext : Roo.tree.DefaultSelectionModel.prototype.selectNext,
12434
12435     selectPrevious : Roo.tree.DefaultSelectionModel.prototype.selectPrevious
12436 });/*
12437  * Based on:
12438  * Ext JS Library 1.1.1
12439  * Copyright(c) 2006-2007, Ext JS, LLC.
12440  *
12441  * Originally Released Under LGPL - original licence link has changed is not relivant.
12442  *
12443  * Fork - LGPL
12444  * <script type="text/javascript">
12445  */
12446  
12447 /**
12448  * @class Roo.tree.TreeNode
12449  * @extends Roo.data.Node
12450  * @cfg {String} text The text for this node
12451  * @cfg {Boolean} expanded true to start the node expanded
12452  * @cfg {Boolean} allowDrag false to make this node undraggable if DD is on (defaults to true)
12453  * @cfg {Boolean} allowDrop false if this node cannot be drop on
12454  * @cfg {Boolean} disabled true to start the node disabled
12455  * @cfg {String} icon The path to an icon for the node. The preferred way to do this
12456  *    is to use the cls or iconCls attributes and add the icon via a CSS background image.
12457  * @cfg {String} cls A css class to be added to the node
12458  * @cfg {String} iconCls A css class to be added to the nodes icon element for applying css background images
12459  * @cfg {String} href URL of the link used for the node (defaults to #)
12460  * @cfg {String} hrefTarget target frame for the link
12461  * @cfg {String} qtip An Ext QuickTip for the node
12462  * @cfg {String} qtipCfg An Ext QuickTip config for the node (used instead of qtip)
12463  * @cfg {Boolean} singleClickExpand True for single click expand on this node
12464  * @cfg {Function} uiProvider A UI <b>class</b> to use for this node (defaults to Roo.tree.TreeNodeUI)
12465  * @cfg {Boolean} checked True to render a checked checkbox for this node, false to render an unchecked checkbox
12466  * (defaults to undefined with no checkbox rendered)
12467  * @constructor
12468  * @param {Object/String} attributes The attributes/config for the node or just a string with the text for the node
12469  */
12470 Roo.tree.TreeNode = function(attributes){
12471     attributes = attributes || {};
12472     if(typeof attributes == "string"){
12473         attributes = {text: attributes};
12474     }
12475     this.childrenRendered = false;
12476     this.rendered = false;
12477     Roo.tree.TreeNode.superclass.constructor.call(this, attributes);
12478     this.expanded = attributes.expanded === true;
12479     this.isTarget = attributes.isTarget !== false;
12480     this.draggable = attributes.draggable !== false && attributes.allowDrag !== false;
12481     this.allowChildren = attributes.allowChildren !== false && attributes.allowDrop !== false;
12482
12483     /**
12484      * Read-only. The text for this node. To change it use setText().
12485      * @type String
12486      */
12487     this.text = attributes.text;
12488     /**
12489      * True if this node is disabled.
12490      * @type Boolean
12491      */
12492     this.disabled = attributes.disabled === true;
12493
12494     this.addEvents({
12495         /**
12496         * @event textchange
12497         * Fires when the text for this node is changed
12498         * @param {Node} this This node
12499         * @param {String} text The new text
12500         * @param {String} oldText The old text
12501         */
12502         "textchange" : true,
12503         /**
12504         * @event beforeexpand
12505         * Fires before this node is expanded, return false to cancel.
12506         * @param {Node} this This node
12507         * @param {Boolean} deep
12508         * @param {Boolean} anim
12509         */
12510         "beforeexpand" : true,
12511         /**
12512         * @event beforecollapse
12513         * Fires before this node is collapsed, return false to cancel.
12514         * @param {Node} this This node
12515         * @param {Boolean} deep
12516         * @param {Boolean} anim
12517         */
12518         "beforecollapse" : true,
12519         /**
12520         * @event expand
12521         * Fires when this node is expanded
12522         * @param {Node} this This node
12523         */
12524         "expand" : true,
12525         /**
12526         * @event disabledchange
12527         * Fires when the disabled status of this node changes
12528         * @param {Node} this This node
12529         * @param {Boolean} disabled
12530         */
12531         "disabledchange" : true,
12532         /**
12533         * @event collapse
12534         * Fires when this node is collapsed
12535         * @param {Node} this This node
12536         */
12537         "collapse" : true,
12538         /**
12539         * @event beforeclick
12540         * Fires before click processing. Return false to cancel the default action.
12541         * @param {Node} this This node
12542         * @param {Roo.EventObject} e The event object
12543         */
12544         "beforeclick":true,
12545         /**
12546         * @event checkchange
12547         * Fires when a node with a checkbox's checked property changes
12548         * @param {Node} this This node
12549         * @param {Boolean} checked
12550         */
12551         "checkchange":true,
12552         /**
12553         * @event click
12554         * Fires when this node is clicked
12555         * @param {Node} this This node
12556         * @param {Roo.EventObject} e The event object
12557         */
12558         "click":true,
12559         /**
12560         * @event dblclick
12561         * Fires when this node is double clicked
12562         * @param {Node} this This node
12563         * @param {Roo.EventObject} e The event object
12564         */
12565         "dblclick":true,
12566         /**
12567         * @event contextmenu
12568         * Fires when this node is right clicked
12569         * @param {Node} this This node
12570         * @param {Roo.EventObject} e The event object
12571         */
12572         "contextmenu":true,
12573         /**
12574         * @event beforechildrenrendered
12575         * Fires right before the child nodes for this node are rendered
12576         * @param {Node} this This node
12577         */
12578         "beforechildrenrendered":true
12579     });
12580
12581     var uiClass = this.attributes.uiProvider || Roo.tree.TreeNodeUI;
12582
12583     /**
12584      * Read-only. The UI for this node
12585      * @type TreeNodeUI
12586      */
12587     this.ui = new uiClass(this);
12588     
12589     // finally support items[]
12590     if (typeof(this.attributes.items) == 'undefined' || !this.attributes.items) {
12591         return;
12592     }
12593     
12594     
12595     Roo.each(this.attributes.items, function(c) {
12596         this.appendChild(Roo.factory(c,Roo.Tree));
12597     }, this);
12598     delete this.attributes.items;
12599     
12600     
12601     
12602 };
12603 Roo.extend(Roo.tree.TreeNode, Roo.data.Node, {
12604     preventHScroll: true,
12605     /**
12606      * Returns true if this node is expanded
12607      * @return {Boolean}
12608      */
12609     isExpanded : function(){
12610         return this.expanded;
12611     },
12612
12613     /**
12614      * Returns the UI object for this node
12615      * @return {TreeNodeUI}
12616      */
12617     getUI : function(){
12618         return this.ui;
12619     },
12620
12621     // private override
12622     setFirstChild : function(node){
12623         var of = this.firstChild;
12624         Roo.tree.TreeNode.superclass.setFirstChild.call(this, node);
12625         if(this.childrenRendered && of && node != of){
12626             of.renderIndent(true, true);
12627         }
12628         if(this.rendered){
12629             this.renderIndent(true, true);
12630         }
12631     },
12632
12633     // private override
12634     setLastChild : function(node){
12635         var ol = this.lastChild;
12636         Roo.tree.TreeNode.superclass.setLastChild.call(this, node);
12637         if(this.childrenRendered && ol && node != ol){
12638             ol.renderIndent(true, true);
12639         }
12640         if(this.rendered){
12641             this.renderIndent(true, true);
12642         }
12643     },
12644
12645     // these methods are overridden to provide lazy rendering support
12646     // private override
12647     appendChild : function()
12648     {
12649         var node = Roo.tree.TreeNode.superclass.appendChild.apply(this, arguments);
12650         if(node && this.childrenRendered){
12651             node.render();
12652         }
12653         this.ui.updateExpandIcon();
12654         return node;
12655     },
12656
12657     // private override
12658     removeChild : function(node){
12659         this.ownerTree.getSelectionModel().unselect(node);
12660         Roo.tree.TreeNode.superclass.removeChild.apply(this, arguments);
12661         // if it's been rendered remove dom node
12662         if(this.childrenRendered){
12663             node.ui.remove();
12664         }
12665         if(this.childNodes.length < 1){
12666             this.collapse(false, false);
12667         }else{
12668             this.ui.updateExpandIcon();
12669         }
12670         if(!this.firstChild) {
12671             this.childrenRendered = false;
12672         }
12673         return node;
12674     },
12675
12676     // private override
12677     insertBefore : function(node, refNode){
12678         var newNode = Roo.tree.TreeNode.superclass.insertBefore.apply(this, arguments);
12679         if(newNode && refNode && this.childrenRendered){
12680             node.render();
12681         }
12682         this.ui.updateExpandIcon();
12683         return newNode;
12684     },
12685
12686     /**
12687      * Sets the text for this node
12688      * @param {String} text
12689      */
12690     setText : function(text){
12691         var oldText = this.text;
12692         this.text = text;
12693         this.attributes.text = text;
12694         if(this.rendered){ // event without subscribing
12695             this.ui.onTextChange(this, text, oldText);
12696         }
12697         this.fireEvent("textchange", this, text, oldText);
12698     },
12699
12700     /**
12701      * Triggers selection of this node
12702      */
12703     select : function(){
12704         this.getOwnerTree().getSelectionModel().select(this);
12705     },
12706
12707     /**
12708      * Triggers deselection of this node
12709      */
12710     unselect : function(){
12711         this.getOwnerTree().getSelectionModel().unselect(this);
12712     },
12713
12714     /**
12715      * Returns true if this node is selected
12716      * @return {Boolean}
12717      */
12718     isSelected : function(){
12719         return this.getOwnerTree().getSelectionModel().isSelected(this);
12720     },
12721
12722     /**
12723      * Expand this node.
12724      * @param {Boolean} deep (optional) True to expand all children as well
12725      * @param {Boolean} anim (optional) false to cancel the default animation
12726      * @param {Function} callback (optional) A callback to be called when
12727      * expanding this node completes (does not wait for deep expand to complete).
12728      * Called with 1 parameter, this node.
12729      */
12730     expand : function(deep, anim, callback){
12731         if(!this.expanded){
12732             if(this.fireEvent("beforeexpand", this, deep, anim) === false){
12733                 return;
12734             }
12735             if(!this.childrenRendered){
12736                 this.renderChildren();
12737             }
12738             this.expanded = true;
12739             
12740             if(!this.isHiddenRoot() && (this.getOwnerTree() && this.getOwnerTree().animate && anim !== false) || anim){
12741                 this.ui.animExpand(function(){
12742                     this.fireEvent("expand", this);
12743                     if(typeof callback == "function"){
12744                         callback(this);
12745                     }
12746                     if(deep === true){
12747                         this.expandChildNodes(true);
12748                     }
12749                 }.createDelegate(this));
12750                 return;
12751             }else{
12752                 this.ui.expand();
12753                 this.fireEvent("expand", this);
12754                 if(typeof callback == "function"){
12755                     callback(this);
12756                 }
12757             }
12758         }else{
12759            if(typeof callback == "function"){
12760                callback(this);
12761            }
12762         }
12763         if(deep === true){
12764             this.expandChildNodes(true);
12765         }
12766     },
12767
12768     isHiddenRoot : function(){
12769         return this.isRoot && !this.getOwnerTree().rootVisible;
12770     },
12771
12772     /**
12773      * Collapse this node.
12774      * @param {Boolean} deep (optional) True to collapse all children as well
12775      * @param {Boolean} anim (optional) false to cancel the default animation
12776      */
12777     collapse : function(deep, anim){
12778         if(this.expanded && !this.isHiddenRoot()){
12779             if(this.fireEvent("beforecollapse", this, deep, anim) === false){
12780                 return;
12781             }
12782             this.expanded = false;
12783             if((this.getOwnerTree().animate && anim !== false) || anim){
12784                 this.ui.animCollapse(function(){
12785                     this.fireEvent("collapse", this);
12786                     if(deep === true){
12787                         this.collapseChildNodes(true);
12788                     }
12789                 }.createDelegate(this));
12790                 return;
12791             }else{
12792                 this.ui.collapse();
12793                 this.fireEvent("collapse", this);
12794             }
12795         }
12796         if(deep === true){
12797             var cs = this.childNodes;
12798             for(var i = 0, len = cs.length; i < len; i++) {
12799                 cs[i].collapse(true, false);
12800             }
12801         }
12802     },
12803
12804     // private
12805     delayedExpand : function(delay){
12806         if(!this.expandProcId){
12807             this.expandProcId = this.expand.defer(delay, this);
12808         }
12809     },
12810
12811     // private
12812     cancelExpand : function(){
12813         if(this.expandProcId){
12814             clearTimeout(this.expandProcId);
12815         }
12816         this.expandProcId = false;
12817     },
12818
12819     /**
12820      * Toggles expanded/collapsed state of the node
12821      */
12822     toggle : function(){
12823         if(this.expanded){
12824             this.collapse();
12825         }else{
12826             this.expand();
12827         }
12828     },
12829
12830     /**
12831      * Ensures all parent nodes are expanded
12832      */
12833     ensureVisible : function(callback){
12834         var tree = this.getOwnerTree();
12835         tree.expandPath(this.parentNode.getPath(), false, function(){
12836             tree.getTreeEl().scrollChildIntoView(this.ui.anchor);
12837             Roo.callback(callback);
12838         }.createDelegate(this));
12839     },
12840
12841     /**
12842      * Expand all child nodes
12843      * @param {Boolean} deep (optional) true if the child nodes should also expand their child nodes
12844      */
12845     expandChildNodes : function(deep){
12846         var cs = this.childNodes;
12847         for(var i = 0, len = cs.length; i < len; i++) {
12848                 cs[i].expand(deep);
12849         }
12850     },
12851
12852     /**
12853      * Collapse all child nodes
12854      * @param {Boolean} deep (optional) true if the child nodes should also collapse their child nodes
12855      */
12856     collapseChildNodes : function(deep){
12857         var cs = this.childNodes;
12858         for(var i = 0, len = cs.length; i < len; i++) {
12859                 cs[i].collapse(deep);
12860         }
12861     },
12862
12863     /**
12864      * Disables this node
12865      */
12866     disable : function(){
12867         this.disabled = true;
12868         this.unselect();
12869         if(this.rendered && this.ui.onDisableChange){ // event without subscribing
12870             this.ui.onDisableChange(this, true);
12871         }
12872         this.fireEvent("disabledchange", this, true);
12873     },
12874
12875     /**
12876      * Enables this node
12877      */
12878     enable : function(){
12879         this.disabled = false;
12880         if(this.rendered && this.ui.onDisableChange){ // event without subscribing
12881             this.ui.onDisableChange(this, false);
12882         }
12883         this.fireEvent("disabledchange", this, false);
12884     },
12885
12886     // private
12887     renderChildren : function(suppressEvent){
12888         if(suppressEvent !== false){
12889             this.fireEvent("beforechildrenrendered", this);
12890         }
12891         var cs = this.childNodes;
12892         for(var i = 0, len = cs.length; i < len; i++){
12893             cs[i].render(true);
12894         }
12895         this.childrenRendered = true;
12896     },
12897
12898     // private
12899     sort : function(fn, scope){
12900         Roo.tree.TreeNode.superclass.sort.apply(this, arguments);
12901         if(this.childrenRendered){
12902             var cs = this.childNodes;
12903             for(var i = 0, len = cs.length; i < len; i++){
12904                 cs[i].render(true);
12905             }
12906         }
12907     },
12908
12909     // private
12910     render : function(bulkRender){
12911         this.ui.render(bulkRender);
12912         if(!this.rendered){
12913             this.rendered = true;
12914             if(this.expanded){
12915                 this.expanded = false;
12916                 this.expand(false, false);
12917             }
12918         }
12919     },
12920
12921     // private
12922     renderIndent : function(deep, refresh){
12923         if(refresh){
12924             this.ui.childIndent = null;
12925         }
12926         this.ui.renderIndent();
12927         if(deep === true && this.childrenRendered){
12928             var cs = this.childNodes;
12929             for(var i = 0, len = cs.length; i < len; i++){
12930                 cs[i].renderIndent(true, refresh);
12931             }
12932         }
12933     }
12934 });/*
12935  * Based on:
12936  * Ext JS Library 1.1.1
12937  * Copyright(c) 2006-2007, Ext JS, LLC.
12938  *
12939  * Originally Released Under LGPL - original licence link has changed is not relivant.
12940  *
12941  * Fork - LGPL
12942  * <script type="text/javascript">
12943  */
12944  
12945 /**
12946  * @class Roo.tree.AsyncTreeNode
12947  * @extends Roo.tree.TreeNode
12948  * @cfg {TreeLoader} loader A TreeLoader to be used by this node (defaults to the loader defined on the tree)
12949  * @constructor
12950  * @param {Object/String} attributes The attributes/config for the node or just a string with the text for the node 
12951  */
12952  Roo.tree.AsyncTreeNode = function(config){
12953     this.loaded = false;
12954     this.loading = false;
12955     Roo.tree.AsyncTreeNode.superclass.constructor.apply(this, arguments);
12956     /**
12957     * @event beforeload
12958     * Fires before this node is loaded, return false to cancel
12959     * @param {Node} this This node
12960     */
12961     this.addEvents({'beforeload':true, 'load': true});
12962     /**
12963     * @event load
12964     * Fires when this node is loaded
12965     * @param {Node} this This node
12966     */
12967     /**
12968      * The loader used by this node (defaults to using the tree's defined loader)
12969      * @type TreeLoader
12970      * @property loader
12971      */
12972 };
12973 Roo.extend(Roo.tree.AsyncTreeNode, Roo.tree.TreeNode, {
12974     expand : function(deep, anim, callback){
12975         if(this.loading){ // if an async load is already running, waiting til it's done
12976             var timer;
12977             var f = function(){
12978                 if(!this.loading){ // done loading
12979                     clearInterval(timer);
12980                     this.expand(deep, anim, callback);
12981                 }
12982             }.createDelegate(this);
12983             timer = setInterval(f, 200);
12984             return;
12985         }
12986         if(!this.loaded){
12987             if(this.fireEvent("beforeload", this) === false){
12988                 return;
12989             }
12990             this.loading = true;
12991             this.ui.beforeLoad(this);
12992             var loader = this.loader || this.attributes.loader || this.getOwnerTree().getLoader();
12993             if(loader){
12994                 loader.load(this, this.loadComplete.createDelegate(this, [deep, anim, callback]));
12995                 return;
12996             }
12997         }
12998         Roo.tree.AsyncTreeNode.superclass.expand.call(this, deep, anim, callback);
12999     },
13000     
13001     /**
13002      * Returns true if this node is currently loading
13003      * @return {Boolean}
13004      */
13005     isLoading : function(){
13006         return this.loading;  
13007     },
13008     
13009     loadComplete : function(deep, anim, callback){
13010         this.loading = false;
13011         this.loaded = true;
13012         this.ui.afterLoad(this);
13013         this.fireEvent("load", this);
13014         this.expand(deep, anim, callback);
13015     },
13016     
13017     /**
13018      * Returns true if this node has been loaded
13019      * @return {Boolean}
13020      */
13021     isLoaded : function(){
13022         return this.loaded;
13023     },
13024     
13025     hasChildNodes : function(){
13026         if(!this.isLeaf() && !this.loaded){
13027             return true;
13028         }else{
13029             return Roo.tree.AsyncTreeNode.superclass.hasChildNodes.call(this);
13030         }
13031     },
13032
13033     /**
13034      * Trigger a reload for this node
13035      * @param {Function} callback
13036      */
13037     reload : function(callback){
13038         this.collapse(false, false);
13039         while(this.firstChild){
13040             this.removeChild(this.firstChild);
13041         }
13042         this.childrenRendered = false;
13043         this.loaded = false;
13044         if(this.isHiddenRoot()){
13045             this.expanded = false;
13046         }
13047         this.expand(false, false, callback);
13048     }
13049 });/*
13050  * Based on:
13051  * Ext JS Library 1.1.1
13052  * Copyright(c) 2006-2007, Ext JS, LLC.
13053  *
13054  * Originally Released Under LGPL - original licence link has changed is not relivant.
13055  *
13056  * Fork - LGPL
13057  * <script type="text/javascript">
13058  */
13059  
13060 /**
13061  * @class Roo.tree.TreeNodeUI
13062  * @constructor
13063  * @param {Object} node The node to render
13064  * The TreeNode UI implementation is separate from the
13065  * tree implementation. Unless you are customizing the tree UI,
13066  * you should never have to use this directly.
13067  */
13068 Roo.tree.TreeNodeUI = function(node){
13069     this.node = node;
13070     this.rendered = false;
13071     this.animating = false;
13072     this.emptyIcon = Roo.BLANK_IMAGE_URL;
13073 };
13074
13075 Roo.tree.TreeNodeUI.prototype = {
13076     removeChild : function(node){
13077         if(this.rendered){
13078             this.ctNode.removeChild(node.ui.getEl());
13079         }
13080     },
13081
13082     beforeLoad : function(){
13083          this.addClass("x-tree-node-loading");
13084     },
13085
13086     afterLoad : function(){
13087          this.removeClass("x-tree-node-loading");
13088     },
13089
13090     onTextChange : function(node, text, oldText){
13091         if(this.rendered){
13092             this.textNode.innerHTML = text;
13093         }
13094     },
13095
13096     onDisableChange : function(node, state){
13097         this.disabled = state;
13098         if(state){
13099             this.addClass("x-tree-node-disabled");
13100         }else{
13101             this.removeClass("x-tree-node-disabled");
13102         }
13103     },
13104
13105     onSelectedChange : function(state){
13106         if(state){
13107             this.focus();
13108             this.addClass("x-tree-selected");
13109         }else{
13110             //this.blur();
13111             this.removeClass("x-tree-selected");
13112         }
13113     },
13114
13115     onMove : function(tree, node, oldParent, newParent, index, refNode){
13116         this.childIndent = null;
13117         if(this.rendered){
13118             var targetNode = newParent.ui.getContainer();
13119             if(!targetNode){//target not rendered
13120                 this.holder = document.createElement("div");
13121                 this.holder.appendChild(this.wrap);
13122                 return;
13123             }
13124             var insertBefore = refNode ? refNode.ui.getEl() : null;
13125             if(insertBefore){
13126                 targetNode.insertBefore(this.wrap, insertBefore);
13127             }else{
13128                 targetNode.appendChild(this.wrap);
13129             }
13130             this.node.renderIndent(true);
13131         }
13132     },
13133
13134     addClass : function(cls){
13135         if(this.elNode){
13136             Roo.fly(this.elNode).addClass(cls);
13137         }
13138     },
13139
13140     removeClass : function(cls){
13141         if(this.elNode){
13142             Roo.fly(this.elNode).removeClass(cls);
13143         }
13144     },
13145
13146     remove : function(){
13147         if(this.rendered){
13148             this.holder = document.createElement("div");
13149             this.holder.appendChild(this.wrap);
13150         }
13151     },
13152
13153     fireEvent : function(){
13154         return this.node.fireEvent.apply(this.node, arguments);
13155     },
13156
13157     initEvents : function(){
13158         this.node.on("move", this.onMove, this);
13159         var E = Roo.EventManager;
13160         var a = this.anchor;
13161
13162         var el = Roo.fly(a, '_treeui');
13163
13164         if(Roo.isOpera){ // opera render bug ignores the CSS
13165             el.setStyle("text-decoration", "none");
13166         }
13167
13168         el.on("click", this.onClick, this);
13169         el.on("dblclick", this.onDblClick, this);
13170
13171         if(this.checkbox){
13172             Roo.EventManager.on(this.checkbox,
13173                     Roo.isIE ? 'click' : 'change', this.onCheckChange, this);
13174         }
13175
13176         el.on("contextmenu", this.onContextMenu, this);
13177
13178         var icon = Roo.fly(this.iconNode);
13179         icon.on("click", this.onClick, this);
13180         icon.on("dblclick", this.onDblClick, this);
13181         icon.on("contextmenu", this.onContextMenu, this);
13182         E.on(this.ecNode, "click", this.ecClick, this, true);
13183
13184         if(this.node.disabled){
13185             this.addClass("x-tree-node-disabled");
13186         }
13187         if(this.node.hidden){
13188             this.addClass("x-tree-node-disabled");
13189         }
13190         var ot = this.node.getOwnerTree();
13191         var dd = ot ? (ot.enableDD || ot.enableDrag || ot.enableDrop) : false;
13192         if(dd && (!this.node.isRoot || ot.rootVisible)){
13193             Roo.dd.Registry.register(this.elNode, {
13194                 node: this.node,
13195                 handles: this.getDDHandles(),
13196                 isHandle: false
13197             });
13198         }
13199     },
13200
13201     getDDHandles : function(){
13202         return [this.iconNode, this.textNode];
13203     },
13204
13205     hide : function(){
13206         if(this.rendered){
13207             this.wrap.style.display = "none";
13208         }
13209     },
13210
13211     show : function(){
13212         if(this.rendered){
13213             this.wrap.style.display = "";
13214         }
13215     },
13216
13217     onContextMenu : function(e){
13218         if (this.node.hasListener("contextmenu") || this.node.getOwnerTree().hasListener("contextmenu")) {
13219             e.preventDefault();
13220             this.focus();
13221             this.fireEvent("contextmenu", this.node, e);
13222         }
13223     },
13224
13225     onClick : function(e){
13226         if(this.dropping){
13227             e.stopEvent();
13228             return;
13229         }
13230         if(this.fireEvent("beforeclick", this.node, e) !== false){
13231             if(!this.disabled && this.node.attributes.href){
13232                 this.fireEvent("click", this.node, e);
13233                 return;
13234             }
13235             e.preventDefault();
13236             if(this.disabled){
13237                 return;
13238             }
13239
13240             if(this.node.attributes.singleClickExpand && !this.animating && this.node.hasChildNodes()){
13241                 this.node.toggle();
13242             }
13243
13244             this.fireEvent("click", this.node, e);
13245         }else{
13246             e.stopEvent();
13247         }
13248     },
13249
13250     onDblClick : function(e){
13251         e.preventDefault();
13252         if(this.disabled){
13253             return;
13254         }
13255         if(this.checkbox){
13256             this.toggleCheck();
13257         }
13258         if(!this.animating && this.node.hasChildNodes()){
13259             this.node.toggle();
13260         }
13261         this.fireEvent("dblclick", this.node, e);
13262     },
13263
13264     onCheckChange : function(){
13265         var checked = this.checkbox.checked;
13266         this.node.attributes.checked = checked;
13267         this.fireEvent('checkchange', this.node, checked);
13268     },
13269
13270     ecClick : function(e){
13271         if(!this.animating && this.node.hasChildNodes()){
13272             this.node.toggle();
13273         }
13274     },
13275
13276     startDrop : function(){
13277         this.dropping = true;
13278     },
13279
13280     // delayed drop so the click event doesn't get fired on a drop
13281     endDrop : function(){
13282        setTimeout(function(){
13283            this.dropping = false;
13284        }.createDelegate(this), 50);
13285     },
13286
13287     expand : function(){
13288         this.updateExpandIcon();
13289         this.ctNode.style.display = "";
13290     },
13291
13292     focus : function(){
13293         if(!this.node.preventHScroll){
13294             try{this.anchor.focus();
13295             }catch(e){}
13296         }else if(!Roo.isIE){
13297             try{
13298                 var noscroll = this.node.getOwnerTree().getTreeEl().dom;
13299                 var l = noscroll.scrollLeft;
13300                 this.anchor.focus();
13301                 noscroll.scrollLeft = l;
13302             }catch(e){}
13303         }
13304     },
13305
13306     toggleCheck : function(value){
13307         var cb = this.checkbox;
13308         if(cb){
13309             cb.checked = (value === undefined ? !cb.checked : value);
13310         }
13311     },
13312
13313     blur : function(){
13314         try{
13315             this.anchor.blur();
13316         }catch(e){}
13317     },
13318
13319     animExpand : function(callback){
13320         var ct = Roo.get(this.ctNode);
13321         ct.stopFx();
13322         if(!this.node.hasChildNodes()){
13323             this.updateExpandIcon();
13324             this.ctNode.style.display = "";
13325             Roo.callback(callback);
13326             return;
13327         }
13328         this.animating = true;
13329         this.updateExpandIcon();
13330
13331         ct.slideIn('t', {
13332            callback : function(){
13333                this.animating = false;
13334                Roo.callback(callback);
13335             },
13336             scope: this,
13337             duration: this.node.ownerTree.duration || .25
13338         });
13339     },
13340
13341     highlight : function(){
13342         var tree = this.node.getOwnerTree();
13343         Roo.fly(this.wrap).highlight(
13344             tree.hlColor || "C3DAF9",
13345             {endColor: tree.hlBaseColor}
13346         );
13347     },
13348
13349     collapse : function(){
13350         this.updateExpandIcon();
13351         this.ctNode.style.display = "none";
13352     },
13353
13354     animCollapse : function(callback){
13355         var ct = Roo.get(this.ctNode);
13356         ct.enableDisplayMode('block');
13357         ct.stopFx();
13358
13359         this.animating = true;
13360         this.updateExpandIcon();
13361
13362         ct.slideOut('t', {
13363             callback : function(){
13364                this.animating = false;
13365                Roo.callback(callback);
13366             },
13367             scope: this,
13368             duration: this.node.ownerTree.duration || .25
13369         });
13370     },
13371
13372     getContainer : function(){
13373         return this.ctNode;
13374     },
13375
13376     getEl : function(){
13377         return this.wrap;
13378     },
13379
13380     appendDDGhost : function(ghostNode){
13381         ghostNode.appendChild(this.elNode.cloneNode(true));
13382     },
13383
13384     getDDRepairXY : function(){
13385         return Roo.lib.Dom.getXY(this.iconNode);
13386     },
13387
13388     onRender : function(){
13389         this.render();
13390     },
13391
13392     render : function(bulkRender){
13393         var n = this.node, a = n.attributes;
13394         var targetNode = n.parentNode ?
13395               n.parentNode.ui.getContainer() : n.ownerTree.innerCt.dom;
13396
13397         if(!this.rendered){
13398             this.rendered = true;
13399
13400             this.renderElements(n, a, targetNode, bulkRender);
13401
13402             if(a.qtip){
13403                if(this.textNode.setAttributeNS){
13404                    this.textNode.setAttributeNS("ext", "qtip", a.qtip);
13405                    if(a.qtipTitle){
13406                        this.textNode.setAttributeNS("ext", "qtitle", a.qtipTitle);
13407                    }
13408                }else{
13409                    this.textNode.setAttribute("ext:qtip", a.qtip);
13410                    if(a.qtipTitle){
13411                        this.textNode.setAttribute("ext:qtitle", a.qtipTitle);
13412                    }
13413                }
13414             }else if(a.qtipCfg){
13415                 a.qtipCfg.target = Roo.id(this.textNode);
13416                 Roo.QuickTips.register(a.qtipCfg);
13417             }
13418             this.initEvents();
13419             if(!this.node.expanded){
13420                 this.updateExpandIcon();
13421             }
13422         }else{
13423             if(bulkRender === true) {
13424                 targetNode.appendChild(this.wrap);
13425             }
13426         }
13427     },
13428
13429     renderElements : function(n, a, targetNode, bulkRender)
13430     {
13431         // add some indent caching, this helps performance when rendering a large tree
13432         this.indentMarkup = n.parentNode ? n.parentNode.ui.getChildIndent() : '';
13433         var t = n.getOwnerTree();
13434         var txt = t && t.renderer ? t.renderer(n.attributes) : Roo.util.Format.htmlEncode(n.text);
13435         if (typeof(n.attributes.html) != 'undefined') {
13436             txt = n.attributes.html;
13437         }
13438         var tip = t && t.rendererTip ? t.rendererTip(n.attributes) : txt;
13439         var cb = typeof a.checked == 'boolean';
13440         var href = a.href ? a.href : Roo.isGecko ? "" : "#";
13441         var buf = ['<li class="x-tree-node"><div class="x-tree-node-el ', a.cls,'">',
13442             '<span class="x-tree-node-indent">',this.indentMarkup,"</span>",
13443             '<img src="', this.emptyIcon, '" class="x-tree-ec-icon" />',
13444             '<img src="', a.icon || this.emptyIcon, '" class="x-tree-node-icon',(a.icon ? " x-tree-node-inline-icon" : ""),(a.iconCls ? " "+a.iconCls : ""),'" unselectable="on" />',
13445             cb ? ('<input class="x-tree-node-cb" type="checkbox" ' + (a.checked ? 'checked="checked" />' : ' />')) : '',
13446             '<a hidefocus="on" href="',href,'" tabIndex="1" ',
13447              a.hrefTarget ? ' target="'+a.hrefTarget+'"' : "", 
13448                 '><span unselectable="on" qtip="' , tip ,'">',txt,"</span></a></div>",
13449             '<ul class="x-tree-node-ct" style="display:none;"></ul>',
13450             "</li>"];
13451
13452         if(bulkRender !== true && n.nextSibling && n.nextSibling.ui.getEl()){
13453             this.wrap = Roo.DomHelper.insertHtml("beforeBegin",
13454                                 n.nextSibling.ui.getEl(), buf.join(""));
13455         }else{
13456             this.wrap = Roo.DomHelper.insertHtml("beforeEnd", targetNode, buf.join(""));
13457         }
13458
13459         this.elNode = this.wrap.childNodes[0];
13460         this.ctNode = this.wrap.childNodes[1];
13461         var cs = this.elNode.childNodes;
13462         this.indentNode = cs[0];
13463         this.ecNode = cs[1];
13464         this.iconNode = cs[2];
13465         var index = 3;
13466         if(cb){
13467             this.checkbox = cs[3];
13468             index++;
13469         }
13470         this.anchor = cs[index];
13471         this.textNode = cs[index].firstChild;
13472     },
13473
13474     getAnchor : function(){
13475         return this.anchor;
13476     },
13477
13478     getTextEl : function(){
13479         return this.textNode;
13480     },
13481
13482     getIconEl : function(){
13483         return this.iconNode;
13484     },
13485
13486     isChecked : function(){
13487         return this.checkbox ? this.checkbox.checked : false;
13488     },
13489
13490     updateExpandIcon : function(){
13491         if(this.rendered){
13492             var n = this.node, c1, c2;
13493             var cls = n.isLast() ? "x-tree-elbow-end" : "x-tree-elbow";
13494             var hasChild = n.hasChildNodes();
13495             if(hasChild){
13496                 if(n.expanded){
13497                     cls += "-minus";
13498                     c1 = "x-tree-node-collapsed";
13499                     c2 = "x-tree-node-expanded";
13500                 }else{
13501                     cls += "-plus";
13502                     c1 = "x-tree-node-expanded";
13503                     c2 = "x-tree-node-collapsed";
13504                 }
13505                 if(this.wasLeaf){
13506                     this.removeClass("x-tree-node-leaf");
13507                     this.wasLeaf = false;
13508                 }
13509                 if(this.c1 != c1 || this.c2 != c2){
13510                     Roo.fly(this.elNode).replaceClass(c1, c2);
13511                     this.c1 = c1; this.c2 = c2;
13512                 }
13513             }else{
13514                 // this changes non-leafs into leafs if they have no children.
13515                 // it's not very rational behaviour..
13516                 
13517                 if(!this.wasLeaf && this.node.leaf){
13518                     Roo.fly(this.elNode).replaceClass("x-tree-node-expanded", "x-tree-node-leaf");
13519                     delete this.c1;
13520                     delete this.c2;
13521                     this.wasLeaf = true;
13522                 }
13523             }
13524             var ecc = "x-tree-ec-icon "+cls;
13525             if(this.ecc != ecc){
13526                 this.ecNode.className = ecc;
13527                 this.ecc = ecc;
13528             }
13529         }
13530     },
13531
13532     getChildIndent : function(){
13533         if(!this.childIndent){
13534             var buf = [];
13535             var p = this.node;
13536             while(p){
13537                 if(!p.isRoot || (p.isRoot && p.ownerTree.rootVisible)){
13538                     if(!p.isLast()) {
13539                         buf.unshift('<img src="'+this.emptyIcon+'" class="x-tree-elbow-line" />');
13540                     } else {
13541                         buf.unshift('<img src="'+this.emptyIcon+'" class="x-tree-icon" />');
13542                     }
13543                 }
13544                 p = p.parentNode;
13545             }
13546             this.childIndent = buf.join("");
13547         }
13548         return this.childIndent;
13549     },
13550
13551     renderIndent : function(){
13552         if(this.rendered){
13553             var indent = "";
13554             var p = this.node.parentNode;
13555             if(p){
13556                 indent = p.ui.getChildIndent();
13557             }
13558             if(this.indentMarkup != indent){ // don't rerender if not required
13559                 this.indentNode.innerHTML = indent;
13560                 this.indentMarkup = indent;
13561             }
13562             this.updateExpandIcon();
13563         }
13564     }
13565 };
13566
13567 Roo.tree.RootTreeNodeUI = function(){
13568     Roo.tree.RootTreeNodeUI.superclass.constructor.apply(this, arguments);
13569 };
13570 Roo.extend(Roo.tree.RootTreeNodeUI, Roo.tree.TreeNodeUI, {
13571     render : function(){
13572         if(!this.rendered){
13573             var targetNode = this.node.ownerTree.innerCt.dom;
13574             this.node.expanded = true;
13575             targetNode.innerHTML = '<div class="x-tree-root-node"></div>';
13576             this.wrap = this.ctNode = targetNode.firstChild;
13577         }
13578     },
13579     collapse : function(){
13580     },
13581     expand : function(){
13582     }
13583 });/*
13584  * Based on:
13585  * Ext JS Library 1.1.1
13586  * Copyright(c) 2006-2007, Ext JS, LLC.
13587  *
13588  * Originally Released Under LGPL - original licence link has changed is not relivant.
13589  *
13590  * Fork - LGPL
13591  * <script type="text/javascript">
13592  */
13593 /**
13594  * @class Roo.tree.TreeLoader
13595  * @extends Roo.util.Observable
13596  * A TreeLoader provides for lazy loading of an {@link Roo.tree.TreeNode}'s child
13597  * nodes from a specified URL. The response must be a javascript Array definition
13598  * who's elements are node definition objects. eg:
13599  * <pre><code>
13600 {  success : true,
13601    data :      [
13602    
13603     { 'id': 1, 'text': 'A folder Node', 'leaf': false },
13604     { 'id': 2, 'text': 'A leaf Node', 'leaf': true }
13605     ]
13606 }
13607
13608
13609 </code></pre>
13610  * <br><br>
13611  * The old style respose with just an array is still supported, but not recommended.
13612  * <br><br>
13613  *
13614  * A server request is sent, and child nodes are loaded only when a node is expanded.
13615  * The loading node's id is passed to the server under the parameter name "node" to
13616  * enable the server to produce the correct child nodes.
13617  * <br><br>
13618  * To pass extra parameters, an event handler may be attached to the "beforeload"
13619  * event, and the parameters specified in the TreeLoader's baseParams property:
13620  * <pre><code>
13621     myTreeLoader.on("beforeload", function(treeLoader, node) {
13622         this.baseParams.category = node.attributes.category;
13623     }, this);
13624     
13625 </code></pre>
13626  *
13627  * This would pass an HTTP parameter called "category" to the server containing
13628  * the value of the Node's "category" attribute.
13629  * @constructor
13630  * Creates a new Treeloader.
13631  * @param {Object} config A config object containing config properties.
13632  */
13633 Roo.tree.TreeLoader = function(config){
13634     this.baseParams = {};
13635     this.requestMethod = "POST";
13636     Roo.apply(this, config);
13637
13638     this.addEvents({
13639     
13640         /**
13641          * @event beforeload
13642          * Fires before a network request is made to retrieve the Json text which specifies a node's children.
13643          * @param {Object} This TreeLoader object.
13644          * @param {Object} node The {@link Roo.tree.TreeNode} object being loaded.
13645          * @param {Object} callback The callback function specified in the {@link #load} call.
13646          */
13647         beforeload : true,
13648         /**
13649          * @event load
13650          * Fires when the node has been successfuly loaded.
13651          * @param {Object} This TreeLoader object.
13652          * @param {Object} node The {@link Roo.tree.TreeNode} object being loaded.
13653          * @param {Object} response The response object containing the data from the server.
13654          */
13655         load : true,
13656         /**
13657          * @event loadexception
13658          * Fires if the network request failed.
13659          * @param {Object} This TreeLoader object.
13660          * @param {Object} node The {@link Roo.tree.TreeNode} object being loaded.
13661          * @param {Object} response The response object containing the data from the server.
13662          */
13663         loadexception : true,
13664         /**
13665          * @event create
13666          * Fires before a node is created, enabling you to return custom Node types 
13667          * @param {Object} This TreeLoader object.
13668          * @param {Object} attr - the data returned from the AJAX call (modify it to suit)
13669          */
13670         create : true
13671     });
13672
13673     Roo.tree.TreeLoader.superclass.constructor.call(this);
13674 };
13675
13676 Roo.extend(Roo.tree.TreeLoader, Roo.util.Observable, {
13677     /**
13678     * @cfg {String} dataUrl The URL from which to request a Json string which
13679     * specifies an array of node definition object representing the child nodes
13680     * to be loaded.
13681     */
13682     /**
13683     * @cfg {String} requestMethod either GET or POST
13684     * defaults to POST (due to BC)
13685     * to be loaded.
13686     */
13687     /**
13688     * @cfg {Object} baseParams (optional) An object containing properties which
13689     * specify HTTP parameters to be passed to each request for child nodes.
13690     */
13691     /**
13692     * @cfg {Object} baseAttrs (optional) An object containing attributes to be added to all nodes
13693     * created by this loader. If the attributes sent by the server have an attribute in this object,
13694     * they take priority.
13695     */
13696     /**
13697     * @cfg {Object} uiProviders (optional) An object containing properties which
13698     * 
13699     * DEPRECATED - use 'create' event handler to modify attributes - which affect creation.
13700     * specify custom {@link Roo.tree.TreeNodeUI} implementations. If the optional
13701     * <i>uiProvider</i> attribute of a returned child node is a string rather
13702     * than a reference to a TreeNodeUI implementation, this that string value
13703     * is used as a property name in the uiProviders object. You can define the provider named
13704     * 'default' , and this will be used for all nodes (if no uiProvider is delivered by the node data)
13705     */
13706     uiProviders : {},
13707
13708     /**
13709     * @cfg {Boolean} clearOnLoad (optional) Default to true. Remove previously existing
13710     * child nodes before loading.
13711     */
13712     clearOnLoad : true,
13713
13714     /**
13715     * @cfg {String} root (optional) Default to false. Use this to read data from an object 
13716     * property on loading, rather than expecting an array. (eg. more compatible to a standard
13717     * Grid query { data : [ .....] }
13718     */
13719     
13720     root : false,
13721      /**
13722     * @cfg {String} queryParam (optional) 
13723     * Name of the query as it will be passed on the querystring (defaults to 'node')
13724     * eg. the request will be ?node=[id]
13725     */
13726     
13727     
13728     queryParam: false,
13729     
13730     /**
13731      * Load an {@link Roo.tree.TreeNode} from the URL specified in the constructor.
13732      * This is called automatically when a node is expanded, but may be used to reload
13733      * a node (or append new children if the {@link #clearOnLoad} option is false.)
13734      * @param {Roo.tree.TreeNode} node
13735      * @param {Function} callback
13736      */
13737     load : function(node, callback){
13738         if(this.clearOnLoad){
13739             while(node.firstChild){
13740                 node.removeChild(node.firstChild);
13741             }
13742         }
13743         if(node.attributes.children){ // preloaded json children
13744             var cs = node.attributes.children;
13745             for(var i = 0, len = cs.length; i < len; i++){
13746                 node.appendChild(this.createNode(cs[i]));
13747             }
13748             if(typeof callback == "function"){
13749                 callback();
13750             }
13751         }else if(this.dataUrl){
13752             this.requestData(node, callback);
13753         }
13754     },
13755
13756     getParams: function(node){
13757         var buf = [], bp = this.baseParams;
13758         for(var key in bp){
13759             if(typeof bp[key] != "function"){
13760                 buf.push(encodeURIComponent(key), "=", encodeURIComponent(bp[key]), "&");
13761             }
13762         }
13763         var n = this.queryParam === false ? 'node' : this.queryParam;
13764         buf.push(n + "=", encodeURIComponent(node.id));
13765         return buf.join("");
13766     },
13767
13768     requestData : function(node, callback){
13769         if(this.fireEvent("beforeload", this, node, callback) !== false){
13770             this.transId = Roo.Ajax.request({
13771                 method:this.requestMethod,
13772                 url: this.dataUrl||this.url,
13773                 success: this.handleResponse,
13774                 failure: this.handleFailure,
13775                 scope: this,
13776                 argument: {callback: callback, node: node},
13777                 params: this.getParams(node)
13778             });
13779         }else{
13780             // if the load is cancelled, make sure we notify
13781             // the node that we are done
13782             if(typeof callback == "function"){
13783                 callback();
13784             }
13785         }
13786     },
13787
13788     isLoading : function(){
13789         return this.transId ? true : false;
13790     },
13791
13792     abort : function(){
13793         if(this.isLoading()){
13794             Roo.Ajax.abort(this.transId);
13795         }
13796     },
13797
13798     // private
13799     createNode : function(attr)
13800     {
13801         // apply baseAttrs, nice idea Corey!
13802         if(this.baseAttrs){
13803             Roo.applyIf(attr, this.baseAttrs);
13804         }
13805         if(this.applyLoader !== false){
13806             attr.loader = this;
13807         }
13808         // uiProvider = depreciated..
13809         
13810         if(typeof(attr.uiProvider) == 'string'){
13811            attr.uiProvider = this.uiProviders[attr.uiProvider] || 
13812                 /**  eval:var:attr */ eval(attr.uiProvider);
13813         }
13814         if(typeof(this.uiProviders['default']) != 'undefined') {
13815             attr.uiProvider = this.uiProviders['default'];
13816         }
13817         
13818         this.fireEvent('create', this, attr);
13819         
13820         attr.leaf  = typeof(attr.leaf) == 'string' ? attr.leaf * 1 : attr.leaf;
13821         return(attr.leaf ?
13822                         new Roo.tree.TreeNode(attr) :
13823                         new Roo.tree.AsyncTreeNode(attr));
13824     },
13825
13826     processResponse : function(response, node, callback)
13827     {
13828         var json = response.responseText;
13829         try {
13830             
13831             var o = Roo.decode(json);
13832             
13833             if (this.root === false && typeof(o.success) != undefined) {
13834                 this.root = 'data'; // the default behaviour for list like data..
13835                 }
13836                 
13837             if (this.root !== false &&  !o.success) {
13838                 // it's a failure condition.
13839                 var a = response.argument;
13840                 this.fireEvent("loadexception", this, a.node, response);
13841                 Roo.log("Load failed - should have a handler really");
13842                 return;
13843             }
13844             
13845             
13846             
13847             if (this.root !== false) {
13848                  o = o[this.root];
13849             }
13850             
13851             for(var i = 0, len = o.length; i < len; i++){
13852                 var n = this.createNode(o[i]);
13853                 if(n){
13854                     node.appendChild(n);
13855                 }
13856             }
13857             if(typeof callback == "function"){
13858                 callback(this, node);
13859             }
13860         }catch(e){
13861             this.handleFailure(response);
13862         }
13863     },
13864
13865     handleResponse : function(response){
13866         this.transId = false;
13867         var a = response.argument;
13868         this.processResponse(response, a.node, a.callback);
13869         this.fireEvent("load", this, a.node, response);
13870     },
13871
13872     handleFailure : function(response)
13873     {
13874         // should handle failure better..
13875         this.transId = false;
13876         var a = response.argument;
13877         this.fireEvent("loadexception", this, a.node, response);
13878         if(typeof a.callback == "function"){
13879             a.callback(this, a.node);
13880         }
13881     }
13882 });/*
13883  * Based on:
13884  * Ext JS Library 1.1.1
13885  * Copyright(c) 2006-2007, Ext JS, LLC.
13886  *
13887  * Originally Released Under LGPL - original licence link has changed is not relivant.
13888  *
13889  * Fork - LGPL
13890  * <script type="text/javascript">
13891  */
13892
13893 /**
13894 * @class Roo.tree.TreeFilter
13895 * Note this class is experimental and doesn't update the indent (lines) or expand collapse icons of the nodes
13896 * @param {TreePanel} tree
13897 * @param {Object} config (optional)
13898  */
13899 Roo.tree.TreeFilter = function(tree, config){
13900     this.tree = tree;
13901     this.filtered = {};
13902     Roo.apply(this, config);
13903 };
13904
13905 Roo.tree.TreeFilter.prototype = {
13906     clearBlank:false,
13907     reverse:false,
13908     autoClear:false,
13909     remove:false,
13910
13911      /**
13912      * Filter the data by a specific attribute.
13913      * @param {String/RegExp} value Either string that the attribute value
13914      * should start with or a RegExp to test against the attribute
13915      * @param {String} attr (optional) The attribute passed in your node's attributes collection. Defaults to "text".
13916      * @param {TreeNode} startNode (optional) The node to start the filter at.
13917      */
13918     filter : function(value, attr, startNode){
13919         attr = attr || "text";
13920         var f;
13921         if(typeof value == "string"){
13922             var vlen = value.length;
13923             // auto clear empty filter
13924             if(vlen == 0 && this.clearBlank){
13925                 this.clear();
13926                 return;
13927             }
13928             value = value.toLowerCase();
13929             f = function(n){
13930                 return n.attributes[attr].substr(0, vlen).toLowerCase() == value;
13931             };
13932         }else if(value.exec){ // regex?
13933             f = function(n){
13934                 return value.test(n.attributes[attr]);
13935             };
13936         }else{
13937             throw 'Illegal filter type, must be string or regex';
13938         }
13939         this.filterBy(f, null, startNode);
13940         },
13941
13942     /**
13943      * Filter by a function. The passed function will be called with each
13944      * node in the tree (or from the startNode). If the function returns true, the node is kept
13945      * otherwise it is filtered. If a node is filtered, its children are also filtered.
13946      * @param {Function} fn The filter function
13947      * @param {Object} scope (optional) The scope of the function (defaults to the current node)
13948      */
13949     filterBy : function(fn, scope, startNode){
13950         startNode = startNode || this.tree.root;
13951         if(this.autoClear){
13952             this.clear();
13953         }
13954         var af = this.filtered, rv = this.reverse;
13955         var f = function(n){
13956             if(n == startNode){
13957                 return true;
13958             }
13959             if(af[n.id]){
13960                 return false;
13961             }
13962             var m = fn.call(scope || n, n);
13963             if(!m || rv){
13964                 af[n.id] = n;
13965                 n.ui.hide();
13966                 return false;
13967             }
13968             return true;
13969         };
13970         startNode.cascade(f);
13971         if(this.remove){
13972            for(var id in af){
13973                if(typeof id != "function"){
13974                    var n = af[id];
13975                    if(n && n.parentNode){
13976                        n.parentNode.removeChild(n);
13977                    }
13978                }
13979            }
13980         }
13981     },
13982
13983     /**
13984      * Clears the current filter. Note: with the "remove" option
13985      * set a filter cannot be cleared.
13986      */
13987     clear : function(){
13988         var t = this.tree;
13989         var af = this.filtered;
13990         for(var id in af){
13991             if(typeof id != "function"){
13992                 var n = af[id];
13993                 if(n){
13994                     n.ui.show();
13995                 }
13996             }
13997         }
13998         this.filtered = {};
13999     }
14000 };
14001 /*
14002  * Based on:
14003  * Ext JS Library 1.1.1
14004  * Copyright(c) 2006-2007, Ext JS, LLC.
14005  *
14006  * Originally Released Under LGPL - original licence link has changed is not relivant.
14007  *
14008  * Fork - LGPL
14009  * <script type="text/javascript">
14010  */
14011  
14012
14013 /**
14014  * @class Roo.tree.TreeSorter
14015  * Provides sorting of nodes in a TreePanel
14016  * 
14017  * @cfg {Boolean} folderSort True to sort leaf nodes under non leaf nodes
14018  * @cfg {String} property The named attribute on the node to sort by (defaults to text)
14019  * @cfg {String} dir The direction to sort (asc or desc) (defaults to asc)
14020  * @cfg {String} leafAttr The attribute used to determine leaf nodes in folder sort (defaults to "leaf")
14021  * @cfg {Boolean} caseSensitive true for case sensitive sort (defaults to false)
14022  * @cfg {Function} sortType A custom "casting" function used to convert node values before sorting
14023  * @constructor
14024  * @param {TreePanel} tree
14025  * @param {Object} config
14026  */
14027 Roo.tree.TreeSorter = function(tree, config){
14028     Roo.apply(this, config);
14029     tree.on("beforechildrenrendered", this.doSort, this);
14030     tree.on("append", this.updateSort, this);
14031     tree.on("insert", this.updateSort, this);
14032     
14033     var dsc = this.dir && this.dir.toLowerCase() == "desc";
14034     var p = this.property || "text";
14035     var sortType = this.sortType;
14036     var fs = this.folderSort;
14037     var cs = this.caseSensitive === true;
14038     var leafAttr = this.leafAttr || 'leaf';
14039
14040     this.sortFn = function(n1, n2){
14041         if(fs){
14042             if(n1.attributes[leafAttr] && !n2.attributes[leafAttr]){
14043                 return 1;
14044             }
14045             if(!n1.attributes[leafAttr] && n2.attributes[leafAttr]){
14046                 return -1;
14047             }
14048         }
14049         var v1 = sortType ? sortType(n1) : (cs ? n1.attributes[p] : n1.attributes[p].toUpperCase());
14050         var v2 = sortType ? sortType(n2) : (cs ? n2.attributes[p] : n2.attributes[p].toUpperCase());
14051         if(v1 < v2){
14052                         return dsc ? +1 : -1;
14053                 }else if(v1 > v2){
14054                         return dsc ? -1 : +1;
14055         }else{
14056                 return 0;
14057         }
14058     };
14059 };
14060
14061 Roo.tree.TreeSorter.prototype = {
14062     doSort : function(node){
14063         node.sort(this.sortFn);
14064     },
14065     
14066     compareNodes : function(n1, n2){
14067         return (n1.text.toUpperCase() > n2.text.toUpperCase() ? 1 : -1);
14068     },
14069     
14070     updateSort : function(tree, node){
14071         if(node.childrenRendered){
14072             this.doSort.defer(1, this, [node]);
14073         }
14074     }
14075 };/*
14076  * Based on:
14077  * Ext JS Library 1.1.1
14078  * Copyright(c) 2006-2007, Ext JS, LLC.
14079  *
14080  * Originally Released Under LGPL - original licence link has changed is not relivant.
14081  *
14082  * Fork - LGPL
14083  * <script type="text/javascript">
14084  */
14085
14086 if(Roo.dd.DropZone){
14087     
14088 Roo.tree.TreeDropZone = function(tree, config){
14089     this.allowParentInsert = false;
14090     this.allowContainerDrop = false;
14091     this.appendOnly = false;
14092     Roo.tree.TreeDropZone.superclass.constructor.call(this, tree.innerCt, config);
14093     this.tree = tree;
14094     this.lastInsertClass = "x-tree-no-status";
14095     this.dragOverData = {};
14096 };
14097
14098 Roo.extend(Roo.tree.TreeDropZone, Roo.dd.DropZone, {
14099     ddGroup : "TreeDD",
14100     scroll:  true,
14101     
14102     expandDelay : 1000,
14103     
14104     expandNode : function(node){
14105         if(node.hasChildNodes() && !node.isExpanded()){
14106             node.expand(false, null, this.triggerCacheRefresh.createDelegate(this));
14107         }
14108     },
14109     
14110     queueExpand : function(node){
14111         this.expandProcId = this.expandNode.defer(this.expandDelay, this, [node]);
14112     },
14113     
14114     cancelExpand : function(){
14115         if(this.expandProcId){
14116             clearTimeout(this.expandProcId);
14117             this.expandProcId = false;
14118         }
14119     },
14120     
14121     isValidDropPoint : function(n, pt, dd, e, data){
14122         if(!n || !data){ return false; }
14123         var targetNode = n.node;
14124         var dropNode = data.node;
14125         // default drop rules
14126         if(!(targetNode && targetNode.isTarget && pt)){
14127             return false;
14128         }
14129         if(pt == "append" && targetNode.allowChildren === false){
14130             return false;
14131         }
14132         if((pt == "above" || pt == "below") && (targetNode.parentNode && targetNode.parentNode.allowChildren === false)){
14133             return false;
14134         }
14135         if(dropNode && (targetNode == dropNode || dropNode.contains(targetNode))){
14136             return false;
14137         }
14138         // reuse the object
14139         var overEvent = this.dragOverData;
14140         overEvent.tree = this.tree;
14141         overEvent.target = targetNode;
14142         overEvent.data = data;
14143         overEvent.point = pt;
14144         overEvent.source = dd;
14145         overEvent.rawEvent = e;
14146         overEvent.dropNode = dropNode;
14147         overEvent.cancel = false;  
14148         var result = this.tree.fireEvent("nodedragover", overEvent);
14149         return overEvent.cancel === false && result !== false;
14150     },
14151     
14152     getDropPoint : function(e, n, dd)
14153     {
14154         var tn = n.node;
14155         if(tn.isRoot){
14156             return tn.allowChildren !== false ? "append" : false; // always append for root
14157         }
14158         var dragEl = n.ddel;
14159         var t = Roo.lib.Dom.getY(dragEl), b = t + dragEl.offsetHeight;
14160         var y = Roo.lib.Event.getPageY(e);
14161         //var noAppend = tn.allowChildren === false || tn.isLeaf();
14162         
14163         // we may drop nodes anywhere, as long as allowChildren has not been set to false..
14164         var noAppend = tn.allowChildren === false;
14165         if(this.appendOnly || tn.parentNode.allowChildren === false){
14166             return noAppend ? false : "append";
14167         }
14168         var noBelow = false;
14169         if(!this.allowParentInsert){
14170             noBelow = tn.hasChildNodes() && tn.isExpanded();
14171         }
14172         var q = (b - t) / (noAppend ? 2 : 3);
14173         if(y >= t && y < (t + q)){
14174             return "above";
14175         }else if(!noBelow && (noAppend || y >= b-q && y <= b)){
14176             return "below";
14177         }else{
14178             return "append";
14179         }
14180     },
14181     
14182     onNodeEnter : function(n, dd, e, data)
14183     {
14184         this.cancelExpand();
14185     },
14186     
14187     onNodeOver : function(n, dd, e, data)
14188     {
14189        
14190         var pt = this.getDropPoint(e, n, dd);
14191         var node = n.node;
14192         
14193         // auto node expand check
14194         if(!this.expandProcId && pt == "append" && node.hasChildNodes() && !n.node.isExpanded()){
14195             this.queueExpand(node);
14196         }else if(pt != "append"){
14197             this.cancelExpand();
14198         }
14199         
14200         // set the insert point style on the target node
14201         var returnCls = this.dropNotAllowed;
14202         if(this.isValidDropPoint(n, pt, dd, e, data)){
14203            if(pt){
14204                var el = n.ddel;
14205                var cls;
14206                if(pt == "above"){
14207                    returnCls = n.node.isFirst() ? "x-tree-drop-ok-above" : "x-tree-drop-ok-between";
14208                    cls = "x-tree-drag-insert-above";
14209                }else if(pt == "below"){
14210                    returnCls = n.node.isLast() ? "x-tree-drop-ok-below" : "x-tree-drop-ok-between";
14211                    cls = "x-tree-drag-insert-below";
14212                }else{
14213                    returnCls = "x-tree-drop-ok-append";
14214                    cls = "x-tree-drag-append";
14215                }
14216                if(this.lastInsertClass != cls){
14217                    Roo.fly(el).replaceClass(this.lastInsertClass, cls);
14218                    this.lastInsertClass = cls;
14219                }
14220            }
14221        }
14222        return returnCls;
14223     },
14224     
14225     onNodeOut : function(n, dd, e, data){
14226         
14227         this.cancelExpand();
14228         this.removeDropIndicators(n);
14229     },
14230     
14231     onNodeDrop : function(n, dd, e, data){
14232         var point = this.getDropPoint(e, n, dd);
14233         var targetNode = n.node;
14234         targetNode.ui.startDrop();
14235         if(!this.isValidDropPoint(n, point, dd, e, data)){
14236             targetNode.ui.endDrop();
14237             return false;
14238         }
14239         // first try to find the drop node
14240         var dropNode = data.node || (dd.getTreeNode ? dd.getTreeNode(data, targetNode, point, e) : null);
14241         var dropEvent = {
14242             tree : this.tree,
14243             target: targetNode,
14244             data: data,
14245             point: point,
14246             source: dd,
14247             rawEvent: e,
14248             dropNode: dropNode,
14249             cancel: !dropNode   
14250         };
14251         var retval = this.tree.fireEvent("beforenodedrop", dropEvent);
14252         if(retval === false || dropEvent.cancel === true || !dropEvent.dropNode){
14253             targetNode.ui.endDrop();
14254             return false;
14255         }
14256         // allow target changing
14257         targetNode = dropEvent.target;
14258         if(point == "append" && !targetNode.isExpanded()){
14259             targetNode.expand(false, null, function(){
14260                 this.completeDrop(dropEvent);
14261             }.createDelegate(this));
14262         }else{
14263             this.completeDrop(dropEvent);
14264         }
14265         return true;
14266     },
14267     
14268     completeDrop : function(de){
14269         var ns = de.dropNode, p = de.point, t = de.target;
14270         if(!(ns instanceof Array)){
14271             ns = [ns];
14272         }
14273         var n;
14274         for(var i = 0, len = ns.length; i < len; i++){
14275             n = ns[i];
14276             if(p == "above"){
14277                 t.parentNode.insertBefore(n, t);
14278             }else if(p == "below"){
14279                 t.parentNode.insertBefore(n, t.nextSibling);
14280             }else{
14281                 t.appendChild(n);
14282             }
14283         }
14284         n.ui.focus();
14285         if(this.tree.hlDrop){
14286             n.ui.highlight();
14287         }
14288         t.ui.endDrop();
14289         this.tree.fireEvent("nodedrop", de);
14290     },
14291     
14292     afterNodeMoved : function(dd, data, e, targetNode, dropNode){
14293         if(this.tree.hlDrop){
14294             dropNode.ui.focus();
14295             dropNode.ui.highlight();
14296         }
14297         this.tree.fireEvent("nodedrop", this.tree, targetNode, data, dd, e);
14298     },
14299     
14300     getTree : function(){
14301         return this.tree;
14302     },
14303     
14304     removeDropIndicators : function(n){
14305         if(n && n.ddel){
14306             var el = n.ddel;
14307             Roo.fly(el).removeClass([
14308                     "x-tree-drag-insert-above",
14309                     "x-tree-drag-insert-below",
14310                     "x-tree-drag-append"]);
14311             this.lastInsertClass = "_noclass";
14312         }
14313     },
14314     
14315     beforeDragDrop : function(target, e, id){
14316         this.cancelExpand();
14317         return true;
14318     },
14319     
14320     afterRepair : function(data){
14321         if(data && Roo.enableFx){
14322             data.node.ui.highlight();
14323         }
14324         this.hideProxy();
14325     } 
14326     
14327 });
14328
14329 }
14330 /*
14331  * Based on:
14332  * Ext JS Library 1.1.1
14333  * Copyright(c) 2006-2007, Ext JS, LLC.
14334  *
14335  * Originally Released Under LGPL - original licence link has changed is not relivant.
14336  *
14337  * Fork - LGPL
14338  * <script type="text/javascript">
14339  */
14340  
14341
14342 if(Roo.dd.DragZone){
14343 Roo.tree.TreeDragZone = function(tree, config){
14344     Roo.tree.TreeDragZone.superclass.constructor.call(this, tree.getTreeEl(), config);
14345     this.tree = tree;
14346 };
14347
14348 Roo.extend(Roo.tree.TreeDragZone, Roo.dd.DragZone, {
14349     ddGroup : "TreeDD",
14350    
14351     onBeforeDrag : function(data, e){
14352         var n = data.node;
14353         return n && n.draggable && !n.disabled;
14354     },
14355      
14356     
14357     onInitDrag : function(e){
14358         var data = this.dragData;
14359         this.tree.getSelectionModel().select(data.node);
14360         this.proxy.update("");
14361         data.node.ui.appendDDGhost(this.proxy.ghost.dom);
14362         this.tree.fireEvent("startdrag", this.tree, data.node, e);
14363     },
14364     
14365     getRepairXY : function(e, data){
14366         return data.node.ui.getDDRepairXY();
14367     },
14368     
14369     onEndDrag : function(data, e){
14370         this.tree.fireEvent("enddrag", this.tree, data.node, e);
14371         
14372         
14373     },
14374     
14375     onValidDrop : function(dd, e, id){
14376         this.tree.fireEvent("dragdrop", this.tree, this.dragData.node, dd, e);
14377         this.hideProxy();
14378     },
14379     
14380     beforeInvalidDrop : function(e, id){
14381         // this scrolls the original position back into view
14382         var sm = this.tree.getSelectionModel();
14383         sm.clearSelections();
14384         sm.select(this.dragData.node);
14385     }
14386 });
14387 }/*
14388  * Based on:
14389  * Ext JS Library 1.1.1
14390  * Copyright(c) 2006-2007, Ext JS, LLC.
14391  *
14392  * Originally Released Under LGPL - original licence link has changed is not relivant.
14393  *
14394  * Fork - LGPL
14395  * <script type="text/javascript">
14396  */
14397 /**
14398  * @class Roo.tree.TreeEditor
14399  * @extends Roo.Editor
14400  * Provides editor functionality for inline tree node editing.  Any valid {@link Roo.form.Field} can be used
14401  * as the editor field.
14402  * @constructor
14403  * @param {Object} config (used to be the tree panel.)
14404  * @param {Object} oldconfig DEPRECIATED Either a prebuilt {@link Roo.form.Field} instance or a Field config object
14405  * 
14406  * @cfg {Roo.tree.TreePanel} tree The tree to bind to.
14407  * @cfg {Roo.form.TextField|Object} field The field configuration
14408  *
14409  * 
14410  */
14411 Roo.tree.TreeEditor = function(config, oldconfig) { // was -- (tree, config){
14412     var tree = config;
14413     var field;
14414     if (oldconfig) { // old style..
14415         field = oldconfig.events ? oldconfig : new Roo.form.TextField(oldconfig);
14416     } else {
14417         // new style..
14418         tree = config.tree;
14419         config.field = config.field  || {};
14420         config.field.xtype = 'TextField';
14421         field = Roo.factory(config.field, Roo.form);
14422     }
14423     config = config || {};
14424     
14425     
14426     this.addEvents({
14427         /**
14428          * @event beforenodeedit
14429          * Fires when editing is initiated, but before the value changes.  Editing can be canceled by returning
14430          * false from the handler of this event.
14431          * @param {Editor} this
14432          * @param {Roo.tree.Node} node 
14433          */
14434         "beforenodeedit" : true
14435     });
14436     
14437     //Roo.log(config);
14438     Roo.tree.TreeEditor.superclass.constructor.call(this, field, config);
14439
14440     this.tree = tree;
14441
14442     tree.on('beforeclick', this.beforeNodeClick, this);
14443     tree.getTreeEl().on('mousedown', this.hide, this);
14444     this.on('complete', this.updateNode, this);
14445     this.on('beforestartedit', this.fitToTree, this);
14446     this.on('startedit', this.bindScroll, this, {delay:10});
14447     this.on('specialkey', this.onSpecialKey, this);
14448 };
14449
14450 Roo.extend(Roo.tree.TreeEditor, Roo.Editor, {
14451     /**
14452      * @cfg {String} alignment
14453      * The position to align to (see {@link Roo.Element#alignTo} for more details, defaults to "l-l").
14454      */
14455     alignment: "l-l",
14456     // inherit
14457     autoSize: false,
14458     /**
14459      * @cfg {Boolean} hideEl
14460      * True to hide the bound element while the editor is displayed (defaults to false)
14461      */
14462     hideEl : false,
14463     /**
14464      * @cfg {String} cls
14465      * CSS class to apply to the editor (defaults to "x-small-editor x-tree-editor")
14466      */
14467     cls: "x-small-editor x-tree-editor",
14468     /**
14469      * @cfg {Boolean} shim
14470      * True to shim the editor if selects/iframes could be displayed beneath it (defaults to false)
14471      */
14472     shim:false,
14473     // inherit
14474     shadow:"frame",
14475     /**
14476      * @cfg {Number} maxWidth
14477      * The maximum width in pixels of the editor field (defaults to 250).  Note that if the maxWidth would exceed
14478      * the containing tree element's size, it will be automatically limited for you to the container width, taking
14479      * scroll and client offsets into account prior to each edit.
14480      */
14481     maxWidth: 250,
14482
14483     editDelay : 350,
14484
14485     // private
14486     fitToTree : function(ed, el){
14487         var td = this.tree.getTreeEl().dom, nd = el.dom;
14488         if(td.scrollLeft >  nd.offsetLeft){ // ensure the node left point is visible
14489             td.scrollLeft = nd.offsetLeft;
14490         }
14491         var w = Math.min(
14492                 this.maxWidth,
14493                 (td.clientWidth > 20 ? td.clientWidth : td.offsetWidth) - Math.max(0, nd.offsetLeft-td.scrollLeft) - /*cushion*/5);
14494         this.setSize(w, '');
14495         
14496         return this.fireEvent('beforenodeedit', this, this.editNode);
14497         
14498     },
14499
14500     // private
14501     triggerEdit : function(node){
14502         this.completeEdit();
14503         this.editNode = node;
14504         this.startEdit(node.ui.textNode, node.text);
14505     },
14506
14507     // private
14508     bindScroll : function(){
14509         this.tree.getTreeEl().on('scroll', this.cancelEdit, this);
14510     },
14511
14512     // private
14513     beforeNodeClick : function(node, e){
14514         var sinceLast = (this.lastClick ? this.lastClick.getElapsed() : 0);
14515         this.lastClick = new Date();
14516         if(sinceLast > this.editDelay && this.tree.getSelectionModel().isSelected(node)){
14517             e.stopEvent();
14518             this.triggerEdit(node);
14519             return false;
14520         }
14521         return true;
14522     },
14523
14524     // private
14525     updateNode : function(ed, value){
14526         this.tree.getTreeEl().un('scroll', this.cancelEdit, this);
14527         this.editNode.setText(value);
14528     },
14529
14530     // private
14531     onHide : function(){
14532         Roo.tree.TreeEditor.superclass.onHide.call(this);
14533         if(this.editNode){
14534             this.editNode.ui.focus();
14535         }
14536     },
14537
14538     // private
14539     onSpecialKey : function(field, e){
14540         var k = e.getKey();
14541         if(k == e.ESC){
14542             e.stopEvent();
14543             this.cancelEdit();
14544         }else if(k == e.ENTER && !e.hasModifier()){
14545             e.stopEvent();
14546             this.completeEdit();
14547         }
14548     }
14549 });//<Script type="text/javascript">
14550 /*
14551  * Based on:
14552  * Ext JS Library 1.1.1
14553  * Copyright(c) 2006-2007, Ext JS, LLC.
14554  *
14555  * Originally Released Under LGPL - original licence link has changed is not relivant.
14556  *
14557  * Fork - LGPL
14558  * <script type="text/javascript">
14559  */
14560  
14561 /**
14562  * Not documented??? - probably should be...
14563  */
14564
14565 Roo.tree.ColumnNodeUI = Roo.extend(Roo.tree.TreeNodeUI, {
14566     //focus: Roo.emptyFn, // prevent odd scrolling behavior
14567     
14568     renderElements : function(n, a, targetNode, bulkRender){
14569         //consel.log("renderElements?");
14570         this.indentMarkup = n.parentNode ? n.parentNode.ui.getChildIndent() : '';
14571
14572         var t = n.getOwnerTree();
14573         var tid = Pman.Tab.Document_TypesTree.tree.el.id;
14574         
14575         var cols = t.columns;
14576         var bw = t.borderWidth;
14577         var c = cols[0];
14578         var href = a.href ? a.href : Roo.isGecko ? "" : "#";
14579          var cb = typeof a.checked == "boolean";
14580         var tx = String.format('{0}',n.text || (c.renderer ? c.renderer(a[c.dataIndex], n, a) : a[c.dataIndex]));
14581         var colcls = 'x-t-' + tid + '-c0';
14582         var buf = [
14583             '<li class="x-tree-node">',
14584             
14585                 
14586                 '<div class="x-tree-node-el ', a.cls,'">',
14587                     // extran...
14588                     '<div class="x-tree-col ', colcls, '" style="width:', c.width-bw, 'px;">',
14589                 
14590                 
14591                         '<span class="x-tree-node-indent">',this.indentMarkup,'</span>',
14592                         '<img src="', this.emptyIcon, '" class="x-tree-ec-icon  " />',
14593                         '<img src="', a.icon || this.emptyIcon, '" class="x-tree-node-icon',
14594                            (a.icon ? ' x-tree-node-inline-icon' : ''),
14595                            (a.iconCls ? ' '+a.iconCls : ''),
14596                            '" unselectable="on" />',
14597                         (cb ? ('<input class="x-tree-node-cb" type="checkbox" ' + 
14598                              (a.checked ? 'checked="checked" />' : ' />')) : ''),
14599                              
14600                         '<a class="x-tree-node-anchor" hidefocus="on" href="',href,'" tabIndex="1" ',
14601                             (a.hrefTarget ? ' target="' +a.hrefTarget + '"' : ''), '>',
14602                             '<span unselectable="on" qtip="' + tx + '">',
14603                              tx,
14604                              '</span></a>' ,
14605                     '</div>',
14606                      '<a class="x-tree-node-anchor" hidefocus="on" href="',href,'" tabIndex="1" ',
14607                             (a.hrefTarget ? ' target="' +a.hrefTarget + '"' : ''), '>'
14608                  ];
14609         for(var i = 1, len = cols.length; i < len; i++){
14610             c = cols[i];
14611             colcls = 'x-t-' + tid + '-c' +i;
14612             tx = String.format('{0}', (c.renderer ? c.renderer(a[c.dataIndex], n, a) : a[c.dataIndex]));
14613             buf.push('<div class="x-tree-col ', colcls, ' ' ,(c.cls?c.cls:''),'" style="width:',c.width-bw,'px;">',
14614                         '<div class="x-tree-col-text" qtip="' + tx +'">',tx,"</div>",
14615                       "</div>");
14616          }
14617          
14618          buf.push(
14619             '</a>',
14620             '<div class="x-clear"></div></div>',
14621             '<ul class="x-tree-node-ct" style="display:none;"></ul>',
14622             "</li>");
14623         
14624         if(bulkRender !== true && n.nextSibling && n.nextSibling.ui.getEl()){
14625             this.wrap = Roo.DomHelper.insertHtml("beforeBegin",
14626                                 n.nextSibling.ui.getEl(), buf.join(""));
14627         }else{
14628             this.wrap = Roo.DomHelper.insertHtml("beforeEnd", targetNode, buf.join(""));
14629         }
14630         var el = this.wrap.firstChild;
14631         this.elRow = el;
14632         this.elNode = el.firstChild;
14633         this.ranchor = el.childNodes[1];
14634         this.ctNode = this.wrap.childNodes[1];
14635         var cs = el.firstChild.childNodes;
14636         this.indentNode = cs[0];
14637         this.ecNode = cs[1];
14638         this.iconNode = cs[2];
14639         var index = 3;
14640         if(cb){
14641             this.checkbox = cs[3];
14642             index++;
14643         }
14644         this.anchor = cs[index];
14645         
14646         this.textNode = cs[index].firstChild;
14647         
14648         //el.on("click", this.onClick, this);
14649         //el.on("dblclick", this.onDblClick, this);
14650         
14651         
14652        // console.log(this);
14653     },
14654     initEvents : function(){
14655         Roo.tree.ColumnNodeUI.superclass.initEvents.call(this);
14656         
14657             
14658         var a = this.ranchor;
14659
14660         var el = Roo.get(a);
14661
14662         if(Roo.isOpera){ // opera render bug ignores the CSS
14663             el.setStyle("text-decoration", "none");
14664         }
14665
14666         el.on("click", this.onClick, this);
14667         el.on("dblclick", this.onDblClick, this);
14668         el.on("contextmenu", this.onContextMenu, this);
14669         
14670     },
14671     
14672     /*onSelectedChange : function(state){
14673         if(state){
14674             this.focus();
14675             this.addClass("x-tree-selected");
14676         }else{
14677             //this.blur();
14678             this.removeClass("x-tree-selected");
14679         }
14680     },*/
14681     addClass : function(cls){
14682         if(this.elRow){
14683             Roo.fly(this.elRow).addClass(cls);
14684         }
14685         
14686     },
14687     
14688     
14689     removeClass : function(cls){
14690         if(this.elRow){
14691             Roo.fly(this.elRow).removeClass(cls);
14692         }
14693     }
14694
14695     
14696     
14697 });//<Script type="text/javascript">
14698
14699 /*
14700  * Based on:
14701  * Ext JS Library 1.1.1
14702  * Copyright(c) 2006-2007, Ext JS, LLC.
14703  *
14704  * Originally Released Under LGPL - original licence link has changed is not relivant.
14705  *
14706  * Fork - LGPL
14707  * <script type="text/javascript">
14708  */
14709  
14710
14711 /**
14712  * @class Roo.tree.ColumnTree
14713  * @extends Roo.data.TreePanel
14714  * @cfg {Object} columns  Including width, header, renderer, cls, dataIndex 
14715  * @cfg {int} borderWidth  compined right/left border allowance
14716  * @constructor
14717  * @param {String/HTMLElement/Element} el The container element
14718  * @param {Object} config
14719  */
14720 Roo.tree.ColumnTree =  function(el, config)
14721 {
14722    Roo.tree.ColumnTree.superclass.constructor.call(this, el , config);
14723    this.addEvents({
14724         /**
14725         * @event resize
14726         * Fire this event on a container when it resizes
14727         * @param {int} w Width
14728         * @param {int} h Height
14729         */
14730        "resize" : true
14731     });
14732     this.on('resize', this.onResize, this);
14733 };
14734
14735 Roo.extend(Roo.tree.ColumnTree, Roo.tree.TreePanel, {
14736     //lines:false,
14737     
14738     
14739     borderWidth: Roo.isBorderBox ? 0 : 2, 
14740     headEls : false,
14741     
14742     render : function(){
14743         // add the header.....
14744        
14745         Roo.tree.ColumnTree.superclass.render.apply(this);
14746         
14747         this.el.addClass('x-column-tree');
14748         
14749         this.headers = this.el.createChild(
14750             {cls:'x-tree-headers'},this.innerCt.dom);
14751    
14752         var cols = this.columns, c;
14753         var totalWidth = 0;
14754         this.headEls = [];
14755         var  len = cols.length;
14756         for(var i = 0; i < len; i++){
14757              c = cols[i];
14758              totalWidth += c.width;
14759             this.headEls.push(this.headers.createChild({
14760                  cls:'x-tree-hd ' + (c.cls?c.cls+'-hd':''),
14761                  cn: {
14762                      cls:'x-tree-hd-text',
14763                      html: c.header
14764                  },
14765                  style:'width:'+(c.width-this.borderWidth)+'px;'
14766              }));
14767         }
14768         this.headers.createChild({cls:'x-clear'});
14769         // prevent floats from wrapping when clipped
14770         this.headers.setWidth(totalWidth);
14771         //this.innerCt.setWidth(totalWidth);
14772         this.innerCt.setStyle({ overflow: 'auto' });
14773         this.onResize(this.width, this.height);
14774              
14775         
14776     },
14777     onResize : function(w,h)
14778     {
14779         this.height = h;
14780         this.width = w;
14781         // resize cols..
14782         this.innerCt.setWidth(this.width);
14783         this.innerCt.setHeight(this.height-20);
14784         
14785         // headers...
14786         var cols = this.columns, c;
14787         var totalWidth = 0;
14788         var expEl = false;
14789         var len = cols.length;
14790         for(var i = 0; i < len; i++){
14791             c = cols[i];
14792             if (this.autoExpandColumn !== false && c.dataIndex == this.autoExpandColumn) {
14793                 // it's the expander..
14794                 expEl  = this.headEls[i];
14795                 continue;
14796             }
14797             totalWidth += c.width;
14798             
14799         }
14800         if (expEl) {
14801             expEl.setWidth(  ((w - totalWidth)-this.borderWidth - 20));
14802         }
14803         this.headers.setWidth(w-20);
14804
14805         
14806         
14807         
14808     }
14809 });
14810 /*
14811  * Based on:
14812  * Ext JS Library 1.1.1
14813  * Copyright(c) 2006-2007, Ext JS, LLC.
14814  *
14815  * Originally Released Under LGPL - original licence link has changed is not relivant.
14816  *
14817  * Fork - LGPL
14818  * <script type="text/javascript">
14819  */
14820  
14821 /**
14822  * @class Roo.menu.Menu
14823  * @extends Roo.util.Observable
14824  * A menu object.  This is the container to which you add all other menu items.  Menu can also serve a as a base class
14825  * when you want a specialzed menu based off of another component (like {@link Roo.menu.DateMenu} for example).
14826  * @constructor
14827  * Creates a new Menu
14828  * @param {Object} config Configuration options
14829  */
14830 Roo.menu.Menu = function(config){
14831     
14832     Roo.menu.Menu.superclass.constructor.call(this, config);
14833     
14834     this.id = this.id || Roo.id();
14835     this.addEvents({
14836         /**
14837          * @event beforeshow
14838          * Fires before this menu is displayed
14839          * @param {Roo.menu.Menu} this
14840          */
14841         beforeshow : true,
14842         /**
14843          * @event beforehide
14844          * Fires before this menu is hidden
14845          * @param {Roo.menu.Menu} this
14846          */
14847         beforehide : true,
14848         /**
14849          * @event show
14850          * Fires after this menu is displayed
14851          * @param {Roo.menu.Menu} this
14852          */
14853         show : true,
14854         /**
14855          * @event hide
14856          * Fires after this menu is hidden
14857          * @param {Roo.menu.Menu} this
14858          */
14859         hide : true,
14860         /**
14861          * @event click
14862          * Fires when this menu is clicked (or when the enter key is pressed while it is active)
14863          * @param {Roo.menu.Menu} this
14864          * @param {Roo.menu.Item} menuItem The menu item that was clicked
14865          * @param {Roo.EventObject} e
14866          */
14867         click : true,
14868         /**
14869          * @event mouseover
14870          * Fires when the mouse is hovering over this menu
14871          * @param {Roo.menu.Menu} this
14872          * @param {Roo.EventObject} e
14873          * @param {Roo.menu.Item} menuItem The menu item that was clicked
14874          */
14875         mouseover : true,
14876         /**
14877          * @event mouseout
14878          * Fires when the mouse exits this menu
14879          * @param {Roo.menu.Menu} this
14880          * @param {Roo.EventObject} e
14881          * @param {Roo.menu.Item} menuItem The menu item that was clicked
14882          */
14883         mouseout : true,
14884         /**
14885          * @event itemclick
14886          * Fires when a menu item contained in this menu is clicked
14887          * @param {Roo.menu.BaseItem} baseItem The BaseItem that was clicked
14888          * @param {Roo.EventObject} e
14889          */
14890         itemclick: true
14891     });
14892     if (this.registerMenu) {
14893         Roo.menu.MenuMgr.register(this);
14894     }
14895     
14896     var mis = this.items;
14897     this.items = new Roo.util.MixedCollection();
14898     if(mis){
14899         this.add.apply(this, mis);
14900     }
14901 };
14902
14903 Roo.extend(Roo.menu.Menu, Roo.util.Observable, {
14904     /**
14905      * @cfg {Number} minWidth The minimum width of the menu in pixels (defaults to 120)
14906      */
14907     minWidth : 120,
14908     /**
14909      * @cfg {Boolean/String} shadow True or "sides" for the default effect, "frame" for 4-way shadow, and "drop"
14910      * for bottom-right shadow (defaults to "sides")
14911      */
14912     shadow : "sides",
14913     /**
14914      * @cfg {String} subMenuAlign The {@link Roo.Element#alignTo} anchor position value to use for submenus of
14915      * this menu (defaults to "tl-tr?")
14916      */
14917     subMenuAlign : "tl-tr?",
14918     /**
14919      * @cfg {String} defaultAlign The default {@link Roo.Element#alignTo) anchor position value for this menu
14920      * relative to its element of origin (defaults to "tl-bl?")
14921      */
14922     defaultAlign : "tl-bl?",
14923     /**
14924      * @cfg {Boolean} allowOtherMenus True to allow multiple menus to be displayed at the same time (defaults to false)
14925      */
14926     allowOtherMenus : false,
14927     /**
14928      * @cfg {Boolean} registerMenu True (default) - means that clicking on screen etc. hides it.
14929      */
14930     registerMenu : true,
14931
14932     hidden:true,
14933
14934     // private
14935     render : function(){
14936         if(this.el){
14937             return;
14938         }
14939         var el = this.el = new Roo.Layer({
14940             cls: "x-menu",
14941             shadow:this.shadow,
14942             constrain: false,
14943             parentEl: this.parentEl || document.body,
14944             zindex:15000
14945         });
14946
14947         this.keyNav = new Roo.menu.MenuNav(this);
14948
14949         if(this.plain){
14950             el.addClass("x-menu-plain");
14951         }
14952         if(this.cls){
14953             el.addClass(this.cls);
14954         }
14955         // generic focus element
14956         this.focusEl = el.createChild({
14957             tag: "a", cls: "x-menu-focus", href: "#", onclick: "return false;", tabIndex:"-1"
14958         });
14959         var ul = el.createChild({tag: "ul", cls: "x-menu-list"});
14960         //disabling touch- as it's causing issues ..
14961         //ul.on(Roo.isTouch ? 'touchstart' : 'click'   , this.onClick, this);
14962         ul.on('click'   , this.onClick, this);
14963         
14964         
14965         ul.on("mouseover", this.onMouseOver, this);
14966         ul.on("mouseout", this.onMouseOut, this);
14967         this.items.each(function(item){
14968             if (item.hidden) {
14969                 return;
14970             }
14971             
14972             var li = document.createElement("li");
14973             li.className = "x-menu-list-item";
14974             ul.dom.appendChild(li);
14975             item.render(li, this);
14976         }, this);
14977         this.ul = ul;
14978         this.autoWidth();
14979     },
14980
14981     // private
14982     autoWidth : function(){
14983         var el = this.el, ul = this.ul;
14984         if(!el){
14985             return;
14986         }
14987         var w = this.width;
14988         if(w){
14989             el.setWidth(w);
14990         }else if(Roo.isIE){
14991             el.setWidth(this.minWidth);
14992             var t = el.dom.offsetWidth; // force recalc
14993             el.setWidth(ul.getWidth()+el.getFrameWidth("lr"));
14994         }
14995     },
14996
14997     // private
14998     delayAutoWidth : function(){
14999         if(this.rendered){
15000             if(!this.awTask){
15001                 this.awTask = new Roo.util.DelayedTask(this.autoWidth, this);
15002             }
15003             this.awTask.delay(20);
15004         }
15005     },
15006
15007     // private
15008     findTargetItem : function(e){
15009         var t = e.getTarget(".x-menu-list-item", this.ul,  true);
15010         if(t && t.menuItemId){
15011             return this.items.get(t.menuItemId);
15012         }
15013     },
15014
15015     // private
15016     onClick : function(e){
15017         Roo.log("menu.onClick");
15018         var t = this.findTargetItem(e);
15019         if(!t){
15020             return;
15021         }
15022         Roo.log(e);
15023         if (Roo.isTouch && e.type == 'touchstart' && t.menu  && !t.disabled) {
15024             if(t == this.activeItem && t.shouldDeactivate(e)){
15025                 this.activeItem.deactivate();
15026                 delete this.activeItem;
15027                 return;
15028             }
15029             if(t.canActivate){
15030                 this.setActiveItem(t, true);
15031             }
15032             return;
15033             
15034             
15035         }
15036         
15037         t.onClick(e);
15038         this.fireEvent("click", this, t, e);
15039     },
15040
15041     // private
15042     setActiveItem : function(item, autoExpand){
15043         if(item != this.activeItem){
15044             if(this.activeItem){
15045                 this.activeItem.deactivate();
15046             }
15047             this.activeItem = item;
15048             item.activate(autoExpand);
15049         }else if(autoExpand){
15050             item.expandMenu();
15051         }
15052     },
15053
15054     // private
15055     tryActivate : function(start, step){
15056         var items = this.items;
15057         for(var i = start, len = items.length; i >= 0 && i < len; i+= step){
15058             var item = items.get(i);
15059             if(!item.disabled && item.canActivate){
15060                 this.setActiveItem(item, false);
15061                 return item;
15062             }
15063         }
15064         return false;
15065     },
15066
15067     // private
15068     onMouseOver : function(e){
15069         var t;
15070         if(t = this.findTargetItem(e)){
15071             if(t.canActivate && !t.disabled){
15072                 this.setActiveItem(t, true);
15073             }
15074         }
15075         this.fireEvent("mouseover", this, e, t);
15076     },
15077
15078     // private
15079     onMouseOut : function(e){
15080         var t;
15081         if(t = this.findTargetItem(e)){
15082             if(t == this.activeItem && t.shouldDeactivate(e)){
15083                 this.activeItem.deactivate();
15084                 delete this.activeItem;
15085             }
15086         }
15087         this.fireEvent("mouseout", this, e, t);
15088     },
15089
15090     /**
15091      * Read-only.  Returns true if the menu is currently displayed, else false.
15092      * @type Boolean
15093      */
15094     isVisible : function(){
15095         return this.el && !this.hidden;
15096     },
15097
15098     /**
15099      * Displays this menu relative to another element
15100      * @param {String/HTMLElement/Roo.Element} element The element to align to
15101      * @param {String} position (optional) The {@link Roo.Element#alignTo} anchor position to use in aligning to
15102      * the element (defaults to this.defaultAlign)
15103      * @param {Roo.menu.Menu} parentMenu (optional) This menu's parent menu, if applicable (defaults to undefined)
15104      */
15105     show : function(el, pos, parentMenu){
15106         this.parentMenu = parentMenu;
15107         if(!this.el){
15108             this.render();
15109         }
15110         this.fireEvent("beforeshow", this);
15111         this.showAt(this.el.getAlignToXY(el, pos || this.defaultAlign), parentMenu, false);
15112     },
15113
15114     /**
15115      * Displays this menu at a specific xy position
15116      * @param {Array} xyPosition Contains X & Y [x, y] values for the position at which to show the menu (coordinates are page-based)
15117      * @param {Roo.menu.Menu} parentMenu (optional) This menu's parent menu, if applicable (defaults to undefined)
15118      */
15119     showAt : function(xy, parentMenu, /* private: */_e){
15120         this.parentMenu = parentMenu;
15121         if(!this.el){
15122             this.render();
15123         }
15124         if(_e !== false){
15125             this.fireEvent("beforeshow", this);
15126             xy = this.el.adjustForConstraints(xy);
15127         }
15128         this.el.setXY(xy);
15129         this.el.show();
15130         this.hidden = false;
15131         this.focus();
15132         this.fireEvent("show", this);
15133     },
15134
15135     focus : function(){
15136         if(!this.hidden){
15137             this.doFocus.defer(50, this);
15138         }
15139     },
15140
15141     doFocus : function(){
15142         if(!this.hidden){
15143             this.focusEl.focus();
15144         }
15145     },
15146
15147     /**
15148      * Hides this menu and optionally all parent menus
15149      * @param {Boolean} deep (optional) True to hide all parent menus recursively, if any (defaults to false)
15150      */
15151     hide : function(deep){
15152         if(this.el && this.isVisible()){
15153             this.fireEvent("beforehide", this);
15154             if(this.activeItem){
15155                 this.activeItem.deactivate();
15156                 this.activeItem = null;
15157             }
15158             this.el.hide();
15159             this.hidden = true;
15160             this.fireEvent("hide", this);
15161         }
15162         if(deep === true && this.parentMenu){
15163             this.parentMenu.hide(true);
15164         }
15165     },
15166
15167     /**
15168      * Addds one or more items of any type supported by the Menu class, or that can be converted into menu items.
15169      * Any of the following are valid:
15170      * <ul>
15171      * <li>Any menu item object based on {@link Roo.menu.Item}</li>
15172      * <li>An HTMLElement object which will be converted to a menu item</li>
15173      * <li>A menu item config object that will be created as a new menu item</li>
15174      * <li>A string, which can either be '-' or 'separator' to add a menu separator, otherwise
15175      * it will be converted into a {@link Roo.menu.TextItem} and added</li>
15176      * </ul>
15177      * Usage:
15178      * <pre><code>
15179 // Create the menu
15180 var menu = new Roo.menu.Menu();
15181
15182 // Create a menu item to add by reference
15183 var menuItem = new Roo.menu.Item({ text: 'New Item!' });
15184
15185 // Add a bunch of items at once using different methods.
15186 // Only the last item added will be returned.
15187 var item = menu.add(
15188     menuItem,                // add existing item by ref
15189     'Dynamic Item',          // new TextItem
15190     '-',                     // new separator
15191     { text: 'Config Item' }  // new item by config
15192 );
15193 </code></pre>
15194      * @param {Mixed} args One or more menu items, menu item configs or other objects that can be converted to menu items
15195      * @return {Roo.menu.Item} The menu item that was added, or the last one if multiple items were added
15196      */
15197     add : function(){
15198         var a = arguments, l = a.length, item;
15199         for(var i = 0; i < l; i++){
15200             var el = a[i];
15201             if ((typeof(el) == "object") && el.xtype && el.xns) {
15202                 el = Roo.factory(el, Roo.menu);
15203             }
15204             
15205             if(el.render){ // some kind of Item
15206                 item = this.addItem(el);
15207             }else if(typeof el == "string"){ // string
15208                 if(el == "separator" || el == "-"){
15209                     item = this.addSeparator();
15210                 }else{
15211                     item = this.addText(el);
15212                 }
15213             }else if(el.tagName || el.el){ // element
15214                 item = this.addElement(el);
15215             }else if(typeof el == "object"){ // must be menu item config?
15216                 item = this.addMenuItem(el);
15217             }
15218         }
15219         return item;
15220     },
15221
15222     /**
15223      * Returns this menu's underlying {@link Roo.Element} object
15224      * @return {Roo.Element} The element
15225      */
15226     getEl : function(){
15227         if(!this.el){
15228             this.render();
15229         }
15230         return this.el;
15231     },
15232
15233     /**
15234      * Adds a separator bar to the menu
15235      * @return {Roo.menu.Item} The menu item that was added
15236      */
15237     addSeparator : function(){
15238         return this.addItem(new Roo.menu.Separator());
15239     },
15240
15241     /**
15242      * Adds an {@link Roo.Element} object to the menu
15243      * @param {String/HTMLElement/Roo.Element} el The element or DOM node to add, or its id
15244      * @return {Roo.menu.Item} The menu item that was added
15245      */
15246     addElement : function(el){
15247         return this.addItem(new Roo.menu.BaseItem(el));
15248     },
15249
15250     /**
15251      * Adds an existing object based on {@link Roo.menu.Item} to the menu
15252      * @param {Roo.menu.Item} item The menu item to add
15253      * @return {Roo.menu.Item} The menu item that was added
15254      */
15255     addItem : function(item){
15256         this.items.add(item);
15257         if(this.ul){
15258             var li = document.createElement("li");
15259             li.className = "x-menu-list-item";
15260             this.ul.dom.appendChild(li);
15261             item.render(li, this);
15262             this.delayAutoWidth();
15263         }
15264         return item;
15265     },
15266
15267     /**
15268      * Creates a new {@link Roo.menu.Item} based an the supplied config object and adds it to the menu
15269      * @param {Object} config A MenuItem config object
15270      * @return {Roo.menu.Item} The menu item that was added
15271      */
15272     addMenuItem : function(config){
15273         if(!(config instanceof Roo.menu.Item)){
15274             if(typeof config.checked == "boolean"){ // must be check menu item config?
15275                 config = new Roo.menu.CheckItem(config);
15276             }else{
15277                 config = new Roo.menu.Item(config);
15278             }
15279         }
15280         return this.addItem(config);
15281     },
15282
15283     /**
15284      * Creates a new {@link Roo.menu.TextItem} with the supplied text and adds it to the menu
15285      * @param {String} text The text to display in the menu item
15286      * @return {Roo.menu.Item} The menu item that was added
15287      */
15288     addText : function(text){
15289         return this.addItem(new Roo.menu.TextItem({ text : text }));
15290     },
15291
15292     /**
15293      * Inserts an existing object based on {@link Roo.menu.Item} to the menu at a specified index
15294      * @param {Number} index The index in the menu's list of current items where the new item should be inserted
15295      * @param {Roo.menu.Item} item The menu item to add
15296      * @return {Roo.menu.Item} The menu item that was added
15297      */
15298     insert : function(index, item){
15299         this.items.insert(index, item);
15300         if(this.ul){
15301             var li = document.createElement("li");
15302             li.className = "x-menu-list-item";
15303             this.ul.dom.insertBefore(li, this.ul.dom.childNodes[index]);
15304             item.render(li, this);
15305             this.delayAutoWidth();
15306         }
15307         return item;
15308     },
15309
15310     /**
15311      * Removes an {@link Roo.menu.Item} from the menu and destroys the object
15312      * @param {Roo.menu.Item} item The menu item to remove
15313      */
15314     remove : function(item){
15315         this.items.removeKey(item.id);
15316         item.destroy();
15317     },
15318
15319     /**
15320      * Removes and destroys all items in the menu
15321      */
15322     removeAll : function(){
15323         var f;
15324         while(f = this.items.first()){
15325             this.remove(f);
15326         }
15327     }
15328 });
15329
15330 // MenuNav is a private utility class used internally by the Menu
15331 Roo.menu.MenuNav = function(menu){
15332     Roo.menu.MenuNav.superclass.constructor.call(this, menu.el);
15333     this.scope = this.menu = menu;
15334 };
15335
15336 Roo.extend(Roo.menu.MenuNav, Roo.KeyNav, {
15337     doRelay : function(e, h){
15338         var k = e.getKey();
15339         if(!this.menu.activeItem && e.isNavKeyPress() && k != e.SPACE && k != e.RETURN){
15340             this.menu.tryActivate(0, 1);
15341             return false;
15342         }
15343         return h.call(this.scope || this, e, this.menu);
15344     },
15345
15346     up : function(e, m){
15347         if(!m.tryActivate(m.items.indexOf(m.activeItem)-1, -1)){
15348             m.tryActivate(m.items.length-1, -1);
15349         }
15350     },
15351
15352     down : function(e, m){
15353         if(!m.tryActivate(m.items.indexOf(m.activeItem)+1, 1)){
15354             m.tryActivate(0, 1);
15355         }
15356     },
15357
15358     right : function(e, m){
15359         if(m.activeItem){
15360             m.activeItem.expandMenu(true);
15361         }
15362     },
15363
15364     left : function(e, m){
15365         m.hide();
15366         if(m.parentMenu && m.parentMenu.activeItem){
15367             m.parentMenu.activeItem.activate();
15368         }
15369     },
15370
15371     enter : function(e, m){
15372         if(m.activeItem){
15373             e.stopPropagation();
15374             m.activeItem.onClick(e);
15375             m.fireEvent("click", this, m.activeItem);
15376             return true;
15377         }
15378     }
15379 });/*
15380  * Based on:
15381  * Ext JS Library 1.1.1
15382  * Copyright(c) 2006-2007, Ext JS, LLC.
15383  *
15384  * Originally Released Under LGPL - original licence link has changed is not relivant.
15385  *
15386  * Fork - LGPL
15387  * <script type="text/javascript">
15388  */
15389  
15390 /**
15391  * @class Roo.menu.MenuMgr
15392  * Provides a common registry of all menu items on a page so that they can be easily accessed by id.
15393  * @singleton
15394  */
15395 Roo.menu.MenuMgr = function(){
15396    var menus, active, groups = {}, attached = false, lastShow = new Date();
15397
15398    // private - called when first menu is created
15399    function init(){
15400        menus = {};
15401        active = new Roo.util.MixedCollection();
15402        Roo.get(document).addKeyListener(27, function(){
15403            if(active.length > 0){
15404                hideAll();
15405            }
15406        });
15407    }
15408
15409    // private
15410    function hideAll(){
15411        if(active && active.length > 0){
15412            var c = active.clone();
15413            c.each(function(m){
15414                m.hide();
15415            });
15416        }
15417    }
15418
15419    // private
15420    function onHide(m){
15421        active.remove(m);
15422        if(active.length < 1){
15423            Roo.get(document).un("mousedown", onMouseDown);
15424            attached = false;
15425        }
15426    }
15427
15428    // private
15429    function onShow(m){
15430        var last = active.last();
15431        lastShow = new Date();
15432        active.add(m);
15433        if(!attached){
15434            Roo.get(document).on("mousedown", onMouseDown);
15435            attached = true;
15436        }
15437        if(m.parentMenu){
15438           m.getEl().setZIndex(parseInt(m.parentMenu.getEl().getStyle("z-index"), 10) + 3);
15439           m.parentMenu.activeChild = m;
15440        }else if(last && last.isVisible()){
15441           m.getEl().setZIndex(parseInt(last.getEl().getStyle("z-index"), 10) + 3);
15442        }
15443    }
15444
15445    // private
15446    function onBeforeHide(m){
15447        if(m.activeChild){
15448            m.activeChild.hide();
15449        }
15450        if(m.autoHideTimer){
15451            clearTimeout(m.autoHideTimer);
15452            delete m.autoHideTimer;
15453        }
15454    }
15455
15456    // private
15457    function onBeforeShow(m){
15458        var pm = m.parentMenu;
15459        if(!pm && !m.allowOtherMenus){
15460            hideAll();
15461        }else if(pm && pm.activeChild && active != m){
15462            pm.activeChild.hide();
15463        }
15464    }
15465
15466    // private
15467    function onMouseDown(e){
15468        if(lastShow.getElapsed() > 50 && active.length > 0 && !e.getTarget(".x-menu")){
15469            hideAll();
15470        }
15471    }
15472
15473    // private
15474    function onBeforeCheck(mi, state){
15475        if(state){
15476            var g = groups[mi.group];
15477            for(var i = 0, l = g.length; i < l; i++){
15478                if(g[i] != mi){
15479                    g[i].setChecked(false);
15480                }
15481            }
15482        }
15483    }
15484
15485    return {
15486
15487        /**
15488         * Hides all menus that are currently visible
15489         */
15490        hideAll : function(){
15491             hideAll();  
15492        },
15493
15494        // private
15495        register : function(menu){
15496            if(!menus){
15497                init();
15498            }
15499            menus[menu.id] = menu;
15500            menu.on("beforehide", onBeforeHide);
15501            menu.on("hide", onHide);
15502            menu.on("beforeshow", onBeforeShow);
15503            menu.on("show", onShow);
15504            var g = menu.group;
15505            if(g && menu.events["checkchange"]){
15506                if(!groups[g]){
15507                    groups[g] = [];
15508                }
15509                groups[g].push(menu);
15510                menu.on("checkchange", onCheck);
15511            }
15512        },
15513
15514         /**
15515          * Returns a {@link Roo.menu.Menu} object
15516          * @param {String/Object} menu The string menu id, an existing menu object reference, or a Menu config that will
15517          * be used to generate and return a new Menu instance.
15518          */
15519        get : function(menu){
15520            if(typeof menu == "string"){ // menu id
15521                return menus[menu];
15522            }else if(menu.events){  // menu instance
15523                return menu;
15524            }else if(typeof menu.length == 'number'){ // array of menu items?
15525                return new Roo.menu.Menu({items:menu});
15526            }else{ // otherwise, must be a config
15527                return new Roo.menu.Menu(menu);
15528            }
15529        },
15530
15531        // private
15532        unregister : function(menu){
15533            delete menus[menu.id];
15534            menu.un("beforehide", onBeforeHide);
15535            menu.un("hide", onHide);
15536            menu.un("beforeshow", onBeforeShow);
15537            menu.un("show", onShow);
15538            var g = menu.group;
15539            if(g && menu.events["checkchange"]){
15540                groups[g].remove(menu);
15541                menu.un("checkchange", onCheck);
15542            }
15543        },
15544
15545        // private
15546        registerCheckable : function(menuItem){
15547            var g = menuItem.group;
15548            if(g){
15549                if(!groups[g]){
15550                    groups[g] = [];
15551                }
15552                groups[g].push(menuItem);
15553                menuItem.on("beforecheckchange", onBeforeCheck);
15554            }
15555        },
15556
15557        // private
15558        unregisterCheckable : function(menuItem){
15559            var g = menuItem.group;
15560            if(g){
15561                groups[g].remove(menuItem);
15562                menuItem.un("beforecheckchange", onBeforeCheck);
15563            }
15564        }
15565    };
15566 }();/*
15567  * Based on:
15568  * Ext JS Library 1.1.1
15569  * Copyright(c) 2006-2007, Ext JS, LLC.
15570  *
15571  * Originally Released Under LGPL - original licence link has changed is not relivant.
15572  *
15573  * Fork - LGPL
15574  * <script type="text/javascript">
15575  */
15576  
15577
15578 /**
15579  * @class Roo.menu.BaseItem
15580  * @extends Roo.Component
15581  * The base class for all items that render into menus.  BaseItem provides default rendering, activated state
15582  * management and base configuration options shared by all menu components.
15583  * @constructor
15584  * Creates a new BaseItem
15585  * @param {Object} config Configuration options
15586  */
15587 Roo.menu.BaseItem = function(config){
15588     Roo.menu.BaseItem.superclass.constructor.call(this, config);
15589
15590     this.addEvents({
15591         /**
15592          * @event click
15593          * Fires when this item is clicked
15594          * @param {Roo.menu.BaseItem} this
15595          * @param {Roo.EventObject} e
15596          */
15597         click: true,
15598         /**
15599          * @event activate
15600          * Fires when this item is activated
15601          * @param {Roo.menu.BaseItem} this
15602          */
15603         activate : true,
15604         /**
15605          * @event deactivate
15606          * Fires when this item is deactivated
15607          * @param {Roo.menu.BaseItem} this
15608          */
15609         deactivate : true
15610     });
15611
15612     if(this.handler){
15613         this.on("click", this.handler, this.scope, true);
15614     }
15615 };
15616
15617 Roo.extend(Roo.menu.BaseItem, Roo.Component, {
15618     /**
15619      * @cfg {Function} handler
15620      * A function that will handle the click event of this menu item (defaults to undefined)
15621      */
15622     /**
15623      * @cfg {Boolean} canActivate True if this item can be visually activated (defaults to false)
15624      */
15625     canActivate : false,
15626     
15627      /**
15628      * @cfg {Boolean} hidden True to prevent creation of this menu item (defaults to false)
15629      */
15630     hidden: false,
15631     
15632     /**
15633      * @cfg {String} activeClass The CSS class to use when the item becomes activated (defaults to "x-menu-item-active")
15634      */
15635     activeClass : "x-menu-item-active",
15636     /**
15637      * @cfg {Boolean} hideOnClick True to hide the containing menu after this item is clicked (defaults to true)
15638      */
15639     hideOnClick : true,
15640     /**
15641      * @cfg {Number} hideDelay Length of time in milliseconds to wait before hiding after a click (defaults to 100)
15642      */
15643     hideDelay : 100,
15644
15645     // private
15646     ctype: "Roo.menu.BaseItem",
15647
15648     // private
15649     actionMode : "container",
15650
15651     // private
15652     render : function(container, parentMenu){
15653         this.parentMenu = parentMenu;
15654         Roo.menu.BaseItem.superclass.render.call(this, container);
15655         this.container.menuItemId = this.id;
15656     },
15657
15658     // private
15659     onRender : function(container, position){
15660         this.el = Roo.get(this.el);
15661         container.dom.appendChild(this.el.dom);
15662     },
15663
15664     // private
15665     onClick : function(e){
15666         if(!this.disabled && this.fireEvent("click", this, e) !== false
15667                 && this.parentMenu.fireEvent("itemclick", this, e) !== false){
15668             this.handleClick(e);
15669         }else{
15670             e.stopEvent();
15671         }
15672     },
15673
15674     // private
15675     activate : function(){
15676         if(this.disabled){
15677             return false;
15678         }
15679         var li = this.container;
15680         li.addClass(this.activeClass);
15681         this.region = li.getRegion().adjust(2, 2, -2, -2);
15682         this.fireEvent("activate", this);
15683         return true;
15684     },
15685
15686     // private
15687     deactivate : function(){
15688         this.container.removeClass(this.activeClass);
15689         this.fireEvent("deactivate", this);
15690     },
15691
15692     // private
15693     shouldDeactivate : function(e){
15694         return !this.region || !this.region.contains(e.getPoint());
15695     },
15696
15697     // private
15698     handleClick : function(e){
15699         if(this.hideOnClick){
15700             this.parentMenu.hide.defer(this.hideDelay, this.parentMenu, [true]);
15701         }
15702     },
15703
15704     // private
15705     expandMenu : function(autoActivate){
15706         // do nothing
15707     },
15708
15709     // private
15710     hideMenu : function(){
15711         // do nothing
15712     }
15713 });/*
15714  * Based on:
15715  * Ext JS Library 1.1.1
15716  * Copyright(c) 2006-2007, Ext JS, LLC.
15717  *
15718  * Originally Released Under LGPL - original licence link has changed is not relivant.
15719  *
15720  * Fork - LGPL
15721  * <script type="text/javascript">
15722  */
15723  
15724 /**
15725  * @class Roo.menu.Adapter
15726  * @extends Roo.menu.BaseItem
15727  * 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.
15728  * It provides basic rendering, activation management and enable/disable logic required to work in menus.
15729  * @constructor
15730  * Creates a new Adapter
15731  * @param {Object} config Configuration options
15732  */
15733 Roo.menu.Adapter = function(component, config){
15734     Roo.menu.Adapter.superclass.constructor.call(this, config);
15735     this.component = component;
15736 };
15737 Roo.extend(Roo.menu.Adapter, Roo.menu.BaseItem, {
15738     // private
15739     canActivate : true,
15740
15741     // private
15742     onRender : function(container, position){
15743         this.component.render(container);
15744         this.el = this.component.getEl();
15745     },
15746
15747     // private
15748     activate : function(){
15749         if(this.disabled){
15750             return false;
15751         }
15752         this.component.focus();
15753         this.fireEvent("activate", this);
15754         return true;
15755     },
15756
15757     // private
15758     deactivate : function(){
15759         this.fireEvent("deactivate", this);
15760     },
15761
15762     // private
15763     disable : function(){
15764         this.component.disable();
15765         Roo.menu.Adapter.superclass.disable.call(this);
15766     },
15767
15768     // private
15769     enable : function(){
15770         this.component.enable();
15771         Roo.menu.Adapter.superclass.enable.call(this);
15772     }
15773 });/*
15774  * Based on:
15775  * Ext JS Library 1.1.1
15776  * Copyright(c) 2006-2007, Ext JS, LLC.
15777  *
15778  * Originally Released Under LGPL - original licence link has changed is not relivant.
15779  *
15780  * Fork - LGPL
15781  * <script type="text/javascript">
15782  */
15783
15784 /**
15785  * @class Roo.menu.TextItem
15786  * @extends Roo.menu.BaseItem
15787  * Adds a static text string to a menu, usually used as either a heading or group separator.
15788  * Note: old style constructor with text is still supported.
15789  * 
15790  * @constructor
15791  * Creates a new TextItem
15792  * @param {Object} cfg Configuration
15793  */
15794 Roo.menu.TextItem = function(cfg){
15795     if (typeof(cfg) == 'string') {
15796         this.text = cfg;
15797     } else {
15798         Roo.apply(this,cfg);
15799     }
15800     
15801     Roo.menu.TextItem.superclass.constructor.call(this);
15802 };
15803
15804 Roo.extend(Roo.menu.TextItem, Roo.menu.BaseItem, {
15805     /**
15806      * @cfg {Boolean} text Text to show on item.
15807      */
15808     text : '',
15809     
15810     /**
15811      * @cfg {Boolean} hideOnClick True to hide the containing menu after this item is clicked (defaults to false)
15812      */
15813     hideOnClick : false,
15814     /**
15815      * @cfg {String} itemCls The default CSS class to use for text items (defaults to "x-menu-text")
15816      */
15817     itemCls : "x-menu-text",
15818
15819     // private
15820     onRender : function(){
15821         var s = document.createElement("span");
15822         s.className = this.itemCls;
15823         s.innerHTML = this.text;
15824         this.el = s;
15825         Roo.menu.TextItem.superclass.onRender.apply(this, arguments);
15826     }
15827 });/*
15828  * Based on:
15829  * Ext JS Library 1.1.1
15830  * Copyright(c) 2006-2007, Ext JS, LLC.
15831  *
15832  * Originally Released Under LGPL - original licence link has changed is not relivant.
15833  *
15834  * Fork - LGPL
15835  * <script type="text/javascript">
15836  */
15837
15838 /**
15839  * @class Roo.menu.Separator
15840  * @extends Roo.menu.BaseItem
15841  * Adds a separator bar to a menu, used to divide logical groups of menu items. Generally you will
15842  * add one of these by using "-" in you call to add() or in your items config rather than creating one directly.
15843  * @constructor
15844  * @param {Object} config Configuration options
15845  */
15846 Roo.menu.Separator = function(config){
15847     Roo.menu.Separator.superclass.constructor.call(this, config);
15848 };
15849
15850 Roo.extend(Roo.menu.Separator, Roo.menu.BaseItem, {
15851     /**
15852      * @cfg {String} itemCls The default CSS class to use for separators (defaults to "x-menu-sep")
15853      */
15854     itemCls : "x-menu-sep",
15855     /**
15856      * @cfg {Boolean} hideOnClick True to hide the containing menu after this item is clicked (defaults to false)
15857      */
15858     hideOnClick : false,
15859
15860     // private
15861     onRender : function(li){
15862         var s = document.createElement("span");
15863         s.className = this.itemCls;
15864         s.innerHTML = "&#160;";
15865         this.el = s;
15866         li.addClass("x-menu-sep-li");
15867         Roo.menu.Separator.superclass.onRender.apply(this, arguments);
15868     }
15869 });/*
15870  * Based on:
15871  * Ext JS Library 1.1.1
15872  * Copyright(c) 2006-2007, Ext JS, LLC.
15873  *
15874  * Originally Released Under LGPL - original licence link has changed is not relivant.
15875  *
15876  * Fork - LGPL
15877  * <script type="text/javascript">
15878  */
15879 /**
15880  * @class Roo.menu.Item
15881  * @extends Roo.menu.BaseItem
15882  * A base class for all menu items that require menu-related functionality (like sub-menus) and are not static
15883  * display items.  Item extends the base functionality of {@link Roo.menu.BaseItem} by adding menu-specific
15884  * activation and click handling.
15885  * @constructor
15886  * Creates a new Item
15887  * @param {Object} config Configuration options
15888  */
15889 Roo.menu.Item = function(config){
15890     Roo.menu.Item.superclass.constructor.call(this, config);
15891     if(this.menu){
15892         this.menu = Roo.menu.MenuMgr.get(this.menu);
15893     }
15894 };
15895 Roo.extend(Roo.menu.Item, Roo.menu.BaseItem, {
15896     
15897     /**
15898      * @cfg {String} text
15899      * The text to show on the menu item.
15900      */
15901     text: '',
15902      /**
15903      * @cfg {String} HTML to render in menu
15904      * The text to show on the menu item (HTML version).
15905      */
15906     html: '',
15907     /**
15908      * @cfg {String} icon
15909      * The path to an icon to display in this menu item (defaults to Roo.BLANK_IMAGE_URL)
15910      */
15911     icon: undefined,
15912     /**
15913      * @cfg {String} itemCls The default CSS class to use for menu items (defaults to "x-menu-item")
15914      */
15915     itemCls : "x-menu-item",
15916     /**
15917      * @cfg {Boolean} canActivate True if this item can be visually activated (defaults to true)
15918      */
15919     canActivate : true,
15920     /**
15921      * @cfg {Number} showDelay Length of time in milliseconds to wait before showing this item (defaults to 200)
15922      */
15923     showDelay: 200,
15924     // doc'd in BaseItem
15925     hideDelay: 200,
15926
15927     // private
15928     ctype: "Roo.menu.Item",
15929     
15930     // private
15931     onRender : function(container, position){
15932         var el = document.createElement("a");
15933         el.hideFocus = true;
15934         el.unselectable = "on";
15935         el.href = this.href || "#";
15936         if(this.hrefTarget){
15937             el.target = this.hrefTarget;
15938         }
15939         el.className = this.itemCls + (this.menu ?  " x-menu-item-arrow" : "") + (this.cls ?  " " + this.cls : "");
15940         
15941         var html = this.html.length ? this.html  : String.format('{0}',this.text);
15942         
15943         el.innerHTML = String.format(
15944                 '<img src="{0}" class="x-menu-item-icon {1}" />' + html,
15945                 this.icon || Roo.BLANK_IMAGE_URL, this.iconCls || '');
15946         this.el = el;
15947         Roo.menu.Item.superclass.onRender.call(this, container, position);
15948     },
15949
15950     /**
15951      * Sets the text to display in this menu item
15952      * @param {String} text The text to display
15953      * @param {Boolean} isHTML true to indicate text is pure html.
15954      */
15955     setText : function(text, isHTML){
15956         if (isHTML) {
15957             this.html = text;
15958         } else {
15959             this.text = text;
15960             this.html = '';
15961         }
15962         if(this.rendered){
15963             var html = this.html.length ? this.html  : String.format('{0}',this.text);
15964      
15965             this.el.update(String.format(
15966                 '<img src="{0}" class="x-menu-item-icon {2}">' + html,
15967                 this.icon || Roo.BLANK_IMAGE_URL, this.text, this.iconCls || ''));
15968             this.parentMenu.autoWidth();
15969         }
15970     },
15971
15972     // private
15973     handleClick : function(e){
15974         if(!this.href){ // if no link defined, stop the event automatically
15975             e.stopEvent();
15976         }
15977         Roo.menu.Item.superclass.handleClick.apply(this, arguments);
15978     },
15979
15980     // private
15981     activate : function(autoExpand){
15982         if(Roo.menu.Item.superclass.activate.apply(this, arguments)){
15983             this.focus();
15984             if(autoExpand){
15985                 this.expandMenu();
15986             }
15987         }
15988         return true;
15989     },
15990
15991     // private
15992     shouldDeactivate : function(e){
15993         if(Roo.menu.Item.superclass.shouldDeactivate.call(this, e)){
15994             if(this.menu && this.menu.isVisible()){
15995                 return !this.menu.getEl().getRegion().contains(e.getPoint());
15996             }
15997             return true;
15998         }
15999         return false;
16000     },
16001
16002     // private
16003     deactivate : function(){
16004         Roo.menu.Item.superclass.deactivate.apply(this, arguments);
16005         this.hideMenu();
16006     },
16007
16008     // private
16009     expandMenu : function(autoActivate){
16010         if(!this.disabled && this.menu){
16011             clearTimeout(this.hideTimer);
16012             delete this.hideTimer;
16013             if(!this.menu.isVisible() && !this.showTimer){
16014                 this.showTimer = this.deferExpand.defer(this.showDelay, this, [autoActivate]);
16015             }else if (this.menu.isVisible() && autoActivate){
16016                 this.menu.tryActivate(0, 1);
16017             }
16018         }
16019     },
16020
16021     // private
16022     deferExpand : function(autoActivate){
16023         delete this.showTimer;
16024         this.menu.show(this.container, this.parentMenu.subMenuAlign || "tl-tr?", this.parentMenu);
16025         if(autoActivate){
16026             this.menu.tryActivate(0, 1);
16027         }
16028     },
16029
16030     // private
16031     hideMenu : function(){
16032         clearTimeout(this.showTimer);
16033         delete this.showTimer;
16034         if(!this.hideTimer && this.menu && this.menu.isVisible()){
16035             this.hideTimer = this.deferHide.defer(this.hideDelay, this);
16036         }
16037     },
16038
16039     // private
16040     deferHide : function(){
16041         delete this.hideTimer;
16042         this.menu.hide();
16043     }
16044 });/*
16045  * Based on:
16046  * Ext JS Library 1.1.1
16047  * Copyright(c) 2006-2007, Ext JS, LLC.
16048  *
16049  * Originally Released Under LGPL - original licence link has changed is not relivant.
16050  *
16051  * Fork - LGPL
16052  * <script type="text/javascript">
16053  */
16054  
16055 /**
16056  * @class Roo.menu.CheckItem
16057  * @extends Roo.menu.Item
16058  * Adds a menu item that contains a checkbox by default, but can also be part of a radio group.
16059  * @constructor
16060  * Creates a new CheckItem
16061  * @param {Object} config Configuration options
16062  */
16063 Roo.menu.CheckItem = function(config){
16064     Roo.menu.CheckItem.superclass.constructor.call(this, config);
16065     this.addEvents({
16066         /**
16067          * @event beforecheckchange
16068          * Fires before the checked value is set, providing an opportunity to cancel if needed
16069          * @param {Roo.menu.CheckItem} this
16070          * @param {Boolean} checked The new checked value that will be set
16071          */
16072         "beforecheckchange" : true,
16073         /**
16074          * @event checkchange
16075          * Fires after the checked value has been set
16076          * @param {Roo.menu.CheckItem} this
16077          * @param {Boolean} checked The checked value that was set
16078          */
16079         "checkchange" : true
16080     });
16081     if(this.checkHandler){
16082         this.on('checkchange', this.checkHandler, this.scope);
16083     }
16084 };
16085 Roo.extend(Roo.menu.CheckItem, Roo.menu.Item, {
16086     /**
16087      * @cfg {String} group
16088      * All check items with the same group name will automatically be grouped into a single-select
16089      * radio button group (defaults to '')
16090      */
16091     /**
16092      * @cfg {String} itemCls The default CSS class to use for check items (defaults to "x-menu-item x-menu-check-item")
16093      */
16094     itemCls : "x-menu-item x-menu-check-item",
16095     /**
16096      * @cfg {String} groupClass The default CSS class to use for radio group check items (defaults to "x-menu-group-item")
16097      */
16098     groupClass : "x-menu-group-item",
16099
16100     /**
16101      * @cfg {Boolean} checked True to initialize this checkbox as checked (defaults to false).  Note that
16102      * if this checkbox is part of a radio group (group = true) only the last item in the group that is
16103      * initialized with checked = true will be rendered as checked.
16104      */
16105     checked: false,
16106
16107     // private
16108     ctype: "Roo.menu.CheckItem",
16109
16110     // private
16111     onRender : function(c){
16112         Roo.menu.CheckItem.superclass.onRender.apply(this, arguments);
16113         if(this.group){
16114             this.el.addClass(this.groupClass);
16115         }
16116         Roo.menu.MenuMgr.registerCheckable(this);
16117         if(this.checked){
16118             this.checked = false;
16119             this.setChecked(true, true);
16120         }
16121     },
16122
16123     // private
16124     destroy : function(){
16125         if(this.rendered){
16126             Roo.menu.MenuMgr.unregisterCheckable(this);
16127         }
16128         Roo.menu.CheckItem.superclass.destroy.apply(this, arguments);
16129     },
16130
16131     /**
16132      * Set the checked state of this item
16133      * @param {Boolean} checked The new checked value
16134      * @param {Boolean} suppressEvent (optional) True to prevent the checkchange event from firing (defaults to false)
16135      */
16136     setChecked : function(state, suppressEvent){
16137         if(this.checked != state && this.fireEvent("beforecheckchange", this, state) !== false){
16138             if(this.container){
16139                 this.container[state ? "addClass" : "removeClass"]("x-menu-item-checked");
16140             }
16141             this.checked = state;
16142             if(suppressEvent !== true){
16143                 this.fireEvent("checkchange", this, state);
16144             }
16145         }
16146     },
16147
16148     // private
16149     handleClick : function(e){
16150        if(!this.disabled && !(this.checked && this.group)){// disable unselect on radio item
16151            this.setChecked(!this.checked);
16152        }
16153        Roo.menu.CheckItem.superclass.handleClick.apply(this, arguments);
16154     }
16155 });/*
16156  * Based on:
16157  * Ext JS Library 1.1.1
16158  * Copyright(c) 2006-2007, Ext JS, LLC.
16159  *
16160  * Originally Released Under LGPL - original licence link has changed is not relivant.
16161  *
16162  * Fork - LGPL
16163  * <script type="text/javascript">
16164  */
16165  
16166 /**
16167  * @class Roo.menu.DateItem
16168  * @extends Roo.menu.Adapter
16169  * A menu item that wraps the {@link Roo.DatPicker} component.
16170  * @constructor
16171  * Creates a new DateItem
16172  * @param {Object} config Configuration options
16173  */
16174 Roo.menu.DateItem = function(config){
16175     Roo.menu.DateItem.superclass.constructor.call(this, new Roo.DatePicker(config), config);
16176     /** The Roo.DatePicker object @type Roo.DatePicker */
16177     this.picker = this.component;
16178     this.addEvents({select: true});
16179     
16180     this.picker.on("render", function(picker){
16181         picker.getEl().swallowEvent("click");
16182         picker.container.addClass("x-menu-date-item");
16183     });
16184
16185     this.picker.on("select", this.onSelect, this);
16186 };
16187
16188 Roo.extend(Roo.menu.DateItem, Roo.menu.Adapter, {
16189     // private
16190     onSelect : function(picker, date){
16191         this.fireEvent("select", this, date, picker);
16192         Roo.menu.DateItem.superclass.handleClick.call(this);
16193     }
16194 });/*
16195  * Based on:
16196  * Ext JS Library 1.1.1
16197  * Copyright(c) 2006-2007, Ext JS, LLC.
16198  *
16199  * Originally Released Under LGPL - original licence link has changed is not relivant.
16200  *
16201  * Fork - LGPL
16202  * <script type="text/javascript">
16203  */
16204  
16205 /**
16206  * @class Roo.menu.ColorItem
16207  * @extends Roo.menu.Adapter
16208  * A menu item that wraps the {@link Roo.ColorPalette} component.
16209  * @constructor
16210  * Creates a new ColorItem
16211  * @param {Object} config Configuration options
16212  */
16213 Roo.menu.ColorItem = function(config){
16214     Roo.menu.ColorItem.superclass.constructor.call(this, new Roo.ColorPalette(config), config);
16215     /** The Roo.ColorPalette object @type Roo.ColorPalette */
16216     this.palette = this.component;
16217     this.relayEvents(this.palette, ["select"]);
16218     if(this.selectHandler){
16219         this.on('select', this.selectHandler, this.scope);
16220     }
16221 };
16222 Roo.extend(Roo.menu.ColorItem, Roo.menu.Adapter);/*
16223  * Based on:
16224  * Ext JS Library 1.1.1
16225  * Copyright(c) 2006-2007, Ext JS, LLC.
16226  *
16227  * Originally Released Under LGPL - original licence link has changed is not relivant.
16228  *
16229  * Fork - LGPL
16230  * <script type="text/javascript">
16231  */
16232  
16233
16234 /**
16235  * @class Roo.menu.DateMenu
16236  * @extends Roo.menu.Menu
16237  * A menu containing a {@link Roo.menu.DateItem} component (which provides a date picker).
16238  * @constructor
16239  * Creates a new DateMenu
16240  * @param {Object} config Configuration options
16241  */
16242 Roo.menu.DateMenu = function(config){
16243     Roo.menu.DateMenu.superclass.constructor.call(this, config);
16244     this.plain = true;
16245     var di = new Roo.menu.DateItem(config);
16246     this.add(di);
16247     /**
16248      * The {@link Roo.DatePicker} instance for this DateMenu
16249      * @type DatePicker
16250      */
16251     this.picker = di.picker;
16252     /**
16253      * @event select
16254      * @param {DatePicker} picker
16255      * @param {Date} date
16256      */
16257     this.relayEvents(di, ["select"]);
16258     this.on('beforeshow', function(){
16259         if(this.picker){
16260             this.picker.hideMonthPicker(false);
16261         }
16262     }, this);
16263 };
16264 Roo.extend(Roo.menu.DateMenu, Roo.menu.Menu, {
16265     cls:'x-date-menu'
16266 });/*
16267  * Based on:
16268  * Ext JS Library 1.1.1
16269  * Copyright(c) 2006-2007, Ext JS, LLC.
16270  *
16271  * Originally Released Under LGPL - original licence link has changed is not relivant.
16272  *
16273  * Fork - LGPL
16274  * <script type="text/javascript">
16275  */
16276  
16277
16278 /**
16279  * @class Roo.menu.ColorMenu
16280  * @extends Roo.menu.Menu
16281  * A menu containing a {@link Roo.menu.ColorItem} component (which provides a basic color picker).
16282  * @constructor
16283  * Creates a new ColorMenu
16284  * @param {Object} config Configuration options
16285  */
16286 Roo.menu.ColorMenu = function(config){
16287     Roo.menu.ColorMenu.superclass.constructor.call(this, config);
16288     this.plain = true;
16289     var ci = new Roo.menu.ColorItem(config);
16290     this.add(ci);
16291     /**
16292      * The {@link Roo.ColorPalette} instance for this ColorMenu
16293      * @type ColorPalette
16294      */
16295     this.palette = ci.palette;
16296     /**
16297      * @event select
16298      * @param {ColorPalette} palette
16299      * @param {String} color
16300      */
16301     this.relayEvents(ci, ["select"]);
16302 };
16303 Roo.extend(Roo.menu.ColorMenu, Roo.menu.Menu);/*
16304  * Based on:
16305  * Ext JS Library 1.1.1
16306  * Copyright(c) 2006-2007, Ext JS, LLC.
16307  *
16308  * Originally Released Under LGPL - original licence link has changed is not relivant.
16309  *
16310  * Fork - LGPL
16311  * <script type="text/javascript">
16312  */
16313  
16314 /**
16315  * @class Roo.form.TextItem
16316  * @extends Roo.BoxComponent
16317  * Base class for form fields that provides default event handling, sizing, value handling and other functionality.
16318  * @constructor
16319  * Creates a new TextItem
16320  * @param {Object} config Configuration options
16321  */
16322 Roo.form.TextItem = function(config){
16323     Roo.form.TextItem.superclass.constructor.call(this, config);
16324 };
16325
16326 Roo.extend(Roo.form.TextItem, Roo.BoxComponent,  {
16327     
16328     /**
16329      * @cfg {String} tag the tag for this item (default div)
16330      */
16331     tag : 'div',
16332     /**
16333      * @cfg {String} html the content for this item
16334      */
16335     html : '',
16336     
16337     getAutoCreate : function()
16338     {
16339         var cfg = {
16340             id: this.id,
16341             tag: this.tag,
16342             html: this.html,
16343             cls: 'x-form-item'
16344         };
16345         
16346         return cfg;
16347         
16348     },
16349     
16350     onRender : function(ct, position)
16351     {
16352         Roo.form.TextItem.superclass.onRender.call(this, ct, position);
16353         
16354         if(!this.el){
16355             var cfg = this.getAutoCreate();
16356             if(!cfg.name){
16357                 cfg.name = typeof(this.name) == 'undefined' ? this.id : this.name;
16358             }
16359             if (!cfg.name.length) {
16360                 delete cfg.name;
16361             }
16362             this.el = ct.createChild(cfg, position);
16363         }
16364     }
16365     
16366 });/*
16367  * Based on:
16368  * Ext JS Library 1.1.1
16369  * Copyright(c) 2006-2007, Ext JS, LLC.
16370  *
16371  * Originally Released Under LGPL - original licence link has changed is not relivant.
16372  *
16373  * Fork - LGPL
16374  * <script type="text/javascript">
16375  */
16376  
16377 /**
16378  * @class Roo.form.Field
16379  * @extends Roo.BoxComponent
16380  * Base class for form fields that provides default event handling, sizing, value handling and other functionality.
16381  * @constructor
16382  * Creates a new Field
16383  * @param {Object} config Configuration options
16384  */
16385 Roo.form.Field = function(config){
16386     Roo.form.Field.superclass.constructor.call(this, config);
16387 };
16388
16389 Roo.extend(Roo.form.Field, Roo.BoxComponent,  {
16390     /**
16391      * @cfg {String} fieldLabel Label to use when rendering a form.
16392      */
16393        /**
16394      * @cfg {String} qtip Mouse over tip
16395      */
16396      
16397     /**
16398      * @cfg {String} invalidClass The CSS class to use when marking a field invalid (defaults to "x-form-invalid")
16399      */
16400     invalidClass : "x-form-invalid",
16401     /**
16402      * @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")
16403      */
16404     invalidText : "The value in this field is invalid",
16405     /**
16406      * @cfg {String} focusClass The CSS class to use when the field receives focus (defaults to "x-form-focus")
16407      */
16408     focusClass : "x-form-focus",
16409     /**
16410      * @cfg {String/Boolean} validationEvent The event that should initiate field validation. Set to false to disable
16411       automatic validation (defaults to "keyup").
16412      */
16413     validationEvent : "keyup",
16414     /**
16415      * @cfg {Boolean} validateOnBlur Whether the field should validate when it loses focus (defaults to true).
16416      */
16417     validateOnBlur : true,
16418     /**
16419      * @cfg {Number} validationDelay The length of time in milliseconds after user input begins until validation is initiated (defaults to 250)
16420      */
16421     validationDelay : 250,
16422     /**
16423      * @cfg {String/Object} autoCreate A DomHelper element spec, or true for a default element spec (defaults to
16424      * {tag: "input", type: "text", size: "20", autocomplete: "off"})
16425      */
16426     defaultAutoCreate : {tag: "input", type: "text", size: "20", autocomplete: "new-password"},
16427     /**
16428      * @cfg {String} fieldClass The default CSS class for the field (defaults to "x-form-field")
16429      */
16430     fieldClass : "x-form-field",
16431     /**
16432      * @cfg {String} msgTarget The location where error text should display.  Should be one of the following values (defaults to 'qtip'):
16433      *<pre>
16434 Value         Description
16435 -----------   ----------------------------------------------------------------------
16436 qtip          Display a quick tip when the user hovers over the field
16437 title         Display a default browser title attribute popup
16438 under         Add a block div beneath the field containing the error text
16439 side          Add an error icon to the right of the field with a popup on hover
16440 [element id]  Add the error text directly to the innerHTML of the specified element
16441 </pre>
16442      */
16443     msgTarget : 'qtip',
16444     /**
16445      * @cfg {String} msgFx <b>Experimental</b> The effect used when displaying a validation message under the field (defaults to 'normal').
16446      */
16447     msgFx : 'normal',
16448
16449     /**
16450      * @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.
16451      */
16452     readOnly : false,
16453
16454     /**
16455      * @cfg {Boolean} disabled True to disable the field (defaults to false).
16456      */
16457     disabled : false,
16458
16459     /**
16460      * @cfg {String} inputType The type attribute for input fields -- e.g. radio, text, password (defaults to "text").
16461      */
16462     inputType : undefined,
16463     
16464     /**
16465      * @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).
16466          */
16467         tabIndex : undefined,
16468         
16469     // private
16470     isFormField : true,
16471
16472     // private
16473     hasFocus : false,
16474     /**
16475      * @property {Roo.Element} fieldEl
16476      * Element Containing the rendered Field (with label etc.)
16477      */
16478     /**
16479      * @cfg {Mixed} value A value to initialize this field with.
16480      */
16481     value : undefined,
16482
16483     /**
16484      * @cfg {String} name The field's HTML name attribute.
16485      */
16486     /**
16487      * @cfg {String} cls A CSS class to apply to the field's underlying element.
16488      */
16489     // private
16490     loadedValue : false,
16491      
16492      
16493         // private ??
16494         initComponent : function(){
16495         Roo.form.Field.superclass.initComponent.call(this);
16496         this.addEvents({
16497             /**
16498              * @event focus
16499              * Fires when this field receives input focus.
16500              * @param {Roo.form.Field} this
16501              */
16502             focus : true,
16503             /**
16504              * @event blur
16505              * Fires when this field loses input focus.
16506              * @param {Roo.form.Field} this
16507              */
16508             blur : true,
16509             /**
16510              * @event specialkey
16511              * Fires when any key related to navigation (arrows, tab, enter, esc, etc.) is pressed.  You can check
16512              * {@link Roo.EventObject#getKey} to determine which key was pressed.
16513              * @param {Roo.form.Field} this
16514              * @param {Roo.EventObject} e The event object
16515              */
16516             specialkey : true,
16517             /**
16518              * @event change
16519              * Fires just before the field blurs if the field value has changed.
16520              * @param {Roo.form.Field} this
16521              * @param {Mixed} newValue The new value
16522              * @param {Mixed} oldValue The original value
16523              */
16524             change : true,
16525             /**
16526              * @event invalid
16527              * Fires after the field has been marked as invalid.
16528              * @param {Roo.form.Field} this
16529              * @param {String} msg The validation message
16530              */
16531             invalid : true,
16532             /**
16533              * @event valid
16534              * Fires after the field has been validated with no errors.
16535              * @param {Roo.form.Field} this
16536              */
16537             valid : true,
16538              /**
16539              * @event keyup
16540              * Fires after the key up
16541              * @param {Roo.form.Field} this
16542              * @param {Roo.EventObject}  e The event Object
16543              */
16544             keyup : true
16545         });
16546     },
16547
16548     /**
16549      * Returns the name attribute of the field if available
16550      * @return {String} name The field name
16551      */
16552     getName: function(){
16553          return this.rendered && this.el.dom.name ? this.el.dom.name : (this.hiddenName || '');
16554     },
16555
16556     // private
16557     onRender : function(ct, position){
16558         Roo.form.Field.superclass.onRender.call(this, ct, position);
16559         if(!this.el){
16560             var cfg = this.getAutoCreate();
16561             if(!cfg.name){
16562                 cfg.name = typeof(this.name) == 'undefined' ? this.id : this.name;
16563             }
16564             if (!cfg.name.length) {
16565                 delete cfg.name;
16566             }
16567             if(this.inputType){
16568                 cfg.type = this.inputType;
16569             }
16570             this.el = ct.createChild(cfg, position);
16571         }
16572         var type = this.el.dom.type;
16573         if(type){
16574             if(type == 'password'){
16575                 type = 'text';
16576             }
16577             this.el.addClass('x-form-'+type);
16578         }
16579         if(this.readOnly){
16580             this.el.dom.readOnly = true;
16581         }
16582         if(this.tabIndex !== undefined){
16583             this.el.dom.setAttribute('tabIndex', this.tabIndex);
16584         }
16585
16586         this.el.addClass([this.fieldClass, this.cls]);
16587         this.initValue();
16588     },
16589
16590     /**
16591      * Apply the behaviors of this component to an existing element. <b>This is used instead of render().</b>
16592      * @param {String/HTMLElement/Element} el The id of the node, a DOM node or an existing Element
16593      * @return {Roo.form.Field} this
16594      */
16595     applyTo : function(target){
16596         this.allowDomMove = false;
16597         this.el = Roo.get(target);
16598         this.render(this.el.dom.parentNode);
16599         return this;
16600     },
16601
16602     // private
16603     initValue : function(){
16604         if(this.value !== undefined){
16605             this.setValue(this.value);
16606         }else if(this.el.dom.value.length > 0){
16607             this.setValue(this.el.dom.value);
16608         }
16609     },
16610
16611     /**
16612      * Returns true if this field has been changed since it was originally loaded and is not disabled.
16613      * DEPRICATED  - it never worked well - use hasChanged/resetHasChanged.
16614      */
16615     isDirty : function() {
16616         if(this.disabled) {
16617             return false;
16618         }
16619         return String(this.getValue()) !== String(this.originalValue);
16620     },
16621
16622     /**
16623      * stores the current value in loadedValue
16624      */
16625     resetHasChanged : function()
16626     {
16627         this.loadedValue = String(this.getValue());
16628     },
16629     /**
16630      * checks the current value against the 'loaded' value.
16631      * Note - will return false if 'resetHasChanged' has not been called first.
16632      */
16633     hasChanged : function()
16634     {
16635         if(this.disabled || this.readOnly) {
16636             return false;
16637         }
16638         return this.loadedValue !== false && String(this.getValue()) !== this.loadedValue;
16639     },
16640     
16641     
16642     
16643     // private
16644     afterRender : function(){
16645         Roo.form.Field.superclass.afterRender.call(this);
16646         this.initEvents();
16647     },
16648
16649     // private
16650     fireKey : function(e){
16651         //Roo.log('field ' + e.getKey());
16652         if(e.isNavKeyPress()){
16653             this.fireEvent("specialkey", this, e);
16654         }
16655     },
16656
16657     /**
16658      * Resets the current field value to the originally loaded value and clears any validation messages
16659      */
16660     reset : function(){
16661         this.setValue(this.resetValue);
16662         this.originalValue = this.getValue();
16663         this.clearInvalid();
16664     },
16665
16666     // private
16667     initEvents : function(){
16668         // safari killled keypress - so keydown is now used..
16669         this.el.on("keydown" , this.fireKey,  this);
16670         this.el.on("focus", this.onFocus,  this);
16671         this.el.on("blur", this.onBlur,  this);
16672         this.el.relayEvent('keyup', this);
16673
16674         // reference to original value for reset
16675         this.originalValue = this.getValue();
16676         this.resetValue =  this.getValue();
16677     },
16678
16679     // private
16680     onFocus : function(){
16681         if(!Roo.isOpera && this.focusClass){ // don't touch in Opera
16682             this.el.addClass(this.focusClass);
16683         }
16684         if(!this.hasFocus){
16685             this.hasFocus = true;
16686             this.startValue = this.getValue();
16687             this.fireEvent("focus", this);
16688         }
16689     },
16690
16691     beforeBlur : Roo.emptyFn,
16692
16693     // private
16694     onBlur : function(){
16695         this.beforeBlur();
16696         if(!Roo.isOpera && this.focusClass){ // don't touch in Opera
16697             this.el.removeClass(this.focusClass);
16698         }
16699         this.hasFocus = false;
16700         if(this.validationEvent !== false && this.validateOnBlur && this.validationEvent != "blur"){
16701             this.validate();
16702         }
16703         var v = this.getValue();
16704         if(String(v) !== String(this.startValue)){
16705             this.fireEvent('change', this, v, this.startValue);
16706         }
16707         this.fireEvent("blur", this);
16708     },
16709
16710     /**
16711      * Returns whether or not the field value is currently valid
16712      * @param {Boolean} preventMark True to disable marking the field invalid
16713      * @return {Boolean} True if the value is valid, else false
16714      */
16715     isValid : function(preventMark){
16716         if(this.disabled){
16717             return true;
16718         }
16719         var restore = this.preventMark;
16720         this.preventMark = preventMark === true;
16721         var v = this.validateValue(this.processValue(this.getRawValue()));
16722         this.preventMark = restore;
16723         return v;
16724     },
16725
16726     /**
16727      * Validates the field value
16728      * @return {Boolean} True if the value is valid, else false
16729      */
16730     validate : function(){
16731         if(this.disabled || this.validateValue(this.processValue(this.getRawValue()))){
16732             this.clearInvalid();
16733             return true;
16734         }
16735         return false;
16736     },
16737
16738     processValue : function(value){
16739         return value;
16740     },
16741
16742     // private
16743     // Subclasses should provide the validation implementation by overriding this
16744     validateValue : function(value){
16745         return true;
16746     },
16747
16748     /**
16749      * Mark this field as invalid
16750      * @param {String} msg The validation message
16751      */
16752     markInvalid : function(msg){
16753         if(!this.rendered || this.preventMark){ // not rendered
16754             return;
16755         }
16756         
16757         var obj = (typeof(this.combo) != 'undefined') ? this.combo : this; // fix the combox array!!
16758         
16759         obj.el.addClass(this.invalidClass);
16760         msg = msg || this.invalidText;
16761         switch(this.msgTarget){
16762             case 'qtip':
16763                 obj.el.dom.qtip = msg;
16764                 obj.el.dom.qclass = 'x-form-invalid-tip';
16765                 if(Roo.QuickTips){ // fix for floating editors interacting with DND
16766                     Roo.QuickTips.enable();
16767                 }
16768                 break;
16769             case 'title':
16770                 this.el.dom.title = msg;
16771                 break;
16772             case 'under':
16773                 if(!this.errorEl){
16774                     var elp = this.el.findParent('.x-form-element', 5, true);
16775                     this.errorEl = elp.createChild({cls:'x-form-invalid-msg'});
16776                     this.errorEl.setWidth(elp.getWidth(true)-20);
16777                 }
16778                 this.errorEl.update(msg);
16779                 Roo.form.Field.msgFx[this.msgFx].show(this.errorEl, this);
16780                 break;
16781             case 'side':
16782                 if(!this.errorIcon){
16783                     var elp = this.el.findParent('.x-form-element', 5, true);
16784                     this.errorIcon = elp.createChild({cls:'x-form-invalid-icon'});
16785                 }
16786                 this.alignErrorIcon();
16787                 this.errorIcon.dom.qtip = msg;
16788                 this.errorIcon.dom.qclass = 'x-form-invalid-tip';
16789                 this.errorIcon.show();
16790                 this.on('resize', this.alignErrorIcon, this);
16791                 break;
16792             default:
16793                 var t = Roo.getDom(this.msgTarget);
16794                 t.innerHTML = msg;
16795                 t.style.display = this.msgDisplay;
16796                 break;
16797         }
16798         this.fireEvent('invalid', this, msg);
16799     },
16800
16801     // private
16802     alignErrorIcon : function(){
16803         this.errorIcon.alignTo(this.el, 'tl-tr', [2, 0]);
16804     },
16805
16806     /**
16807      * Clear any invalid styles/messages for this field
16808      */
16809     clearInvalid : function(){
16810         if(!this.rendered || this.preventMark){ // not rendered
16811             return;
16812         }
16813         var obj = (typeof(this.combo) != 'undefined') ? this.combo : this; // fix the combox array!!
16814         
16815         obj.el.removeClass(this.invalidClass);
16816         switch(this.msgTarget){
16817             case 'qtip':
16818                 obj.el.dom.qtip = '';
16819                 break;
16820             case 'title':
16821                 this.el.dom.title = '';
16822                 break;
16823             case 'under':
16824                 if(this.errorEl){
16825                     Roo.form.Field.msgFx[this.msgFx].hide(this.errorEl, this);
16826                 }
16827                 break;
16828             case 'side':
16829                 if(this.errorIcon){
16830                     this.errorIcon.dom.qtip = '';
16831                     this.errorIcon.hide();
16832                     this.un('resize', this.alignErrorIcon, this);
16833                 }
16834                 break;
16835             default:
16836                 var t = Roo.getDom(this.msgTarget);
16837                 t.innerHTML = '';
16838                 t.style.display = 'none';
16839                 break;
16840         }
16841         this.fireEvent('valid', this);
16842     },
16843
16844     /**
16845      * Returns the raw data value which may or may not be a valid, defined value.  To return a normalized value see {@link #getValue}.
16846      * @return {Mixed} value The field value
16847      */
16848     getRawValue : function(){
16849         var v = this.el.getValue();
16850         
16851         return v;
16852     },
16853
16854     /**
16855      * Returns the normalized data value (undefined or emptyText will be returned as '').  To return the raw value see {@link #getRawValue}.
16856      * @return {Mixed} value The field value
16857      */
16858     getValue : function(){
16859         var v = this.el.getValue();
16860          
16861         return v;
16862     },
16863
16864     /**
16865      * Sets the underlying DOM field's value directly, bypassing validation.  To set the value with validation see {@link #setValue}.
16866      * @param {Mixed} value The value to set
16867      */
16868     setRawValue : function(v){
16869         return this.el.dom.value = (v === null || v === undefined ? '' : v);
16870     },
16871
16872     /**
16873      * Sets a data value into the field and validates it.  To set the value directly without validation see {@link #setRawValue}.
16874      * @param {Mixed} value The value to set
16875      */
16876     setValue : function(v){
16877         this.value = v;
16878         if(this.rendered){
16879             this.el.dom.value = (v === null || v === undefined ? '' : v);
16880              this.validate();
16881         }
16882     },
16883
16884     adjustSize : function(w, h){
16885         var s = Roo.form.Field.superclass.adjustSize.call(this, w, h);
16886         s.width = this.adjustWidth(this.el.dom.tagName, s.width);
16887         return s;
16888     },
16889
16890     adjustWidth : function(tag, w){
16891         tag = tag.toLowerCase();
16892         if(typeof w == 'number' && Roo.isStrict && !Roo.isSafari){
16893             if(Roo.isIE && (tag == 'input' || tag == 'textarea')){
16894                 if(tag == 'input'){
16895                     return w + 2;
16896                 }
16897                 if(tag == 'textarea'){
16898                     return w-2;
16899                 }
16900             }else if(Roo.isOpera){
16901                 if(tag == 'input'){
16902                     return w + 2;
16903                 }
16904                 if(tag == 'textarea'){
16905                     return w-2;
16906                 }
16907             }
16908         }
16909         return w;
16910     }
16911 });
16912
16913
16914 // anything other than normal should be considered experimental
16915 Roo.form.Field.msgFx = {
16916     normal : {
16917         show: function(msgEl, f){
16918             msgEl.setDisplayed('block');
16919         },
16920
16921         hide : function(msgEl, f){
16922             msgEl.setDisplayed(false).update('');
16923         }
16924     },
16925
16926     slide : {
16927         show: function(msgEl, f){
16928             msgEl.slideIn('t', {stopFx:true});
16929         },
16930
16931         hide : function(msgEl, f){
16932             msgEl.slideOut('t', {stopFx:true,useDisplay:true});
16933         }
16934     },
16935
16936     slideRight : {
16937         show: function(msgEl, f){
16938             msgEl.fixDisplay();
16939             msgEl.alignTo(f.el, 'tl-tr');
16940             msgEl.slideIn('l', {stopFx:true});
16941         },
16942
16943         hide : function(msgEl, f){
16944             msgEl.slideOut('l', {stopFx:true,useDisplay:true});
16945         }
16946     }
16947 };/*
16948  * Based on:
16949  * Ext JS Library 1.1.1
16950  * Copyright(c) 2006-2007, Ext JS, LLC.
16951  *
16952  * Originally Released Under LGPL - original licence link has changed is not relivant.
16953  *
16954  * Fork - LGPL
16955  * <script type="text/javascript">
16956  */
16957  
16958
16959 /**
16960  * @class Roo.form.TextField
16961  * @extends Roo.form.Field
16962  * Basic text field.  Can be used as a direct replacement for traditional text inputs, or as the base
16963  * class for more sophisticated input controls (like {@link Roo.form.TextArea} and {@link Roo.form.ComboBox}).
16964  * @constructor
16965  * Creates a new TextField
16966  * @param {Object} config Configuration options
16967  */
16968 Roo.form.TextField = function(config){
16969     Roo.form.TextField.superclass.constructor.call(this, config);
16970     this.addEvents({
16971         /**
16972          * @event autosize
16973          * Fires when the autosize function is triggered.  The field may or may not have actually changed size
16974          * according to the default logic, but this event provides a hook for the developer to apply additional
16975          * logic at runtime to resize the field if needed.
16976              * @param {Roo.form.Field} this This text field
16977              * @param {Number} width The new field width
16978              */
16979         autosize : true
16980     });
16981 };
16982
16983 Roo.extend(Roo.form.TextField, Roo.form.Field,  {
16984     /**
16985      * @cfg {Boolean} grow True if this field should automatically grow and shrink to its content
16986      */
16987     grow : false,
16988     /**
16989      * @cfg {Number} growMin The minimum width to allow when grow = true (defaults to 30)
16990      */
16991     growMin : 30,
16992     /**
16993      * @cfg {Number} growMax The maximum width to allow when grow = true (defaults to 800)
16994      */
16995     growMax : 800,
16996     /**
16997      * @cfg {String} vtype A validation type name as defined in {@link Roo.form.VTypes} (defaults to null)
16998      */
16999     vtype : null,
17000     /**
17001      * @cfg {String} maskRe An input mask regular expression that will be used to filter keystrokes that don't match (defaults to null)
17002      */
17003     maskRe : null,
17004     /**
17005      * @cfg {Boolean} disableKeyFilter True to disable input keystroke filtering (defaults to false)
17006      */
17007     disableKeyFilter : false,
17008     /**
17009      * @cfg {Boolean} allowBlank False to validate that the value length > 0 (defaults to true)
17010      */
17011     allowBlank : true,
17012     /**
17013      * @cfg {Number} minLength Minimum input field length required (defaults to 0)
17014      */
17015     minLength : 0,
17016     /**
17017      * @cfg {Number} maxLength Maximum input field length allowed (defaults to Number.MAX_VALUE)
17018      */
17019     maxLength : Number.MAX_VALUE,
17020     /**
17021      * @cfg {String} minLengthText Error text to display if the minimum length validation fails (defaults to "The minimum length for this field is {minLength}")
17022      */
17023     minLengthText : "The minimum length for this field is {0}",
17024     /**
17025      * @cfg {String} maxLengthText Error text to display if the maximum length validation fails (defaults to "The maximum length for this field is {maxLength}")
17026      */
17027     maxLengthText : "The maximum length for this field is {0}",
17028     /**
17029      * @cfg {Boolean} selectOnFocus True to automatically select any existing field text when the field receives input focus (defaults to false)
17030      */
17031     selectOnFocus : false,
17032     /**
17033      * @cfg {Boolean} allowLeadingSpace True to prevent the stripping of leading white space 
17034      */    
17035     allowLeadingSpace : false,
17036     /**
17037      * @cfg {String} blankText Error text to display if the allow blank validation fails (defaults to "This field is required")
17038      */
17039     blankText : "This field is required",
17040     /**
17041      * @cfg {Function} validator A custom validation function to be called during field validation (defaults to null).
17042      * If available, this function will be called only after the basic validators all return true, and will be passed the
17043      * current field value and expected to return boolean true if the value is valid or a string error message if invalid.
17044      */
17045     validator : null,
17046     /**
17047      * @cfg {RegExp} regex A JavaScript RegExp object to be tested against the field value during validation (defaults to null).
17048      * If available, this regex will be evaluated only after the basic validators all return true, and will be passed the
17049      * current field value.  If the test fails, the field will be marked invalid using {@link #regexText}.
17050      */
17051     regex : null,
17052     /**
17053      * @cfg {String} regexText The error text to display if {@link #regex} is used and the test fails during validation (defaults to "")
17054      */
17055     regexText : "",
17056     /**
17057      * @cfg {String} emptyText The default text to display in an empty field - placeholder... (defaults to null).
17058      */
17059     emptyText : null,
17060    
17061
17062     // private
17063     initEvents : function()
17064     {
17065         if (this.emptyText) {
17066             this.el.attr('placeholder', this.emptyText);
17067         }
17068         
17069         Roo.form.TextField.superclass.initEvents.call(this);
17070         if(this.validationEvent == 'keyup'){
17071             this.validationTask = new Roo.util.DelayedTask(this.validate, this);
17072             this.el.on('keyup', this.filterValidation, this);
17073         }
17074         else if(this.validationEvent !== false){
17075             this.el.on(this.validationEvent, this.validate, this, {buffer: this.validationDelay});
17076         }
17077         
17078         if(this.selectOnFocus){
17079             this.on("focus", this.preFocus, this);
17080         }
17081         if (!this.allowLeadingSpace) {
17082             this.on('blur', this.cleanLeadingSpace, this);
17083         }
17084         
17085         if(this.maskRe || (this.vtype && this.disableKeyFilter !== true && (this.maskRe = Roo.form.VTypes[this.vtype+'Mask']))){
17086             this.el.on("keypress", this.filterKeys, this);
17087         }
17088         if(this.grow){
17089             this.el.on("keyup", this.onKeyUp,  this, {buffer:50});
17090             this.el.on("click", this.autoSize,  this);
17091         }
17092         if(this.el.is('input[type=password]') && Roo.isSafari){
17093             this.el.on('keydown', this.SafariOnKeyDown, this);
17094         }
17095     },
17096
17097     processValue : function(value){
17098         if(this.stripCharsRe){
17099             var newValue = value.replace(this.stripCharsRe, '');
17100             if(newValue !== value){
17101                 this.setRawValue(newValue);
17102                 return newValue;
17103             }
17104         }
17105         return value;
17106     },
17107
17108     filterValidation : function(e){
17109         if(!e.isNavKeyPress()){
17110             this.validationTask.delay(this.validationDelay);
17111         }
17112     },
17113
17114     // private
17115     onKeyUp : function(e){
17116         if(!e.isNavKeyPress()){
17117             this.autoSize();
17118         }
17119     },
17120     // private - clean the leading white space
17121     cleanLeadingSpace : function(e)
17122     {
17123         if ( this.inputType == 'file') {
17124             return;
17125         }
17126         
17127         this.setValue((this.getValue() + '').replace(/^\s+/,''));
17128     },
17129     /**
17130      * Resets the current field value to the originally-loaded value and clears any validation messages.
17131      *  
17132      */
17133     reset : function(){
17134         Roo.form.TextField.superclass.reset.call(this);
17135        
17136     }, 
17137     // private
17138     preFocus : function(){
17139         
17140         if(this.selectOnFocus){
17141             this.el.dom.select();
17142         }
17143     },
17144
17145     
17146     // private
17147     filterKeys : function(e){
17148         var k = e.getKey();
17149         if(!Roo.isIE && (e.isNavKeyPress() || k == e.BACKSPACE || (k == e.DELETE && e.button == -1))){
17150             return;
17151         }
17152         var c = e.getCharCode(), cc = String.fromCharCode(c);
17153         if(Roo.isIE && (e.isSpecialKey() || !cc)){
17154             return;
17155         }
17156         if(!this.maskRe.test(cc)){
17157             e.stopEvent();
17158         }
17159     },
17160
17161     setValue : function(v){
17162         
17163         Roo.form.TextField.superclass.setValue.apply(this, arguments);
17164         
17165         this.autoSize();
17166     },
17167
17168     /**
17169      * Validates a value according to the field's validation rules and marks the field as invalid
17170      * if the validation fails
17171      * @param {Mixed} value The value to validate
17172      * @return {Boolean} True if the value is valid, else false
17173      */
17174     validateValue : function(value){
17175         if(value.length < 1)  { // if it's blank
17176              if(this.allowBlank){
17177                 this.clearInvalid();
17178                 return true;
17179              }else{
17180                 this.markInvalid(this.blankText);
17181                 return false;
17182              }
17183         }
17184         if(value.length < this.minLength){
17185             this.markInvalid(String.format(this.minLengthText, this.minLength));
17186             return false;
17187         }
17188         if(value.length > this.maxLength){
17189             this.markInvalid(String.format(this.maxLengthText, this.maxLength));
17190             return false;
17191         }
17192         if(this.vtype){
17193             var vt = Roo.form.VTypes;
17194             if(!vt[this.vtype](value, this)){
17195                 this.markInvalid(this.vtypeText || vt[this.vtype +'Text']);
17196                 return false;
17197             }
17198         }
17199         if(typeof this.validator == "function"){
17200             var msg = this.validator(value);
17201             if(msg !== true){
17202                 this.markInvalid(msg);
17203                 return false;
17204             }
17205         }
17206         if(this.regex && !this.regex.test(value)){
17207             this.markInvalid(this.regexText);
17208             return false;
17209         }
17210         return true;
17211     },
17212
17213     /**
17214      * Selects text in this field
17215      * @param {Number} start (optional) The index where the selection should start (defaults to 0)
17216      * @param {Number} end (optional) The index where the selection should end (defaults to the text length)
17217      */
17218     selectText : function(start, end){
17219         var v = this.getRawValue();
17220         if(v.length > 0){
17221             start = start === undefined ? 0 : start;
17222             end = end === undefined ? v.length : end;
17223             var d = this.el.dom;
17224             if(d.setSelectionRange){
17225                 d.setSelectionRange(start, end);
17226             }else if(d.createTextRange){
17227                 var range = d.createTextRange();
17228                 range.moveStart("character", start);
17229                 range.moveEnd("character", v.length-end);
17230                 range.select();
17231             }
17232         }
17233     },
17234
17235     /**
17236      * Automatically grows the field to accomodate the width of the text up to the maximum field width allowed.
17237      * This only takes effect if grow = true, and fires the autosize event.
17238      */
17239     autoSize : function(){
17240         if(!this.grow || !this.rendered){
17241             return;
17242         }
17243         if(!this.metrics){
17244             this.metrics = Roo.util.TextMetrics.createInstance(this.el);
17245         }
17246         var el = this.el;
17247         var v = el.dom.value;
17248         var d = document.createElement('div');
17249         d.appendChild(document.createTextNode(v));
17250         v = d.innerHTML;
17251         d = null;
17252         v += "&#160;";
17253         var w = Math.min(this.growMax, Math.max(this.metrics.getWidth(v) + /* add extra padding */ 10, this.growMin));
17254         this.el.setWidth(w);
17255         this.fireEvent("autosize", this, w);
17256     },
17257     
17258     // private
17259     SafariOnKeyDown : function(event)
17260     {
17261         // this is a workaround for a password hang bug on chrome/ webkit.
17262         
17263         var isSelectAll = false;
17264         
17265         if(this.el.dom.selectionEnd > 0){
17266             isSelectAll = (this.el.dom.selectionEnd - this.el.dom.selectionStart - this.getValue().length == 0) ? true : false;
17267         }
17268         if(((event.getKey() == 8 || event.getKey() == 46) && this.getValue().length ==1)){ // backspace and delete key
17269             event.preventDefault();
17270             this.setValue('');
17271             return;
17272         }
17273         
17274         if(isSelectAll && event.getCharCode() > 31){ // backspace and delete key
17275             
17276             event.preventDefault();
17277             // this is very hacky as keydown always get's upper case.
17278             
17279             var cc = String.fromCharCode(event.getCharCode());
17280             
17281             
17282             this.setValue( event.shiftKey ?  cc : cc.toLowerCase());
17283             
17284         }
17285         
17286         
17287     }
17288 });/*
17289  * Based on:
17290  * Ext JS Library 1.1.1
17291  * Copyright(c) 2006-2007, Ext JS, LLC.
17292  *
17293  * Originally Released Under LGPL - original licence link has changed is not relivant.
17294  *
17295  * Fork - LGPL
17296  * <script type="text/javascript">
17297  */
17298  
17299 /**
17300  * @class Roo.form.Hidden
17301  * @extends Roo.form.TextField
17302  * Simple Hidden element used on forms 
17303  * 
17304  * usage: form.add(new Roo.form.HiddenField({ 'name' : 'test1' }));
17305  * 
17306  * @constructor
17307  * Creates a new Hidden form element.
17308  * @param {Object} config Configuration options
17309  */
17310
17311
17312
17313 // easy hidden field...
17314 Roo.form.Hidden = function(config){
17315     Roo.form.Hidden.superclass.constructor.call(this, config);
17316 };
17317   
17318 Roo.extend(Roo.form.Hidden, Roo.form.TextField, {
17319     fieldLabel:      '',
17320     inputType:      'hidden',
17321     width:          50,
17322     allowBlank:     true,
17323     labelSeparator: '',
17324     hidden:         true,
17325     itemCls :       'x-form-item-display-none'
17326
17327
17328 });
17329
17330
17331 /*
17332  * Based on:
17333  * Ext JS Library 1.1.1
17334  * Copyright(c) 2006-2007, Ext JS, LLC.
17335  *
17336  * Originally Released Under LGPL - original licence link has changed is not relivant.
17337  *
17338  * Fork - LGPL
17339  * <script type="text/javascript">
17340  */
17341  
17342 /**
17343  * @class Roo.form.TriggerField
17344  * @extends Roo.form.TextField
17345  * Provides a convenient wrapper for TextFields that adds a clickable trigger button (looks like a combobox by default).
17346  * The trigger has no default action, so you must assign a function to implement the trigger click handler by
17347  * overriding {@link #onTriggerClick}. You can create a TriggerField directly, as it renders exactly like a combobox
17348  * for which you can provide a custom implementation.  For example:
17349  * <pre><code>
17350 var trigger = new Roo.form.TriggerField();
17351 trigger.onTriggerClick = myTriggerFn;
17352 trigger.applyTo('my-field');
17353 </code></pre>
17354  *
17355  * However, in general you will most likely want to use TriggerField as the base class for a reusable component.
17356  * {@link Roo.form.DateField} and {@link Roo.form.ComboBox} are perfect examples of this.
17357  * @cfg {String} triggerClass An additional CSS class used to style the trigger button.  The trigger will always get the
17358  * class 'x-form-trigger' by default and triggerClass will be <b>appended</b> if specified.
17359  * @constructor
17360  * Create a new TriggerField.
17361  * @param {Object} config Configuration options (valid {@Roo.form.TextField} config options will also be applied
17362  * to the base TextField)
17363  */
17364 Roo.form.TriggerField = function(config){
17365     this.mimicing = false;
17366     Roo.form.TriggerField.superclass.constructor.call(this, config);
17367 };
17368
17369 Roo.extend(Roo.form.TriggerField, Roo.form.TextField,  {
17370     /**
17371      * @cfg {String} triggerClass A CSS class to apply to the trigger
17372      */
17373     /**
17374      * @cfg {String/Object} autoCreate A DomHelper element spec, or true for a default element spec (defaults to
17375      * {tag: "input", type: "text", size: "16", autocomplete: "off"})
17376      */
17377     defaultAutoCreate : {tag: "input", type: "text", size: "16", autocomplete: "new-password"},
17378     /**
17379      * @cfg {Boolean} hideTrigger True to hide the trigger element and display only the base text field (defaults to false)
17380      */
17381     hideTrigger:false,
17382
17383     /** @cfg {Boolean} grow @hide */
17384     /** @cfg {Number} growMin @hide */
17385     /** @cfg {Number} growMax @hide */
17386
17387     /**
17388      * @hide 
17389      * @method
17390      */
17391     autoSize: Roo.emptyFn,
17392     // private
17393     monitorTab : true,
17394     // private
17395     deferHeight : true,
17396
17397     
17398     actionMode : 'wrap',
17399     // private
17400     onResize : function(w, h){
17401         Roo.form.TriggerField.superclass.onResize.apply(this, arguments);
17402         if(typeof w == 'number'){
17403             var x = w - this.trigger.getWidth();
17404             this.el.setWidth(this.adjustWidth('input', x));
17405             this.trigger.setStyle('left', x+'px');
17406         }
17407     },
17408
17409     // private
17410     adjustSize : Roo.BoxComponent.prototype.adjustSize,
17411
17412     // private
17413     getResizeEl : function(){
17414         return this.wrap;
17415     },
17416
17417     // private
17418     getPositionEl : function(){
17419         return this.wrap;
17420     },
17421
17422     // private
17423     alignErrorIcon : function(){
17424         this.errorIcon.alignTo(this.wrap, 'tl-tr', [2, 0]);
17425     },
17426
17427     // private
17428     onRender : function(ct, position){
17429         Roo.form.TriggerField.superclass.onRender.call(this, ct, position);
17430         this.wrap = this.el.wrap({cls: "x-form-field-wrap"});
17431         this.trigger = this.wrap.createChild(this.triggerConfig ||
17432                 {tag: "img", src: Roo.BLANK_IMAGE_URL, cls: "x-form-trigger " + this.triggerClass});
17433         if(this.hideTrigger){
17434             this.trigger.setDisplayed(false);
17435         }
17436         this.initTrigger();
17437         if(!this.width){
17438             this.wrap.setWidth(this.el.getWidth()+this.trigger.getWidth());
17439         }
17440     },
17441
17442     // private
17443     initTrigger : function(){
17444         this.trigger.on("click", this.onTriggerClick, this, {preventDefault:true});
17445         this.trigger.addClassOnOver('x-form-trigger-over');
17446         this.trigger.addClassOnClick('x-form-trigger-click');
17447     },
17448
17449     // private
17450     onDestroy : function(){
17451         if(this.trigger){
17452             this.trigger.removeAllListeners();
17453             this.trigger.remove();
17454         }
17455         if(this.wrap){
17456             this.wrap.remove();
17457         }
17458         Roo.form.TriggerField.superclass.onDestroy.call(this);
17459     },
17460
17461     // private
17462     onFocus : function(){
17463         Roo.form.TriggerField.superclass.onFocus.call(this);
17464         if(!this.mimicing){
17465             this.wrap.addClass('x-trigger-wrap-focus');
17466             this.mimicing = true;
17467             Roo.get(Roo.isIE ? document.body : document).on("mousedown", this.mimicBlur, this);
17468             if(this.monitorTab){
17469                 this.el.on("keydown", this.checkTab, this);
17470             }
17471         }
17472     },
17473
17474     // private
17475     checkTab : function(e){
17476         if(e.getKey() == e.TAB){
17477             this.triggerBlur();
17478         }
17479     },
17480
17481     // private
17482     onBlur : function(){
17483         // do nothing
17484     },
17485
17486     // private
17487     mimicBlur : function(e, t){
17488         if(!this.wrap.contains(t) && this.validateBlur()){
17489             this.triggerBlur();
17490         }
17491     },
17492
17493     // private
17494     triggerBlur : function(){
17495         this.mimicing = false;
17496         Roo.get(Roo.isIE ? document.body : document).un("mousedown", this.mimicBlur);
17497         if(this.monitorTab){
17498             this.el.un("keydown", this.checkTab, this);
17499         }
17500         this.wrap.removeClass('x-trigger-wrap-focus');
17501         Roo.form.TriggerField.superclass.onBlur.call(this);
17502     },
17503
17504     // private
17505     // This should be overriden by any subclass that needs to check whether or not the field can be blurred.
17506     validateBlur : function(e, t){
17507         return true;
17508     },
17509
17510     // private
17511     onDisable : function(){
17512         Roo.form.TriggerField.superclass.onDisable.call(this);
17513         if(this.wrap){
17514             this.wrap.addClass('x-item-disabled');
17515         }
17516     },
17517
17518     // private
17519     onEnable : function(){
17520         Roo.form.TriggerField.superclass.onEnable.call(this);
17521         if(this.wrap){
17522             this.wrap.removeClass('x-item-disabled');
17523         }
17524     },
17525
17526     // private
17527     onShow : function(){
17528         var ae = this.getActionEl();
17529         
17530         if(ae){
17531             ae.dom.style.display = '';
17532             ae.dom.style.visibility = 'visible';
17533         }
17534     },
17535
17536     // private
17537     
17538     onHide : function(){
17539         var ae = this.getActionEl();
17540         ae.dom.style.display = 'none';
17541     },
17542
17543     /**
17544      * The function that should handle the trigger's click event.  This method does nothing by default until overridden
17545      * by an implementing function.
17546      * @method
17547      * @param {EventObject} e
17548      */
17549     onTriggerClick : Roo.emptyFn
17550 });
17551
17552 // TwinTriggerField is not a public class to be used directly.  It is meant as an abstract base class
17553 // to be extended by an implementing class.  For an example of implementing this class, see the custom
17554 // SearchField implementation here: http://extjs.com/deploy/ext/examples/form/custom.html
17555 Roo.form.TwinTriggerField = Roo.extend(Roo.form.TriggerField, {
17556     initComponent : function(){
17557         Roo.form.TwinTriggerField.superclass.initComponent.call(this);
17558
17559         this.triggerConfig = {
17560             tag:'span', cls:'x-form-twin-triggers', cn:[
17561             {tag: "img", src: Roo.BLANK_IMAGE_URL, cls: "x-form-trigger " + this.trigger1Class},
17562             {tag: "img", src: Roo.BLANK_IMAGE_URL, cls: "x-form-trigger " + this.trigger2Class}
17563         ]};
17564     },
17565
17566     getTrigger : function(index){
17567         return this.triggers[index];
17568     },
17569
17570     initTrigger : function(){
17571         var ts = this.trigger.select('.x-form-trigger', true);
17572         this.wrap.setStyle('overflow', 'hidden');
17573         var triggerField = this;
17574         ts.each(function(t, all, index){
17575             t.hide = function(){
17576                 var w = triggerField.wrap.getWidth();
17577                 this.dom.style.display = 'none';
17578                 triggerField.el.setWidth(w-triggerField.trigger.getWidth());
17579             };
17580             t.show = function(){
17581                 var w = triggerField.wrap.getWidth();
17582                 this.dom.style.display = '';
17583                 triggerField.el.setWidth(w-triggerField.trigger.getWidth());
17584             };
17585             var triggerIndex = 'Trigger'+(index+1);
17586
17587             if(this['hide'+triggerIndex]){
17588                 t.dom.style.display = 'none';
17589             }
17590             t.on("click", this['on'+triggerIndex+'Click'], this, {preventDefault:true});
17591             t.addClassOnOver('x-form-trigger-over');
17592             t.addClassOnClick('x-form-trigger-click');
17593         }, this);
17594         this.triggers = ts.elements;
17595     },
17596
17597     onTrigger1Click : Roo.emptyFn,
17598     onTrigger2Click : Roo.emptyFn
17599 });/*
17600  * Based on:
17601  * Ext JS Library 1.1.1
17602  * Copyright(c) 2006-2007, Ext JS, LLC.
17603  *
17604  * Originally Released Under LGPL - original licence link has changed is not relivant.
17605  *
17606  * Fork - LGPL
17607  * <script type="text/javascript">
17608  */
17609  
17610 /**
17611  * @class Roo.form.TextArea
17612  * @extends Roo.form.TextField
17613  * Multiline text field.  Can be used as a direct replacement for traditional textarea fields, plus adds
17614  * support for auto-sizing.
17615  * @constructor
17616  * Creates a new TextArea
17617  * @param {Object} config Configuration options
17618  */
17619 Roo.form.TextArea = function(config){
17620     Roo.form.TextArea.superclass.constructor.call(this, config);
17621     // these are provided exchanges for backwards compat
17622     // minHeight/maxHeight were replaced by growMin/growMax to be
17623     // compatible with TextField growing config values
17624     if(this.minHeight !== undefined){
17625         this.growMin = this.minHeight;
17626     }
17627     if(this.maxHeight !== undefined){
17628         this.growMax = this.maxHeight;
17629     }
17630 };
17631
17632 Roo.extend(Roo.form.TextArea, Roo.form.TextField,  {
17633     /**
17634      * @cfg {Number} growMin The minimum height to allow when grow = true (defaults to 60)
17635      */
17636     growMin : 60,
17637     /**
17638      * @cfg {Number} growMax The maximum height to allow when grow = true (defaults to 1000)
17639      */
17640     growMax: 1000,
17641     /**
17642      * @cfg {Boolean} preventScrollbars True to prevent scrollbars from appearing regardless of how much text is
17643      * in the field (equivalent to setting overflow: hidden, defaults to false)
17644      */
17645     preventScrollbars: false,
17646     /**
17647      * @cfg {String/Object} autoCreate A DomHelper element spec, or true for a default element spec (defaults to
17648      * {tag: "textarea", style: "width:300px;height:60px;", autocomplete: "off"})
17649      */
17650
17651     // private
17652     onRender : function(ct, position){
17653         if(!this.el){
17654             this.defaultAutoCreate = {
17655                 tag: "textarea",
17656                 style:"width:300px;height:60px;",
17657                 autocomplete: "new-password"
17658             };
17659         }
17660         Roo.form.TextArea.superclass.onRender.call(this, ct, position);
17661         if(this.grow){
17662             this.textSizeEl = Roo.DomHelper.append(document.body, {
17663                 tag: "pre", cls: "x-form-grow-sizer"
17664             });
17665             if(this.preventScrollbars){
17666                 this.el.setStyle("overflow", "hidden");
17667             }
17668             this.el.setHeight(this.growMin);
17669         }
17670     },
17671
17672     onDestroy : function(){
17673         if(this.textSizeEl){
17674             this.textSizeEl.parentNode.removeChild(this.textSizeEl);
17675         }
17676         Roo.form.TextArea.superclass.onDestroy.call(this);
17677     },
17678
17679     // private
17680     onKeyUp : function(e){
17681         if(!e.isNavKeyPress() || e.getKey() == e.ENTER){
17682             this.autoSize();
17683         }
17684     },
17685
17686     /**
17687      * Automatically grows the field to accomodate the height of the text up to the maximum field height allowed.
17688      * This only takes effect if grow = true, and fires the autosize event if the height changes.
17689      */
17690     autoSize : function(){
17691         if(!this.grow || !this.textSizeEl){
17692             return;
17693         }
17694         var el = this.el;
17695         var v = el.dom.value;
17696         var ts = this.textSizeEl;
17697
17698         ts.innerHTML = '';
17699         ts.appendChild(document.createTextNode(v));
17700         v = ts.innerHTML;
17701
17702         Roo.fly(ts).setWidth(this.el.getWidth());
17703         if(v.length < 1){
17704             v = "&#160;&#160;";
17705         }else{
17706             if(Roo.isIE){
17707                 v = v.replace(/\n/g, '<p>&#160;</p>');
17708             }
17709             v += "&#160;\n&#160;";
17710         }
17711         ts.innerHTML = v;
17712         var h = Math.min(this.growMax, Math.max(ts.offsetHeight, this.growMin));
17713         if(h != this.lastHeight){
17714             this.lastHeight = h;
17715             this.el.setHeight(h);
17716             this.fireEvent("autosize", this, h);
17717         }
17718     }
17719 });/*
17720  * Based on:
17721  * Ext JS Library 1.1.1
17722  * Copyright(c) 2006-2007, Ext JS, LLC.
17723  *
17724  * Originally Released Under LGPL - original licence link has changed is not relivant.
17725  *
17726  * Fork - LGPL
17727  * <script type="text/javascript">
17728  */
17729  
17730
17731 /**
17732  * @class Roo.form.NumberField
17733  * @extends Roo.form.TextField
17734  * Numeric text field that provides automatic keystroke filtering and numeric validation.
17735  * @constructor
17736  * Creates a new NumberField
17737  * @param {Object} config Configuration options
17738  */
17739 Roo.form.NumberField = function(config){
17740     Roo.form.NumberField.superclass.constructor.call(this, config);
17741 };
17742
17743 Roo.extend(Roo.form.NumberField, Roo.form.TextField,  {
17744     /**
17745      * @cfg {String} fieldClass The default CSS class for the field (defaults to "x-form-field x-form-num-field")
17746      */
17747     fieldClass: "x-form-field x-form-num-field",
17748     /**
17749      * @cfg {Boolean} allowDecimals False to disallow decimal values (defaults to true)
17750      */
17751     allowDecimals : true,
17752     /**
17753      * @cfg {String} decimalSeparator Character(s) to allow as the decimal separator (defaults to '.')
17754      */
17755     decimalSeparator : ".",
17756     /**
17757      * @cfg {Number} decimalPrecision The maximum precision to display after the decimal separator (defaults to 2)
17758      */
17759     decimalPrecision : 2,
17760     /**
17761      * @cfg {Boolean} allowNegative False to prevent entering a negative sign (defaults to true)
17762      */
17763     allowNegative : true,
17764     /**
17765      * @cfg {Number} minValue The minimum allowed value (defaults to Number.NEGATIVE_INFINITY)
17766      */
17767     minValue : Number.NEGATIVE_INFINITY,
17768     /**
17769      * @cfg {Number} maxValue The maximum allowed value (defaults to Number.MAX_VALUE)
17770      */
17771     maxValue : Number.MAX_VALUE,
17772     /**
17773      * @cfg {String} minText Error text to display if the minimum value validation fails (defaults to "The minimum value for this field is {minValue}")
17774      */
17775     minText : "The minimum value for this field is {0}",
17776     /**
17777      * @cfg {String} maxText Error text to display if the maximum value validation fails (defaults to "The maximum value for this field is {maxValue}")
17778      */
17779     maxText : "The maximum value for this field is {0}",
17780     /**
17781      * @cfg {String} nanText Error text to display if the value is not a valid number.  For example, this can happen
17782      * if a valid character like '.' or '-' is left in the field with no number (defaults to "{value} is not a valid number")
17783      */
17784     nanText : "{0} is not a valid number",
17785
17786     // private
17787     initEvents : function(){
17788         Roo.form.NumberField.superclass.initEvents.call(this);
17789         var allowed = "0123456789";
17790         if(this.allowDecimals){
17791             allowed += this.decimalSeparator;
17792         }
17793         if(this.allowNegative){
17794             allowed += "-";
17795         }
17796         this.stripCharsRe = new RegExp('[^'+allowed+']', 'gi');
17797         var keyPress = function(e){
17798             var k = e.getKey();
17799             if(!Roo.isIE && (e.isSpecialKey() || k == e.BACKSPACE || k == e.DELETE)){
17800                 return;
17801             }
17802             var c = e.getCharCode();
17803             if(allowed.indexOf(String.fromCharCode(c)) === -1){
17804                 e.stopEvent();
17805             }
17806         };
17807         this.el.on("keypress", keyPress, this);
17808     },
17809
17810     // private
17811     validateValue : function(value){
17812         if(!Roo.form.NumberField.superclass.validateValue.call(this, value)){
17813             return false;
17814         }
17815         if(value.length < 1){ // if it's blank and textfield didn't flag it then it's valid
17816              return true;
17817         }
17818         var num = this.parseValue(value);
17819         if(isNaN(num)){
17820             this.markInvalid(String.format(this.nanText, value));
17821             return false;
17822         }
17823         if(num < this.minValue){
17824             this.markInvalid(String.format(this.minText, this.minValue));
17825             return false;
17826         }
17827         if(num > this.maxValue){
17828             this.markInvalid(String.format(this.maxText, this.maxValue));
17829             return false;
17830         }
17831         return true;
17832     },
17833
17834     getValue : function(){
17835         return this.fixPrecision(this.parseValue(Roo.form.NumberField.superclass.getValue.call(this)));
17836     },
17837
17838     // private
17839     parseValue : function(value){
17840         value = parseFloat(String(value).replace(this.decimalSeparator, "."));
17841         return isNaN(value) ? '' : value;
17842     },
17843
17844     // private
17845     fixPrecision : function(value){
17846         var nan = isNaN(value);
17847         if(!this.allowDecimals || this.decimalPrecision == -1 || nan || !value){
17848             return nan ? '' : value;
17849         }
17850         return parseFloat(value).toFixed(this.decimalPrecision);
17851     },
17852
17853     setValue : function(v){
17854         v = this.fixPrecision(v);
17855         Roo.form.NumberField.superclass.setValue.call(this, String(v).replace(".", this.decimalSeparator));
17856     },
17857
17858     // private
17859     decimalPrecisionFcn : function(v){
17860         return Math.floor(v);
17861     },
17862
17863     beforeBlur : function(){
17864         var v = this.parseValue(this.getRawValue());
17865         if(v){
17866             this.setValue(v);
17867         }
17868     }
17869 });/*
17870  * Based on:
17871  * Ext JS Library 1.1.1
17872  * Copyright(c) 2006-2007, Ext JS, LLC.
17873  *
17874  * Originally Released Under LGPL - original licence link has changed is not relivant.
17875  *
17876  * Fork - LGPL
17877  * <script type="text/javascript">
17878  */
17879  
17880 /**
17881  * @class Roo.form.DateField
17882  * @extends Roo.form.TriggerField
17883  * Provides a date input field with a {@link Roo.DatePicker} dropdown and automatic date validation.
17884 * @constructor
17885 * Create a new DateField
17886 * @param {Object} config
17887  */
17888 Roo.form.DateField = function(config)
17889 {
17890     Roo.form.DateField.superclass.constructor.call(this, config);
17891     
17892       this.addEvents({
17893          
17894         /**
17895          * @event select
17896          * Fires when a date is selected
17897              * @param {Roo.form.DateField} combo This combo box
17898              * @param {Date} date The date selected
17899              */
17900         'select' : true
17901          
17902     });
17903     
17904     
17905     if(typeof this.minValue == "string") {
17906         this.minValue = this.parseDate(this.minValue);
17907     }
17908     if(typeof this.maxValue == "string") {
17909         this.maxValue = this.parseDate(this.maxValue);
17910     }
17911     this.ddMatch = null;
17912     if(this.disabledDates){
17913         var dd = this.disabledDates;
17914         var re = "(?:";
17915         for(var i = 0; i < dd.length; i++){
17916             re += dd[i];
17917             if(i != dd.length-1) {
17918                 re += "|";
17919             }
17920         }
17921         this.ddMatch = new RegExp(re + ")");
17922     }
17923 };
17924
17925 Roo.extend(Roo.form.DateField, Roo.form.TriggerField,  {
17926     /**
17927      * @cfg {String} format
17928      * The default date format string which can be overriden for localization support.  The format must be
17929      * valid according to {@link Date#parseDate} (defaults to 'm/d/y').
17930      */
17931     format : "m/d/y",
17932     /**
17933      * @cfg {String} altFormats
17934      * Multiple date formats separated by "|" to try when parsing a user input value and it doesn't match the defined
17935      * format (defaults to 'm/d/Y|m-d-y|m-d-Y|m/d|m-d|d').
17936      */
17937     altFormats : "m/d/Y|m-d-y|m-d-Y|m/d|m-d|md|mdy|mdY|d",
17938     /**
17939      * @cfg {Array} disabledDays
17940      * An array of days to disable, 0 based. For example, [0, 6] disables Sunday and Saturday (defaults to null).
17941      */
17942     disabledDays : null,
17943     /**
17944      * @cfg {String} disabledDaysText
17945      * The tooltip to display when the date falls on a disabled day (defaults to 'Disabled')
17946      */
17947     disabledDaysText : "Disabled",
17948     /**
17949      * @cfg {Array} disabledDates
17950      * An array of "dates" to disable, as strings. These strings will be used to build a dynamic regular
17951      * expression so they are very powerful. Some examples:
17952      * <ul>
17953      * <li>["03/08/2003", "09/16/2003"] would disable those exact dates</li>
17954      * <li>["03/08", "09/16"] would disable those days for every year</li>
17955      * <li>["^03/08"] would only match the beginning (useful if you are using short years)</li>
17956      * <li>["03/../2006"] would disable every day in March 2006</li>
17957      * <li>["^03"] would disable every day in every March</li>
17958      * </ul>
17959      * In order to support regular expressions, if you are using a date format that has "." in it, you will have to
17960      * escape the dot when restricting dates. For example: ["03\\.08\\.03"].
17961      */
17962     disabledDates : null,
17963     /**
17964      * @cfg {String} disabledDatesText
17965      * The tooltip text to display when the date falls on a disabled date (defaults to 'Disabled')
17966      */
17967     disabledDatesText : "Disabled",
17968     /**
17969      * @cfg {Date/String} minValue
17970      * The minimum allowed date. Can be either a Javascript date object or a string date in a
17971      * valid format (defaults to null).
17972      */
17973     minValue : null,
17974     /**
17975      * @cfg {Date/String} maxValue
17976      * The maximum allowed date. Can be either a Javascript date object or a string date in a
17977      * valid format (defaults to null).
17978      */
17979     maxValue : null,
17980     /**
17981      * @cfg {String} minText
17982      * The error text to display when the date in the cell is before minValue (defaults to
17983      * 'The date in this field must be after {minValue}').
17984      */
17985     minText : "The date in this field must be equal to or after {0}",
17986     /**
17987      * @cfg {String} maxText
17988      * The error text to display when the date in the cell is after maxValue (defaults to
17989      * 'The date in this field must be before {maxValue}').
17990      */
17991     maxText : "The date in this field must be equal to or before {0}",
17992     /**
17993      * @cfg {String} invalidText
17994      * The error text to display when the date in the field is invalid (defaults to
17995      * '{value} is not a valid date - it must be in the format {format}').
17996      */
17997     invalidText : "{0} is not a valid date - it must be in the format {1}",
17998     /**
17999      * @cfg {String} triggerClass
18000      * An additional CSS class used to style the trigger button.  The trigger will always get the
18001      * class 'x-form-trigger' and triggerClass will be <b>appended</b> if specified (defaults to 'x-form-date-trigger'
18002      * which displays a calendar icon).
18003      */
18004     triggerClass : 'x-form-date-trigger',
18005     
18006
18007     /**
18008      * @cfg {Boolean} useIso
18009      * if enabled, then the date field will use a hidden field to store the 
18010      * real value as iso formated date. default (false)
18011      */ 
18012     useIso : false,
18013     /**
18014      * @cfg {String/Object} autoCreate
18015      * A DomHelper element spec, or true for a default element spec (defaults to
18016      * {tag: "input", type: "text", size: "10", autocomplete: "off"})
18017      */ 
18018     // private
18019     defaultAutoCreate : {tag: "input", type: "text", size: "10", autocomplete: "off"},
18020     
18021     // private
18022     hiddenField: false,
18023     
18024     onRender : function(ct, position)
18025     {
18026         Roo.form.DateField.superclass.onRender.call(this, ct, position);
18027         if (this.useIso) {
18028             //this.el.dom.removeAttribute('name'); 
18029             Roo.log("Changing name?");
18030             this.el.dom.setAttribute('name', this.name + '____hidden___' ); 
18031             this.hiddenField = this.el.insertSibling({ tag:'input', type:'hidden', name: this.name },
18032                     'before', true);
18033             this.hiddenField.value = this.value ? this.formatDate(this.value, 'Y-m-d') : '';
18034             // prevent input submission
18035             this.hiddenName = this.name;
18036         }
18037             
18038             
18039     },
18040     
18041     // private
18042     validateValue : function(value)
18043     {
18044         value = this.formatDate(value);
18045         if(!Roo.form.DateField.superclass.validateValue.call(this, value)){
18046             Roo.log('super failed');
18047             return false;
18048         }
18049         if(value.length < 1){ // if it's blank and textfield didn't flag it then it's valid
18050              return true;
18051         }
18052         var svalue = value;
18053         value = this.parseDate(value);
18054         if(!value){
18055             Roo.log('parse date failed' + svalue);
18056             this.markInvalid(String.format(this.invalidText, svalue, this.format));
18057             return false;
18058         }
18059         var time = value.getTime();
18060         if(this.minValue && time < this.minValue.getTime()){
18061             this.markInvalid(String.format(this.minText, this.formatDate(this.minValue)));
18062             return false;
18063         }
18064         if(this.maxValue && time > this.maxValue.getTime()){
18065             this.markInvalid(String.format(this.maxText, this.formatDate(this.maxValue)));
18066             return false;
18067         }
18068         if(this.disabledDays){
18069             var day = value.getDay();
18070             for(var i = 0; i < this.disabledDays.length; i++) {
18071                 if(day === this.disabledDays[i]){
18072                     this.markInvalid(this.disabledDaysText);
18073                     return false;
18074                 }
18075             }
18076         }
18077         var fvalue = this.formatDate(value);
18078         if(this.ddMatch && this.ddMatch.test(fvalue)){
18079             this.markInvalid(String.format(this.disabledDatesText, fvalue));
18080             return false;
18081         }
18082         return true;
18083     },
18084
18085     // private
18086     // Provides logic to override the default TriggerField.validateBlur which just returns true
18087     validateBlur : function(){
18088         return !this.menu || !this.menu.isVisible();
18089     },
18090     
18091     getName: function()
18092     {
18093         // returns hidden if it's set..
18094         if (!this.rendered) {return ''};
18095         return !this.hiddenName && this.el.dom.name  ? this.el.dom.name : (this.hiddenName || '');
18096         
18097     },
18098
18099     /**
18100      * Returns the current date value of the date field.
18101      * @return {Date} The date value
18102      */
18103     getValue : function(){
18104         
18105         return  this.hiddenField ?
18106                 this.hiddenField.value :
18107                 this.parseDate(Roo.form.DateField.superclass.getValue.call(this)) || "";
18108     },
18109
18110     /**
18111      * Sets the value of the date field.  You can pass a date object or any string that can be parsed into a valid
18112      * date, using DateField.format as the date format, according to the same rules as {@link Date#parseDate}
18113      * (the default format used is "m/d/y").
18114      * <br />Usage:
18115      * <pre><code>
18116 //All of these calls set the same date value (May 4, 2006)
18117
18118 //Pass a date object:
18119 var dt = new Date('5/4/06');
18120 dateField.setValue(dt);
18121
18122 //Pass a date string (default format):
18123 dateField.setValue('5/4/06');
18124
18125 //Pass a date string (custom format):
18126 dateField.format = 'Y-m-d';
18127 dateField.setValue('2006-5-4');
18128 </code></pre>
18129      * @param {String/Date} date The date or valid date string
18130      */
18131     setValue : function(date){
18132         if (this.hiddenField) {
18133             this.hiddenField.value = this.formatDate(this.parseDate(date), 'Y-m-d');
18134         }
18135         Roo.form.DateField.superclass.setValue.call(this, this.formatDate(this.parseDate(date)));
18136         // make sure the value field is always stored as a date..
18137         this.value = this.parseDate(date);
18138         
18139         
18140     },
18141
18142     // private
18143     parseDate : function(value){
18144         if(!value || value instanceof Date){
18145             return value;
18146         }
18147         var v = Date.parseDate(value, this.format);
18148          if (!v && this.useIso) {
18149             v = Date.parseDate(value, 'Y-m-d');
18150         }
18151         if(!v && this.altFormats){
18152             if(!this.altFormatsArray){
18153                 this.altFormatsArray = this.altFormats.split("|");
18154             }
18155             for(var i = 0, len = this.altFormatsArray.length; i < len && !v; i++){
18156                 v = Date.parseDate(value, this.altFormatsArray[i]);
18157             }
18158         }
18159         return v;
18160     },
18161
18162     // private
18163     formatDate : function(date, fmt){
18164         return (!date || !(date instanceof Date)) ?
18165                date : date.dateFormat(fmt || this.format);
18166     },
18167
18168     // private
18169     menuListeners : {
18170         select: function(m, d){
18171             
18172             this.setValue(d);
18173             this.fireEvent('select', this, d);
18174         },
18175         show : function(){ // retain focus styling
18176             this.onFocus();
18177         },
18178         hide : function(){
18179             this.focus.defer(10, this);
18180             var ml = this.menuListeners;
18181             this.menu.un("select", ml.select,  this);
18182             this.menu.un("show", ml.show,  this);
18183             this.menu.un("hide", ml.hide,  this);
18184         }
18185     },
18186
18187     // private
18188     // Implements the default empty TriggerField.onTriggerClick function to display the DatePicker
18189     onTriggerClick : function(){
18190         if(this.disabled){
18191             return;
18192         }
18193         if(this.menu == null){
18194             this.menu = new Roo.menu.DateMenu();
18195         }
18196         Roo.apply(this.menu.picker,  {
18197             showClear: this.allowBlank,
18198             minDate : this.minValue,
18199             maxDate : this.maxValue,
18200             disabledDatesRE : this.ddMatch,
18201             disabledDatesText : this.disabledDatesText,
18202             disabledDays : this.disabledDays,
18203             disabledDaysText : this.disabledDaysText,
18204             format : this.useIso ? 'Y-m-d' : this.format,
18205             minText : String.format(this.minText, this.formatDate(this.minValue)),
18206             maxText : String.format(this.maxText, this.formatDate(this.maxValue))
18207         });
18208         this.menu.on(Roo.apply({}, this.menuListeners, {
18209             scope:this
18210         }));
18211         this.menu.picker.setValue(this.getValue() || new Date());
18212         this.menu.show(this.el, "tl-bl?");
18213     },
18214
18215     beforeBlur : function(){
18216         var v = this.parseDate(this.getRawValue());
18217         if(v){
18218             this.setValue(v);
18219         }
18220     },
18221
18222     /*@
18223      * overide
18224      * 
18225      */
18226     isDirty : function() {
18227         if(this.disabled) {
18228             return false;
18229         }
18230         
18231         if(typeof(this.startValue) === 'undefined'){
18232             return false;
18233         }
18234         
18235         return String(this.getValue()) !== String(this.startValue);
18236         
18237     },
18238     // @overide
18239     cleanLeadingSpace : function(e)
18240     {
18241        return;
18242     }
18243     
18244 });/*
18245  * Based on:
18246  * Ext JS Library 1.1.1
18247  * Copyright(c) 2006-2007, Ext JS, LLC.
18248  *
18249  * Originally Released Under LGPL - original licence link has changed is not relivant.
18250  *
18251  * Fork - LGPL
18252  * <script type="text/javascript">
18253  */
18254  
18255 /**
18256  * @class Roo.form.MonthField
18257  * @extends Roo.form.TriggerField
18258  * Provides a date input field with a {@link Roo.DatePicker} dropdown and automatic date validation.
18259 * @constructor
18260 * Create a new MonthField
18261 * @param {Object} config
18262  */
18263 Roo.form.MonthField = function(config){
18264     
18265     Roo.form.MonthField.superclass.constructor.call(this, config);
18266     
18267       this.addEvents({
18268          
18269         /**
18270          * @event select
18271          * Fires when a date is selected
18272              * @param {Roo.form.MonthFieeld} combo This combo box
18273              * @param {Date} date The date selected
18274              */
18275         'select' : true
18276          
18277     });
18278     
18279     
18280     if(typeof this.minValue == "string") {
18281         this.minValue = this.parseDate(this.minValue);
18282     }
18283     if(typeof this.maxValue == "string") {
18284         this.maxValue = this.parseDate(this.maxValue);
18285     }
18286     this.ddMatch = null;
18287     if(this.disabledDates){
18288         var dd = this.disabledDates;
18289         var re = "(?:";
18290         for(var i = 0; i < dd.length; i++){
18291             re += dd[i];
18292             if(i != dd.length-1) {
18293                 re += "|";
18294             }
18295         }
18296         this.ddMatch = new RegExp(re + ")");
18297     }
18298 };
18299
18300 Roo.extend(Roo.form.MonthField, Roo.form.TriggerField,  {
18301     /**
18302      * @cfg {String} format
18303      * The default date format string which can be overriden for localization support.  The format must be
18304      * valid according to {@link Date#parseDate} (defaults to 'm/d/y').
18305      */
18306     format : "M Y",
18307     /**
18308      * @cfg {String} altFormats
18309      * Multiple date formats separated by "|" to try when parsing a user input value and it doesn't match the defined
18310      * format (defaults to 'm/d/Y|m-d-y|m-d-Y|m/d|m-d|d').
18311      */
18312     altFormats : "M Y|m/Y|m-y|m-Y|my|mY",
18313     /**
18314      * @cfg {Array} disabledDays
18315      * An array of days to disable, 0 based. For example, [0, 6] disables Sunday and Saturday (defaults to null).
18316      */
18317     disabledDays : [0,1,2,3,4,5,6],
18318     /**
18319      * @cfg {String} disabledDaysText
18320      * The tooltip to display when the date falls on a disabled day (defaults to 'Disabled')
18321      */
18322     disabledDaysText : "Disabled",
18323     /**
18324      * @cfg {Array} disabledDates
18325      * An array of "dates" to disable, as strings. These strings will be used to build a dynamic regular
18326      * expression so they are very powerful. Some examples:
18327      * <ul>
18328      * <li>["03/08/2003", "09/16/2003"] would disable those exact dates</li>
18329      * <li>["03/08", "09/16"] would disable those days for every year</li>
18330      * <li>["^03/08"] would only match the beginning (useful if you are using short years)</li>
18331      * <li>["03/../2006"] would disable every day in March 2006</li>
18332      * <li>["^03"] would disable every day in every March</li>
18333      * </ul>
18334      * In order to support regular expressions, if you are using a date format that has "." in it, you will have to
18335      * escape the dot when restricting dates. For example: ["03\\.08\\.03"].
18336      */
18337     disabledDates : null,
18338     /**
18339      * @cfg {String} disabledDatesText
18340      * The tooltip text to display when the date falls on a disabled date (defaults to 'Disabled')
18341      */
18342     disabledDatesText : "Disabled",
18343     /**
18344      * @cfg {Date/String} minValue
18345      * The minimum allowed date. Can be either a Javascript date object or a string date in a
18346      * valid format (defaults to null).
18347      */
18348     minValue : null,
18349     /**
18350      * @cfg {Date/String} maxValue
18351      * The maximum allowed date. Can be either a Javascript date object or a string date in a
18352      * valid format (defaults to null).
18353      */
18354     maxValue : null,
18355     /**
18356      * @cfg {String} minText
18357      * The error text to display when the date in the cell is before minValue (defaults to
18358      * 'The date in this field must be after {minValue}').
18359      */
18360     minText : "The date in this field must be equal to or after {0}",
18361     /**
18362      * @cfg {String} maxTextf
18363      * The error text to display when the date in the cell is after maxValue (defaults to
18364      * 'The date in this field must be before {maxValue}').
18365      */
18366     maxText : "The date in this field must be equal to or before {0}",
18367     /**
18368      * @cfg {String} invalidText
18369      * The error text to display when the date in the field is invalid (defaults to
18370      * '{value} is not a valid date - it must be in the format {format}').
18371      */
18372     invalidText : "{0} is not a valid date - it must be in the format {1}",
18373     /**
18374      * @cfg {String} triggerClass
18375      * An additional CSS class used to style the trigger button.  The trigger will always get the
18376      * class 'x-form-trigger' and triggerClass will be <b>appended</b> if specified (defaults to 'x-form-date-trigger'
18377      * which displays a calendar icon).
18378      */
18379     triggerClass : 'x-form-date-trigger',
18380     
18381
18382     /**
18383      * @cfg {Boolean} useIso
18384      * if enabled, then the date field will use a hidden field to store the 
18385      * real value as iso formated date. default (true)
18386      */ 
18387     useIso : true,
18388     /**
18389      * @cfg {String/Object} autoCreate
18390      * A DomHelper element spec, or true for a default element spec (defaults to
18391      * {tag: "input", type: "text", size: "10", autocomplete: "off"})
18392      */ 
18393     // private
18394     defaultAutoCreate : {tag: "input", type: "text", size: "10", autocomplete: "new-password"},
18395     
18396     // private
18397     hiddenField: false,
18398     
18399     hideMonthPicker : false,
18400     
18401     onRender : function(ct, position)
18402     {
18403         Roo.form.MonthField.superclass.onRender.call(this, ct, position);
18404         if (this.useIso) {
18405             this.el.dom.removeAttribute('name'); 
18406             this.hiddenField = this.el.insertSibling({ tag:'input', type:'hidden', name: this.name },
18407                     'before', true);
18408             this.hiddenField.value = this.value ? this.formatDate(this.value, 'Y-m-d') : '';
18409             // prevent input submission
18410             this.hiddenName = this.name;
18411         }
18412             
18413             
18414     },
18415     
18416     // private
18417     validateValue : function(value)
18418     {
18419         value = this.formatDate(value);
18420         if(!Roo.form.MonthField.superclass.validateValue.call(this, value)){
18421             return false;
18422         }
18423         if(value.length < 1){ // if it's blank and textfield didn't flag it then it's valid
18424              return true;
18425         }
18426         var svalue = value;
18427         value = this.parseDate(value);
18428         if(!value){
18429             this.markInvalid(String.format(this.invalidText, svalue, this.format));
18430             return false;
18431         }
18432         var time = value.getTime();
18433         if(this.minValue && time < this.minValue.getTime()){
18434             this.markInvalid(String.format(this.minText, this.formatDate(this.minValue)));
18435             return false;
18436         }
18437         if(this.maxValue && time > this.maxValue.getTime()){
18438             this.markInvalid(String.format(this.maxText, this.formatDate(this.maxValue)));
18439             return false;
18440         }
18441         /*if(this.disabledDays){
18442             var day = value.getDay();
18443             for(var i = 0; i < this.disabledDays.length; i++) {
18444                 if(day === this.disabledDays[i]){
18445                     this.markInvalid(this.disabledDaysText);
18446                     return false;
18447                 }
18448             }
18449         }
18450         */
18451         var fvalue = this.formatDate(value);
18452         /*if(this.ddMatch && this.ddMatch.test(fvalue)){
18453             this.markInvalid(String.format(this.disabledDatesText, fvalue));
18454             return false;
18455         }
18456         */
18457         return true;
18458     },
18459
18460     // private
18461     // Provides logic to override the default TriggerField.validateBlur which just returns true
18462     validateBlur : function(){
18463         return !this.menu || !this.menu.isVisible();
18464     },
18465
18466     /**
18467      * Returns the current date value of the date field.
18468      * @return {Date} The date value
18469      */
18470     getValue : function(){
18471         
18472         
18473         
18474         return  this.hiddenField ?
18475                 this.hiddenField.value :
18476                 this.parseDate(Roo.form.MonthField.superclass.getValue.call(this)) || "";
18477     },
18478
18479     /**
18480      * Sets the value of the date field.  You can pass a date object or any string that can be parsed into a valid
18481      * date, using MonthField.format as the date format, according to the same rules as {@link Date#parseDate}
18482      * (the default format used is "m/d/y").
18483      * <br />Usage:
18484      * <pre><code>
18485 //All of these calls set the same date value (May 4, 2006)
18486
18487 //Pass a date object:
18488 var dt = new Date('5/4/06');
18489 monthField.setValue(dt);
18490
18491 //Pass a date string (default format):
18492 monthField.setValue('5/4/06');
18493
18494 //Pass a date string (custom format):
18495 monthField.format = 'Y-m-d';
18496 monthField.setValue('2006-5-4');
18497 </code></pre>
18498      * @param {String/Date} date The date or valid date string
18499      */
18500     setValue : function(date){
18501         Roo.log('month setValue' + date);
18502         // can only be first of month..
18503         
18504         var val = this.parseDate(date);
18505         
18506         if (this.hiddenField) {
18507             this.hiddenField.value = this.formatDate(this.parseDate(date), 'Y-m-d');
18508         }
18509         Roo.form.MonthField.superclass.setValue.call(this, this.formatDate(this.parseDate(date)));
18510         this.value = this.parseDate(date);
18511     },
18512
18513     // private
18514     parseDate : function(value){
18515         if(!value || value instanceof Date){
18516             value = value ? Date.parseDate(value.format('Y-m') + '-01', 'Y-m-d') : null;
18517             return value;
18518         }
18519         var v = Date.parseDate(value, this.format);
18520         if (!v && this.useIso) {
18521             v = Date.parseDate(value, 'Y-m-d');
18522         }
18523         if (v) {
18524             // 
18525             v = Date.parseDate(v.format('Y-m') +'-01', 'Y-m-d');
18526         }
18527         
18528         
18529         if(!v && this.altFormats){
18530             if(!this.altFormatsArray){
18531                 this.altFormatsArray = this.altFormats.split("|");
18532             }
18533             for(var i = 0, len = this.altFormatsArray.length; i < len && !v; i++){
18534                 v = Date.parseDate(value, this.altFormatsArray[i]);
18535             }
18536         }
18537         return v;
18538     },
18539
18540     // private
18541     formatDate : function(date, fmt){
18542         return (!date || !(date instanceof Date)) ?
18543                date : date.dateFormat(fmt || this.format);
18544     },
18545
18546     // private
18547     menuListeners : {
18548         select: function(m, d){
18549             this.setValue(d);
18550             this.fireEvent('select', this, d);
18551         },
18552         show : function(){ // retain focus styling
18553             this.onFocus();
18554         },
18555         hide : function(){
18556             this.focus.defer(10, this);
18557             var ml = this.menuListeners;
18558             this.menu.un("select", ml.select,  this);
18559             this.menu.un("show", ml.show,  this);
18560             this.menu.un("hide", ml.hide,  this);
18561         }
18562     },
18563     // private
18564     // Implements the default empty TriggerField.onTriggerClick function to display the DatePicker
18565     onTriggerClick : function(){
18566         if(this.disabled){
18567             return;
18568         }
18569         if(this.menu == null){
18570             this.menu = new Roo.menu.DateMenu();
18571            
18572         }
18573         
18574         Roo.apply(this.menu.picker,  {
18575             
18576             showClear: this.allowBlank,
18577             minDate : this.minValue,
18578             maxDate : this.maxValue,
18579             disabledDatesRE : this.ddMatch,
18580             disabledDatesText : this.disabledDatesText,
18581             
18582             format : this.useIso ? 'Y-m-d' : this.format,
18583             minText : String.format(this.minText, this.formatDate(this.minValue)),
18584             maxText : String.format(this.maxText, this.formatDate(this.maxValue))
18585             
18586         });
18587          this.menu.on(Roo.apply({}, this.menuListeners, {
18588             scope:this
18589         }));
18590        
18591         
18592         var m = this.menu;
18593         var p = m.picker;
18594         
18595         // hide month picker get's called when we called by 'before hide';
18596         
18597         var ignorehide = true;
18598         p.hideMonthPicker  = function(disableAnim){
18599             if (ignorehide) {
18600                 return;
18601             }
18602              if(this.monthPicker){
18603                 Roo.log("hideMonthPicker called");
18604                 if(disableAnim === true){
18605                     this.monthPicker.hide();
18606                 }else{
18607                     this.monthPicker.slideOut('t', {duration:.2});
18608                     p.setValue(new Date(m.picker.mpSelYear, m.picker.mpSelMonth, 1));
18609                     p.fireEvent("select", this, this.value);
18610                     m.hide();
18611                 }
18612             }
18613         }
18614         
18615         Roo.log('picker set value');
18616         Roo.log(this.getValue());
18617         p.setValue(this.getValue() ? this.parseDate(this.getValue()) : new Date());
18618         m.show(this.el, 'tl-bl?');
18619         ignorehide  = false;
18620         // this will trigger hideMonthPicker..
18621         
18622         
18623         // hidden the day picker
18624         Roo.select('.x-date-picker table', true).first().dom.style.visibility = "hidden";
18625         
18626         
18627         
18628       
18629         
18630         p.showMonthPicker.defer(100, p);
18631     
18632         
18633        
18634     },
18635
18636     beforeBlur : function(){
18637         var v = this.parseDate(this.getRawValue());
18638         if(v){
18639             this.setValue(v);
18640         }
18641     }
18642
18643     /** @cfg {Boolean} grow @hide */
18644     /** @cfg {Number} growMin @hide */
18645     /** @cfg {Number} growMax @hide */
18646     /**
18647      * @hide
18648      * @method autoSize
18649      */
18650 });/*
18651  * Based on:
18652  * Ext JS Library 1.1.1
18653  * Copyright(c) 2006-2007, Ext JS, LLC.
18654  *
18655  * Originally Released Under LGPL - original licence link has changed is not relivant.
18656  *
18657  * Fork - LGPL
18658  * <script type="text/javascript">
18659  */
18660  
18661
18662 /**
18663  * @class Roo.form.ComboBox
18664  * @extends Roo.form.TriggerField
18665  * A combobox control with support for autocomplete, remote-loading, paging and many other features.
18666  * @constructor
18667  * Create a new ComboBox.
18668  * @param {Object} config Configuration options
18669  */
18670 Roo.form.ComboBox = function(config){
18671     Roo.form.ComboBox.superclass.constructor.call(this, config);
18672     this.addEvents({
18673         /**
18674          * @event expand
18675          * Fires when the dropdown list is expanded
18676              * @param {Roo.form.ComboBox} combo This combo box
18677              */
18678         'expand' : true,
18679         /**
18680          * @event collapse
18681          * Fires when the dropdown list is collapsed
18682              * @param {Roo.form.ComboBox} combo This combo box
18683              */
18684         'collapse' : true,
18685         /**
18686          * @event beforeselect
18687          * Fires before a list item is selected. Return false to cancel the selection.
18688              * @param {Roo.form.ComboBox} combo This combo box
18689              * @param {Roo.data.Record} record The data record returned from the underlying store
18690              * @param {Number} index The index of the selected item in the dropdown list
18691              */
18692         'beforeselect' : true,
18693         /**
18694          * @event select
18695          * Fires when a list item is selected
18696              * @param {Roo.form.ComboBox} combo This combo box
18697              * @param {Roo.data.Record} record The data record returned from the underlying store (or false on clear)
18698              * @param {Number} index The index of the selected item in the dropdown list
18699              */
18700         'select' : true,
18701         /**
18702          * @event beforequery
18703          * Fires before all queries are processed. Return false to cancel the query or set cancel to true.
18704          * The event object passed has these properties:
18705              * @param {Roo.form.ComboBox} combo This combo box
18706              * @param {String} query The query
18707              * @param {Boolean} forceAll true to force "all" query
18708              * @param {Boolean} cancel true to cancel the query
18709              * @param {Object} e The query event object
18710              */
18711         'beforequery': true,
18712          /**
18713          * @event add
18714          * Fires when the 'add' icon is pressed (add a listener to enable add button)
18715              * @param {Roo.form.ComboBox} combo This combo box
18716              */
18717         'add' : true,
18718         /**
18719          * @event edit
18720          * Fires when the 'edit' icon is pressed (add a listener to enable add button)
18721              * @param {Roo.form.ComboBox} combo This combo box
18722              * @param {Roo.data.Record|false} record The data record returned from the underlying store (or false on nothing selected)
18723              */
18724         'edit' : true
18725         
18726         
18727     });
18728     if(this.transform){
18729         this.allowDomMove = false;
18730         var s = Roo.getDom(this.transform);
18731         if(!this.hiddenName){
18732             this.hiddenName = s.name;
18733         }
18734         if(!this.store){
18735             this.mode = 'local';
18736             var d = [], opts = s.options;
18737             for(var i = 0, len = opts.length;i < len; i++){
18738                 var o = opts[i];
18739                 var value = (Roo.isIE ? o.getAttributeNode('value').specified : o.hasAttribute('value')) ? o.value : o.text;
18740                 if(o.selected) {
18741                     this.value = value;
18742                 }
18743                 d.push([value, o.text]);
18744             }
18745             this.store = new Roo.data.SimpleStore({
18746                 'id': 0,
18747                 fields: ['value', 'text'],
18748                 data : d
18749             });
18750             this.valueField = 'value';
18751             this.displayField = 'text';
18752         }
18753         s.name = Roo.id(); // wipe out the name in case somewhere else they have a reference
18754         if(!this.lazyRender){
18755             this.target = true;
18756             this.el = Roo.DomHelper.insertBefore(s, this.autoCreate || this.defaultAutoCreate);
18757             s.parentNode.removeChild(s); // remove it
18758             this.render(this.el.parentNode);
18759         }else{
18760             s.parentNode.removeChild(s); // remove it
18761         }
18762
18763     }
18764     if (this.store) {
18765         this.store = Roo.factory(this.store, Roo.data);
18766     }
18767     
18768     this.selectedIndex = -1;
18769     if(this.mode == 'local'){
18770         if(config.queryDelay === undefined){
18771             this.queryDelay = 10;
18772         }
18773         if(config.minChars === undefined){
18774             this.minChars = 0;
18775         }
18776     }
18777 };
18778
18779 Roo.extend(Roo.form.ComboBox, Roo.form.TriggerField, {
18780     /**
18781      * @cfg {String/HTMLElement/Element} transform The id, DOM node or element of an existing select to convert to a ComboBox
18782      */
18783     /**
18784      * @cfg {Boolean} lazyRender True to prevent the ComboBox from rendering until requested (should always be used when
18785      * rendering into an Roo.Editor, defaults to false)
18786      */
18787     /**
18788      * @cfg {Boolean/Object} autoCreate A DomHelper element spec, or true for a default element spec (defaults to:
18789      * {tag: "input", type: "text", size: "24", autocomplete: "off"})
18790      */
18791     /**
18792      * @cfg {Roo.data.Store} store The data store to which this combo is bound (defaults to undefined)
18793      */
18794     /**
18795      * @cfg {String} title If supplied, a header element is created containing this text and added into the top of
18796      * the dropdown list (defaults to undefined, with no header element)
18797      */
18798
18799      /**
18800      * @cfg {String/Roo.Template} tpl The template to use to render the output
18801      */
18802      
18803     // private
18804     defaultAutoCreate : {tag: "input", type: "text", size: "24", autocomplete: "off"},
18805     /**
18806      * @cfg {Number} listWidth The width in pixels of the dropdown list (defaults to the width of the ComboBox field)
18807      */
18808     listWidth: undefined,
18809     /**
18810      * @cfg {String} displayField The underlying data field name to bind to this CombBox (defaults to undefined if
18811      * mode = 'remote' or 'text' if mode = 'local')
18812      */
18813     displayField: undefined,
18814     /**
18815      * @cfg {String} valueField The underlying data value name to bind to this CombBox (defaults to undefined if
18816      * mode = 'remote' or 'value' if mode = 'local'). 
18817      * Note: use of a valueField requires the user make a selection
18818      * in order for a value to be mapped.
18819      */
18820     valueField: undefined,
18821     
18822     
18823     /**
18824      * @cfg {String} hiddenName If specified, a hidden form field with this name is dynamically generated to store the
18825      * field's data value (defaults to the underlying DOM element's name)
18826      */
18827     hiddenName: undefined,
18828     /**
18829      * @cfg {String} listClass CSS class to apply to the dropdown list element (defaults to '')
18830      */
18831     listClass: '',
18832     /**
18833      * @cfg {String} selectedClass CSS class to apply to the selected item in the dropdown list (defaults to 'x-combo-selected')
18834      */
18835     selectedClass: 'x-combo-selected',
18836     /**
18837      * @cfg {String} triggerClass An additional CSS class used to style the trigger button.  The trigger will always get the
18838      * class 'x-form-trigger' and triggerClass will be <b>appended</b> if specified (defaults to 'x-form-arrow-trigger'
18839      * which displays a downward arrow icon).
18840      */
18841     triggerClass : 'x-form-arrow-trigger',
18842     /**
18843      * @cfg {Boolean/String} shadow True or "sides" for the default effect, "frame" for 4-way shadow, and "drop" for bottom-right
18844      */
18845     shadow:'sides',
18846     /**
18847      * @cfg {String} listAlign A valid anchor position value. See {@link Roo.Element#alignTo} for details on supported
18848      * anchor positions (defaults to 'tl-bl')
18849      */
18850     listAlign: 'tl-bl?',
18851     /**
18852      * @cfg {Number} maxHeight The maximum height in pixels of the dropdown list before scrollbars are shown (defaults to 300)
18853      */
18854     maxHeight: 300,
18855     /**
18856      * @cfg {String} triggerAction The action to execute when the trigger field is activated.  Use 'all' to run the
18857      * query specified by the allQuery config option (defaults to 'query')
18858      */
18859     triggerAction: 'query',
18860     /**
18861      * @cfg {Number} minChars The minimum number of characters the user must type before autocomplete and typeahead activate
18862      * (defaults to 4, does not apply if editable = false)
18863      */
18864     minChars : 4,
18865     /**
18866      * @cfg {Boolean} typeAhead True to populate and autoselect the remainder of the text being typed after a configurable
18867      * delay (typeAheadDelay) if it matches a known value (defaults to false)
18868      */
18869     typeAhead: false,
18870     /**
18871      * @cfg {Number} queryDelay The length of time in milliseconds to delay between the start of typing and sending the
18872      * query to filter the dropdown list (defaults to 500 if mode = 'remote' or 10 if mode = 'local')
18873      */
18874     queryDelay: 500,
18875     /**
18876      * @cfg {Number} pageSize If greater than 0, a paging toolbar is displayed in the footer of the dropdown list and the
18877      * filter queries will execute with page start and limit parameters.  Only applies when mode = 'remote' (defaults to 0)
18878      */
18879     pageSize: 0,
18880     /**
18881      * @cfg {Boolean} selectOnFocus True to select any existing text in the field immediately on focus.  Only applies
18882      * when editable = true (defaults to false)
18883      */
18884     selectOnFocus:false,
18885     /**
18886      * @cfg {String} queryParam Name of the query as it will be passed on the querystring (defaults to 'query')
18887      */
18888     queryParam: 'query',
18889     /**
18890      * @cfg {String} loadingText The text to display in the dropdown list while data is loading.  Only applies
18891      * when mode = 'remote' (defaults to 'Loading...')
18892      */
18893     loadingText: 'Loading...',
18894     /**
18895      * @cfg {Boolean} resizable True to add a resize handle to the bottom of the dropdown list (defaults to false)
18896      */
18897     resizable: false,
18898     /**
18899      * @cfg {Number} handleHeight The height in pixels of the dropdown list resize handle if resizable = true (defaults to 8)
18900      */
18901     handleHeight : 8,
18902     /**
18903      * @cfg {Boolean} editable False to prevent the user from typing text directly into the field, just like a
18904      * traditional select (defaults to true)
18905      */
18906     editable: true,
18907     /**
18908      * @cfg {String} allQuery The text query to send to the server to return all records for the list with no filtering (defaults to '')
18909      */
18910     allQuery: '',
18911     /**
18912      * @cfg {String} mode Set to 'local' if the ComboBox loads local data (defaults to 'remote' which loads from the server)
18913      */
18914     mode: 'remote',
18915     /**
18916      * @cfg {Number} minListWidth The minimum width of the dropdown list in pixels (defaults to 70, will be ignored if
18917      * listWidth has a higher value)
18918      */
18919     minListWidth : 70,
18920     /**
18921      * @cfg {Boolean} forceSelection True to restrict the selected value to one of the values in the list, false to
18922      * allow the user to set arbitrary text into the field (defaults to false)
18923      */
18924     forceSelection:false,
18925     /**
18926      * @cfg {Number} typeAheadDelay The length of time in milliseconds to wait until the typeahead text is displayed
18927      * if typeAhead = true (defaults to 250)
18928      */
18929     typeAheadDelay : 250,
18930     /**
18931      * @cfg {String} valueNotFoundText When using a name/value combo, if the value passed to setValue is not found in
18932      * the store, valueNotFoundText will be displayed as the field text if defined (defaults to undefined)
18933      */
18934     valueNotFoundText : undefined,
18935     /**
18936      * @cfg {Boolean} blockFocus Prevents all focus calls, so it can work with things like HTML edtor bar
18937      */
18938     blockFocus : false,
18939     
18940     /**
18941      * @cfg {Boolean} disableClear Disable showing of clear button.
18942      */
18943     disableClear : false,
18944     /**
18945      * @cfg {Boolean} alwaysQuery  Disable caching of results, and always send query
18946      */
18947     alwaysQuery : false,
18948     
18949     //private
18950     addicon : false,
18951     editicon: false,
18952     
18953     // element that contains real text value.. (when hidden is used..)
18954      
18955     // private
18956     onRender : function(ct, position)
18957     {
18958         Roo.form.ComboBox.superclass.onRender.call(this, ct, position);
18959         
18960         if(this.hiddenName){
18961             this.hiddenField = this.el.insertSibling({tag:'input', type:'hidden', name: this.hiddenName, id:  (this.hiddenId||this.hiddenName)},
18962                     'before', true);
18963             this.hiddenField.value =
18964                 this.hiddenValue !== undefined ? this.hiddenValue :
18965                 this.value !== undefined ? this.value : '';
18966
18967             // prevent input submission
18968             this.el.dom.removeAttribute('name');
18969              
18970              
18971         }
18972         
18973         if(Roo.isGecko){
18974             this.el.dom.setAttribute('autocomplete', 'off');
18975         }
18976
18977         var cls = 'x-combo-list';
18978
18979         this.list = new Roo.Layer({
18980             shadow: this.shadow, cls: [cls, this.listClass].join(' '), constrain:false
18981         });
18982
18983         var lw = this.listWidth || Math.max(this.wrap.getWidth(), this.minListWidth);
18984         this.list.setWidth(lw);
18985         this.list.swallowEvent('mousewheel');
18986         this.assetHeight = 0;
18987
18988         if(this.title){
18989             this.header = this.list.createChild({cls:cls+'-hd', html: this.title});
18990             this.assetHeight += this.header.getHeight();
18991         }
18992
18993         this.innerList = this.list.createChild({cls:cls+'-inner'});
18994         this.innerList.on('mouseover', this.onViewOver, this);
18995         this.innerList.on('mousemove', this.onViewMove, this);
18996         this.innerList.setWidth(lw - this.list.getFrameWidth('lr'));
18997         
18998         if(this.allowBlank && !this.pageSize && !this.disableClear){
18999             this.footer = this.list.createChild({cls:cls+'-ft'});
19000             this.pageTb = new Roo.Toolbar(this.footer);
19001            
19002         }
19003         if(this.pageSize){
19004             this.footer = this.list.createChild({cls:cls+'-ft'});
19005             this.pageTb = new Roo.PagingToolbar(this.footer, this.store,
19006                     {pageSize: this.pageSize});
19007             
19008         }
19009         
19010         if (this.pageTb && this.allowBlank && !this.disableClear) {
19011             var _this = this;
19012             this.pageTb.add(new Roo.Toolbar.Fill(), {
19013                 cls: 'x-btn-icon x-btn-clear',
19014                 text: '&#160;',
19015                 handler: function()
19016                 {
19017                     _this.collapse();
19018                     _this.clearValue();
19019                     _this.onSelect(false, -1);
19020                 }
19021             });
19022         }
19023         if (this.footer) {
19024             this.assetHeight += this.footer.getHeight();
19025         }
19026         
19027
19028         if(!this.tpl){
19029             this.tpl = '<div class="'+cls+'-item">{' + this.displayField + '}</div>';
19030         }
19031
19032         this.view = new Roo.View(this.innerList, this.tpl, {
19033             singleSelect:true,
19034             store: this.store,
19035             selectedClass: this.selectedClass
19036         });
19037
19038         this.view.on('click', this.onViewClick, this);
19039
19040         this.store.on('beforeload', this.onBeforeLoad, this);
19041         this.store.on('load', this.onLoad, this);
19042         this.store.on('loadexception', this.onLoadException, this);
19043
19044         if(this.resizable){
19045             this.resizer = new Roo.Resizable(this.list,  {
19046                pinned:true, handles:'se'
19047             });
19048             this.resizer.on('resize', function(r, w, h){
19049                 this.maxHeight = h-this.handleHeight-this.list.getFrameWidth('tb')-this.assetHeight;
19050                 this.listWidth = w;
19051                 this.innerList.setWidth(w - this.list.getFrameWidth('lr'));
19052                 this.restrictHeight();
19053             }, this);
19054             this[this.pageSize?'footer':'innerList'].setStyle('margin-bottom', this.handleHeight+'px');
19055         }
19056         if(!this.editable){
19057             this.editable = true;
19058             this.setEditable(false);
19059         }  
19060         
19061         
19062         if (typeof(this.events.add.listeners) != 'undefined') {
19063             
19064             this.addicon = this.wrap.createChild(
19065                 {tag: 'img', src: Roo.BLANK_IMAGE_URL, cls: 'x-form-combo-add' });  
19066        
19067             this.addicon.on('click', function(e) {
19068                 this.fireEvent('add', this);
19069             }, this);
19070         }
19071         if (typeof(this.events.edit.listeners) != 'undefined') {
19072             
19073             this.editicon = this.wrap.createChild(
19074                 {tag: 'img', src: Roo.BLANK_IMAGE_URL, cls: 'x-form-combo-edit' });  
19075             if (this.addicon) {
19076                 this.editicon.setStyle('margin-left', '40px');
19077             }
19078             this.editicon.on('click', function(e) {
19079                 
19080                 // we fire even  if inothing is selected..
19081                 this.fireEvent('edit', this, this.lastData );
19082                 
19083             }, this);
19084         }
19085         
19086         
19087         
19088     },
19089
19090     // private
19091     initEvents : function(){
19092         Roo.form.ComboBox.superclass.initEvents.call(this);
19093
19094         this.keyNav = new Roo.KeyNav(this.el, {
19095             "up" : function(e){
19096                 this.inKeyMode = true;
19097                 this.selectPrev();
19098             },
19099
19100             "down" : function(e){
19101                 if(!this.isExpanded()){
19102                     this.onTriggerClick();
19103                 }else{
19104                     this.inKeyMode = true;
19105                     this.selectNext();
19106                 }
19107             },
19108
19109             "enter" : function(e){
19110                 this.onViewClick();
19111                 //return true;
19112             },
19113
19114             "esc" : function(e){
19115                 this.collapse();
19116             },
19117
19118             "tab" : function(e){
19119                 this.onViewClick(false);
19120                 this.fireEvent("specialkey", this, e);
19121                 return true;
19122             },
19123
19124             scope : this,
19125
19126             doRelay : function(foo, bar, hname){
19127                 if(hname == 'down' || this.scope.isExpanded()){
19128                    return Roo.KeyNav.prototype.doRelay.apply(this, arguments);
19129                 }
19130                 return true;
19131             },
19132
19133             forceKeyDown: true
19134         });
19135         this.queryDelay = Math.max(this.queryDelay || 10,
19136                 this.mode == 'local' ? 10 : 250);
19137         this.dqTask = new Roo.util.DelayedTask(this.initQuery, this);
19138         if(this.typeAhead){
19139             this.taTask = new Roo.util.DelayedTask(this.onTypeAhead, this);
19140         }
19141         if(this.editable !== false){
19142             this.el.on("keyup", this.onKeyUp, this);
19143         }
19144         if(this.forceSelection){
19145             this.on('blur', this.doForce, this);
19146         }
19147     },
19148
19149     onDestroy : function(){
19150         if(this.view){
19151             this.view.setStore(null);
19152             this.view.el.removeAllListeners();
19153             this.view.el.remove();
19154             this.view.purgeListeners();
19155         }
19156         if(this.list){
19157             this.list.destroy();
19158         }
19159         if(this.store){
19160             this.store.un('beforeload', this.onBeforeLoad, this);
19161             this.store.un('load', this.onLoad, this);
19162             this.store.un('loadexception', this.onLoadException, this);
19163         }
19164         Roo.form.ComboBox.superclass.onDestroy.call(this);
19165     },
19166
19167     // private
19168     fireKey : function(e){
19169         if(e.isNavKeyPress() && !this.list.isVisible()){
19170             this.fireEvent("specialkey", this, e);
19171         }
19172     },
19173
19174     // private
19175     onResize: function(w, h){
19176         Roo.form.ComboBox.superclass.onResize.apply(this, arguments);
19177         
19178         if(typeof w != 'number'){
19179             // we do not handle it!?!?
19180             return;
19181         }
19182         var tw = this.trigger.getWidth();
19183         tw += this.addicon ? this.addicon.getWidth() : 0;
19184         tw += this.editicon ? this.editicon.getWidth() : 0;
19185         var x = w - tw;
19186         this.el.setWidth( this.adjustWidth('input', x));
19187             
19188         this.trigger.setStyle('left', x+'px');
19189         
19190         if(this.list && this.listWidth === undefined){
19191             var lw = Math.max(x + this.trigger.getWidth(), this.minListWidth);
19192             this.list.setWidth(lw);
19193             this.innerList.setWidth(lw - this.list.getFrameWidth('lr'));
19194         }
19195         
19196     
19197         
19198     },
19199
19200     /**
19201      * Allow or prevent the user from directly editing the field text.  If false is passed,
19202      * the user will only be able to select from the items defined in the dropdown list.  This method
19203      * is the runtime equivalent of setting the 'editable' config option at config time.
19204      * @param {Boolean} value True to allow the user to directly edit the field text
19205      */
19206     setEditable : function(value){
19207         if(value == this.editable){
19208             return;
19209         }
19210         this.editable = value;
19211         if(!value){
19212             this.el.dom.setAttribute('readOnly', true);
19213             this.el.on('mousedown', this.onTriggerClick,  this);
19214             this.el.addClass('x-combo-noedit');
19215         }else{
19216             this.el.dom.setAttribute('readOnly', false);
19217             this.el.un('mousedown', this.onTriggerClick,  this);
19218             this.el.removeClass('x-combo-noedit');
19219         }
19220     },
19221
19222     // private
19223     onBeforeLoad : function(){
19224         if(!this.hasFocus){
19225             return;
19226         }
19227         this.innerList.update(this.loadingText ?
19228                '<div class="loading-indicator">'+this.loadingText+'</div>' : '');
19229         this.restrictHeight();
19230         this.selectedIndex = -1;
19231     },
19232
19233     // private
19234     onLoad : function(){
19235         if(!this.hasFocus){
19236             return;
19237         }
19238         if(this.store.getCount() > 0){
19239             this.expand();
19240             this.restrictHeight();
19241             if(this.lastQuery == this.allQuery){
19242                 if(this.editable){
19243                     this.el.dom.select();
19244                 }
19245                 if(!this.selectByValue(this.value, true)){
19246                     this.select(0, true);
19247                 }
19248             }else{
19249                 this.selectNext();
19250                 if(this.typeAhead && this.lastKey != Roo.EventObject.BACKSPACE && this.lastKey != Roo.EventObject.DELETE){
19251                     this.taTask.delay(this.typeAheadDelay);
19252                 }
19253             }
19254         }else{
19255             this.onEmptyResults();
19256         }
19257         //this.el.focus();
19258     },
19259     // private
19260     onLoadException : function()
19261     {
19262         this.collapse();
19263         Roo.log(this.store.reader.jsonData);
19264         if (this.store && typeof(this.store.reader.jsonData.errorMsg) != 'undefined') {
19265             Roo.MessageBox.alert("Error loading",this.store.reader.jsonData.errorMsg);
19266         }
19267         
19268         
19269     },
19270     // private
19271     onTypeAhead : function(){
19272         if(this.store.getCount() > 0){
19273             var r = this.store.getAt(0);
19274             var newValue = r.data[this.displayField];
19275             var len = newValue.length;
19276             var selStart = this.getRawValue().length;
19277             if(selStart != len){
19278                 this.setRawValue(newValue);
19279                 this.selectText(selStart, newValue.length);
19280             }
19281         }
19282     },
19283
19284     // private
19285     onSelect : function(record, index){
19286         if(this.fireEvent('beforeselect', this, record, index) !== false){
19287             this.setFromData(index > -1 ? record.data : false);
19288             this.collapse();
19289             this.fireEvent('select', this, record, index);
19290         }
19291     },
19292
19293     /**
19294      * Returns the currently selected field value or empty string if no value is set.
19295      * @return {String} value The selected value
19296      */
19297     getValue : function(){
19298         if(this.valueField){
19299             return typeof this.value != 'undefined' ? this.value : '';
19300         }
19301         return Roo.form.ComboBox.superclass.getValue.call(this);
19302     },
19303
19304     /**
19305      * Clears any text/value currently set in the field
19306      */
19307     clearValue : function(){
19308         if(this.hiddenField){
19309             this.hiddenField.value = '';
19310         }
19311         this.value = '';
19312         this.setRawValue('');
19313         this.lastSelectionText = '';
19314         
19315     },
19316
19317     /**
19318      * Sets the specified value into the field.  If the value finds a match, the corresponding record text
19319      * will be displayed in the field.  If the value does not match the data value of an existing item,
19320      * and the valueNotFoundText config option is defined, it will be displayed as the default field text.
19321      * Otherwise the field will be blank (although the value will still be set).
19322      * @param {String} value The value to match
19323      */
19324     setValue : function(v){
19325         var text = v;
19326         if(this.valueField){
19327             var r = this.findRecord(this.valueField, v);
19328             if(r){
19329                 text = r.data[this.displayField];
19330             }else if(this.valueNotFoundText !== undefined){
19331                 text = this.valueNotFoundText;
19332             }
19333         }
19334         this.lastSelectionText = text;
19335         if(this.hiddenField){
19336             this.hiddenField.value = v;
19337         }
19338         Roo.form.ComboBox.superclass.setValue.call(this, text);
19339         this.value = v;
19340     },
19341     /**
19342      * @property {Object} the last set data for the element
19343      */
19344     
19345     lastData : false,
19346     /**
19347      * Sets the value of the field based on a object which is related to the record format for the store.
19348      * @param {Object} value the value to set as. or false on reset?
19349      */
19350     setFromData : function(o){
19351         var dv = ''; // display value
19352         var vv = ''; // value value..
19353         this.lastData = o;
19354         if (this.displayField) {
19355             dv = !o || typeof(o[this.displayField]) == 'undefined' ? '' : o[this.displayField];
19356         } else {
19357             // this is an error condition!!!
19358             Roo.log('no  displayField value set for '+ (this.name ? this.name : this.id));
19359         }
19360         
19361         if(this.valueField){
19362             vv = !o || typeof(o[this.valueField]) == 'undefined' ? dv : o[this.valueField];
19363         }
19364         if(this.hiddenField){
19365             this.hiddenField.value = vv;
19366             
19367             this.lastSelectionText = dv;
19368             Roo.form.ComboBox.superclass.setValue.call(this, dv);
19369             this.value = vv;
19370             return;
19371         }
19372         // no hidden field.. - we store the value in 'value', but still display
19373         // display field!!!!
19374         this.lastSelectionText = dv;
19375         Roo.form.ComboBox.superclass.setValue.call(this, dv);
19376         this.value = vv;
19377         
19378         
19379     },
19380     // private
19381     reset : function(){
19382         // overridden so that last data is reset..
19383         this.setValue(this.resetValue);
19384         this.originalValue = this.getValue();
19385         this.clearInvalid();
19386         this.lastData = false;
19387         if (this.view) {
19388             this.view.clearSelections();
19389         }
19390     },
19391     // private
19392     findRecord : function(prop, value){
19393         var record;
19394         if(this.store.getCount() > 0){
19395             this.store.each(function(r){
19396                 if(r.data[prop] == value){
19397                     record = r;
19398                     return false;
19399                 }
19400                 return true;
19401             });
19402         }
19403         return record;
19404     },
19405     
19406     getName: function()
19407     {
19408         // returns hidden if it's set..
19409         if (!this.rendered) {return ''};
19410         return !this.hiddenName && this.el.dom.name  ? this.el.dom.name : (this.hiddenName || '');
19411         
19412     },
19413     // private
19414     onViewMove : function(e, t){
19415         this.inKeyMode = false;
19416     },
19417
19418     // private
19419     onViewOver : function(e, t){
19420         if(this.inKeyMode){ // prevent key nav and mouse over conflicts
19421             return;
19422         }
19423         var item = this.view.findItemFromChild(t);
19424         if(item){
19425             var index = this.view.indexOf(item);
19426             this.select(index, false);
19427         }
19428     },
19429
19430     // private
19431     onViewClick : function(doFocus)
19432     {
19433         var index = this.view.getSelectedIndexes()[0];
19434         var r = this.store.getAt(index);
19435         if(r){
19436             this.onSelect(r, index);
19437         }
19438         if(doFocus !== false && !this.blockFocus){
19439             this.el.focus();
19440         }
19441     },
19442
19443     // private
19444     restrictHeight : function(){
19445         this.innerList.dom.style.height = '';
19446         var inner = this.innerList.dom;
19447         var h = Math.max(inner.clientHeight, inner.offsetHeight, inner.scrollHeight);
19448         this.innerList.setHeight(h < this.maxHeight ? 'auto' : this.maxHeight);
19449         this.list.beginUpdate();
19450         this.list.setHeight(this.innerList.getHeight()+this.list.getFrameWidth('tb')+(this.resizable?this.handleHeight:0)+this.assetHeight);
19451         this.list.alignTo(this.el, this.listAlign);
19452         this.list.endUpdate();
19453     },
19454
19455     // private
19456     onEmptyResults : function(){
19457         this.collapse();
19458     },
19459
19460     /**
19461      * Returns true if the dropdown list is expanded, else false.
19462      */
19463     isExpanded : function(){
19464         return this.list.isVisible();
19465     },
19466
19467     /**
19468      * Select an item in the dropdown list by its data value. This function does NOT cause the select event to fire.
19469      * The store must be loaded and the list expanded for this function to work, otherwise use setValue.
19470      * @param {String} value The data value of the item to select
19471      * @param {Boolean} scrollIntoView False to prevent the dropdown list from autoscrolling to display the
19472      * selected item if it is not currently in view (defaults to true)
19473      * @return {Boolean} True if the value matched an item in the list, else false
19474      */
19475     selectByValue : function(v, scrollIntoView){
19476         if(v !== undefined && v !== null){
19477             var r = this.findRecord(this.valueField || this.displayField, v);
19478             if(r){
19479                 this.select(this.store.indexOf(r), scrollIntoView);
19480                 return true;
19481             }
19482         }
19483         return false;
19484     },
19485
19486     /**
19487      * Select an item in the dropdown list by its numeric index in the list. This function does NOT cause the select event to fire.
19488      * The store must be loaded and the list expanded for this function to work, otherwise use setValue.
19489      * @param {Number} index The zero-based index of the list item to select
19490      * @param {Boolean} scrollIntoView False to prevent the dropdown list from autoscrolling to display the
19491      * selected item if it is not currently in view (defaults to true)
19492      */
19493     select : function(index, scrollIntoView){
19494         this.selectedIndex = index;
19495         this.view.select(index);
19496         if(scrollIntoView !== false){
19497             var el = this.view.getNode(index);
19498             if(el){
19499                 this.innerList.scrollChildIntoView(el, false);
19500             }
19501         }
19502     },
19503
19504     // private
19505     selectNext : function(){
19506         var ct = this.store.getCount();
19507         if(ct > 0){
19508             if(this.selectedIndex == -1){
19509                 this.select(0);
19510             }else if(this.selectedIndex < ct-1){
19511                 this.select(this.selectedIndex+1);
19512             }
19513         }
19514     },
19515
19516     // private
19517     selectPrev : function(){
19518         var ct = this.store.getCount();
19519         if(ct > 0){
19520             if(this.selectedIndex == -1){
19521                 this.select(0);
19522             }else if(this.selectedIndex != 0){
19523                 this.select(this.selectedIndex-1);
19524             }
19525         }
19526     },
19527
19528     // private
19529     onKeyUp : function(e){
19530         if(this.editable !== false && !e.isSpecialKey()){
19531             this.lastKey = e.getKey();
19532             this.dqTask.delay(this.queryDelay);
19533         }
19534     },
19535
19536     // private
19537     validateBlur : function(){
19538         return !this.list || !this.list.isVisible();   
19539     },
19540
19541     // private
19542     initQuery : function(){
19543         this.doQuery(this.getRawValue());
19544     },
19545
19546     // private
19547     doForce : function(){
19548         if(this.el.dom.value.length > 0){
19549             this.el.dom.value =
19550                 this.lastSelectionText === undefined ? '' : this.lastSelectionText;
19551              
19552         }
19553     },
19554
19555     /**
19556      * Execute a query to filter the dropdown list.  Fires the beforequery event prior to performing the
19557      * query allowing the query action to be canceled if needed.
19558      * @param {String} query The SQL query to execute
19559      * @param {Boolean} forceAll True to force the query to execute even if there are currently fewer characters
19560      * in the field than the minimum specified by the minChars config option.  It also clears any filter previously
19561      * saved in the current store (defaults to false)
19562      */
19563     doQuery : function(q, forceAll){
19564         if(q === undefined || q === null){
19565             q = '';
19566         }
19567         var qe = {
19568             query: q,
19569             forceAll: forceAll,
19570             combo: this,
19571             cancel:false
19572         };
19573         if(this.fireEvent('beforequery', qe)===false || qe.cancel){
19574             return false;
19575         }
19576         q = qe.query;
19577         forceAll = qe.forceAll;
19578         if(forceAll === true || (q.length >= this.minChars)){
19579             if(this.lastQuery != q || this.alwaysQuery){
19580                 this.lastQuery = q;
19581                 if(this.mode == 'local'){
19582                     this.selectedIndex = -1;
19583                     if(forceAll){
19584                         this.store.clearFilter();
19585                     }else{
19586                         this.store.filter(this.displayField, q);
19587                     }
19588                     this.onLoad();
19589                 }else{
19590                     this.store.baseParams[this.queryParam] = q;
19591                     this.store.load({
19592                         params: this.getParams(q)
19593                     });
19594                     this.expand();
19595                 }
19596             }else{
19597                 this.selectedIndex = -1;
19598                 this.onLoad();   
19599             }
19600         }
19601     },
19602
19603     // private
19604     getParams : function(q){
19605         var p = {};
19606         //p[this.queryParam] = q;
19607         if(this.pageSize){
19608             p.start = 0;
19609             p.limit = this.pageSize;
19610         }
19611         return p;
19612     },
19613
19614     /**
19615      * Hides the dropdown list if it is currently expanded. Fires the 'collapse' event on completion.
19616      */
19617     collapse : function(){
19618         if(!this.isExpanded()){
19619             return;
19620         }
19621         this.list.hide();
19622         Roo.get(document).un('mousedown', this.collapseIf, this);
19623         Roo.get(document).un('mousewheel', this.collapseIf, this);
19624         if (!this.editable) {
19625             Roo.get(document).un('keydown', this.listKeyPress, this);
19626         }
19627         this.fireEvent('collapse', this);
19628     },
19629
19630     // private
19631     collapseIf : function(e){
19632         if(!e.within(this.wrap) && !e.within(this.list)){
19633             this.collapse();
19634         }
19635     },
19636
19637     /**
19638      * Expands the dropdown list if it is currently hidden. Fires the 'expand' event on completion.
19639      */
19640     expand : function(){
19641         if(this.isExpanded() || !this.hasFocus){
19642             return;
19643         }
19644         this.list.alignTo(this.el, this.listAlign);
19645         this.list.show();
19646         Roo.get(document).on('mousedown', this.collapseIf, this);
19647         Roo.get(document).on('mousewheel', this.collapseIf, this);
19648         if (!this.editable) {
19649             Roo.get(document).on('keydown', this.listKeyPress, this);
19650         }
19651         
19652         this.fireEvent('expand', this);
19653     },
19654
19655     // private
19656     // Implements the default empty TriggerField.onTriggerClick function
19657     onTriggerClick : function(){
19658         if(this.disabled){
19659             return;
19660         }
19661         if(this.isExpanded()){
19662             this.collapse();
19663             if (!this.blockFocus) {
19664                 this.el.focus();
19665             }
19666             
19667         }else {
19668             this.hasFocus = true;
19669             if(this.triggerAction == 'all') {
19670                 this.doQuery(this.allQuery, true);
19671             } else {
19672                 this.doQuery(this.getRawValue());
19673             }
19674             if (!this.blockFocus) {
19675                 this.el.focus();
19676             }
19677         }
19678     },
19679     listKeyPress : function(e)
19680     {
19681         //Roo.log('listkeypress');
19682         // scroll to first matching element based on key pres..
19683         if (e.isSpecialKey()) {
19684             return false;
19685         }
19686         var k = String.fromCharCode(e.getKey()).toUpperCase();
19687         //Roo.log(k);
19688         var match  = false;
19689         var csel = this.view.getSelectedNodes();
19690         var cselitem = false;
19691         if (csel.length) {
19692             var ix = this.view.indexOf(csel[0]);
19693             cselitem  = this.store.getAt(ix);
19694             if (!cselitem.get(this.displayField) || cselitem.get(this.displayField).substring(0,1).toUpperCase() != k) {
19695                 cselitem = false;
19696             }
19697             
19698         }
19699         
19700         this.store.each(function(v) { 
19701             if (cselitem) {
19702                 // start at existing selection.
19703                 if (cselitem.id == v.id) {
19704                     cselitem = false;
19705                 }
19706                 return;
19707             }
19708                 
19709             if (v.get(this.displayField) && v.get(this.displayField).substring(0,1).toUpperCase() == k) {
19710                 match = this.store.indexOf(v);
19711                 return false;
19712             }
19713         }, this);
19714         
19715         if (match === false) {
19716             return true; // no more action?
19717         }
19718         // scroll to?
19719         this.view.select(match);
19720         var sn = Roo.get(this.view.getSelectedNodes()[0]);
19721         sn.scrollIntoView(sn.dom.parentNode, false);
19722     } 
19723
19724     /** 
19725     * @cfg {Boolean} grow 
19726     * @hide 
19727     */
19728     /** 
19729     * @cfg {Number} growMin 
19730     * @hide 
19731     */
19732     /** 
19733     * @cfg {Number} growMax 
19734     * @hide 
19735     */
19736     /**
19737      * @hide
19738      * @method autoSize
19739      */
19740 });/*
19741  * Copyright(c) 2010-2012, Roo J Solutions Limited
19742  *
19743  * Licence LGPL
19744  *
19745  */
19746
19747 /**
19748  * @class Roo.form.ComboBoxArray
19749  * @extends Roo.form.TextField
19750  * A facebook style adder... for lists of email / people / countries  etc...
19751  * pick multiple items from a combo box, and shows each one.
19752  *
19753  *  Fred [x]  Brian [x]  [Pick another |v]
19754  *
19755  *
19756  *  For this to work: it needs various extra information
19757  *    - normal combo problay has
19758  *      name, hiddenName
19759  *    + displayField, valueField
19760  *
19761  *    For our purpose...
19762  *
19763  *
19764  *   If we change from 'extends' to wrapping...
19765  *   
19766  *  
19767  *
19768  
19769  
19770  * @constructor
19771  * Create a new ComboBoxArray.
19772  * @param {Object} config Configuration options
19773  */
19774  
19775
19776 Roo.form.ComboBoxArray = function(config)
19777 {
19778     this.addEvents({
19779         /**
19780          * @event beforeremove
19781          * Fires before remove the value from the list
19782              * @param {Roo.form.ComboBoxArray} _self This combo box array
19783              * @param {Roo.form.ComboBoxArray.Item} item removed item
19784              */
19785         'beforeremove' : true,
19786         /**
19787          * @event remove
19788          * Fires when remove the value from the list
19789              * @param {Roo.form.ComboBoxArray} _self This combo box array
19790              * @param {Roo.form.ComboBoxArray.Item} item removed item
19791              */
19792         'remove' : true
19793         
19794         
19795     });
19796     
19797     Roo.form.ComboBoxArray.superclass.constructor.call(this, config);
19798     
19799     this.items = new Roo.util.MixedCollection(false);
19800     
19801     // construct the child combo...
19802     
19803     
19804     
19805     
19806    
19807     
19808 }
19809
19810  
19811 Roo.extend(Roo.form.ComboBoxArray, Roo.form.TextField,
19812
19813     /**
19814      * @cfg {Roo.form.Combo} combo The combo box that is wrapped
19815      */
19816     
19817     lastData : false,
19818     
19819     // behavies liek a hiddne field
19820     inputType:      'hidden',
19821     /**
19822      * @cfg {Number} width The width of the box that displays the selected element
19823      */ 
19824     width:          300,
19825
19826     
19827     
19828     /**
19829      * @cfg {String} name    The name of the visable items on this form (eg. titles not ids)
19830      */
19831     name : false,
19832     /**
19833      * @cfg {String} hiddenName    The hidden name of the field, often contains an comma seperated list of names
19834      */
19835     hiddenName : false,
19836       /**
19837      * @cfg {String} seperator    The value seperator normally ',' 
19838      */
19839     seperator : ',',
19840     
19841     // private the array of items that are displayed..
19842     items  : false,
19843     // private - the hidden field el.
19844     hiddenEl : false,
19845     // private - the filed el..
19846     el : false,
19847     
19848     //validateValue : function() { return true; }, // all values are ok!
19849     //onAddClick: function() { },
19850     
19851     onRender : function(ct, position) 
19852     {
19853         
19854         // create the standard hidden element
19855         //Roo.form.ComboBoxArray.superclass.onRender.call(this, ct, position);
19856         
19857         
19858         // give fake names to child combo;
19859         this.combo.hiddenName = this.hiddenName ? (this.hiddenName+'-subcombo') : this.hiddenName;
19860         this.combo.name = this.name ? (this.name+'-subcombo') : this.name;
19861         
19862         this.combo = Roo.factory(this.combo, Roo.form);
19863         this.combo.onRender(ct, position);
19864         if (typeof(this.combo.width) != 'undefined') {
19865             this.combo.onResize(this.combo.width,0);
19866         }
19867         
19868         this.combo.initEvents();
19869         
19870         // assigned so form know we need to do this..
19871         this.store          = this.combo.store;
19872         this.valueField     = this.combo.valueField;
19873         this.displayField   = this.combo.displayField ;
19874         
19875         
19876         this.combo.wrap.addClass('x-cbarray-grp');
19877         
19878         var cbwrap = this.combo.wrap.createChild(
19879             {tag: 'div', cls: 'x-cbarray-cb'},
19880             this.combo.el.dom
19881         );
19882         
19883              
19884         this.hiddenEl = this.combo.wrap.createChild({
19885             tag: 'input',  type:'hidden' , name: this.hiddenName, value : ''
19886         });
19887         this.el = this.combo.wrap.createChild({
19888             tag: 'input',  type:'hidden' , name: this.name, value : ''
19889         });
19890          //   this.el.dom.removeAttribute("name");
19891         
19892         
19893         this.outerWrap = this.combo.wrap;
19894         this.wrap = cbwrap;
19895         
19896         this.outerWrap.setWidth(this.width);
19897         this.outerWrap.dom.removeChild(this.el.dom);
19898         
19899         this.wrap.dom.appendChild(this.el.dom);
19900         this.outerWrap.dom.removeChild(this.combo.trigger.dom);
19901         this.combo.wrap.dom.appendChild(this.combo.trigger.dom);
19902         
19903         this.combo.trigger.setStyle('position','relative');
19904         this.combo.trigger.setStyle('left', '0px');
19905         this.combo.trigger.setStyle('top', '2px');
19906         
19907         this.combo.el.setStyle('vertical-align', 'text-bottom');
19908         
19909         //this.trigger.setStyle('vertical-align', 'top');
19910         
19911         // this should use the code from combo really... on('add' ....)
19912         if (this.adder) {
19913             
19914         
19915             this.adder = this.outerWrap.createChild(
19916                 {tag: 'img', src: Roo.BLANK_IMAGE_URL, cls: 'x-form-adder', style: 'margin-left:2px'});  
19917             var _t = this;
19918             this.adder.on('click', function(e) {
19919                 _t.fireEvent('adderclick', this, e);
19920             }, _t);
19921         }
19922         //var _t = this;
19923         //this.adder.on('click', this.onAddClick, _t);
19924         
19925         
19926         this.combo.on('select', function(cb, rec, ix) {
19927             this.addItem(rec.data);
19928             
19929             cb.setValue('');
19930             cb.el.dom.value = '';
19931             //cb.lastData = rec.data;
19932             // add to list
19933             
19934         }, this);
19935         
19936         
19937     },
19938     
19939     
19940     getName: function()
19941     {
19942         // returns hidden if it's set..
19943         if (!this.rendered) {return ''};
19944         return  this.hiddenName ? this.hiddenName : this.name;
19945         
19946     },
19947     
19948     
19949     onResize: function(w, h){
19950         
19951         return;
19952         // not sure if this is needed..
19953         //this.combo.onResize(w,h);
19954         
19955         if(typeof w != 'number'){
19956             // we do not handle it!?!?
19957             return;
19958         }
19959         var tw = this.combo.trigger.getWidth();
19960         tw += this.addicon ? this.addicon.getWidth() : 0;
19961         tw += this.editicon ? this.editicon.getWidth() : 0;
19962         var x = w - tw;
19963         this.combo.el.setWidth( this.combo.adjustWidth('input', x));
19964             
19965         this.combo.trigger.setStyle('left', '0px');
19966         
19967         if(this.list && this.listWidth === undefined){
19968             var lw = Math.max(x + this.combo.trigger.getWidth(), this.combo.minListWidth);
19969             this.list.setWidth(lw);
19970             this.innerList.setWidth(lw - this.list.getFrameWidth('lr'));
19971         }
19972         
19973     
19974         
19975     },
19976     
19977     addItem: function(rec)
19978     {
19979         var valueField = this.combo.valueField;
19980         var displayField = this.combo.displayField;
19981         
19982         if (this.items.indexOfKey(rec[valueField]) > -1) {
19983             //console.log("GOT " + rec.data.id);
19984             return;
19985         }
19986         
19987         var x = new Roo.form.ComboBoxArray.Item({
19988             //id : rec[this.idField],
19989             data : rec,
19990             displayField : displayField ,
19991             tipField : displayField ,
19992             cb : this
19993         });
19994         // use the 
19995         this.items.add(rec[valueField],x);
19996         // add it before the element..
19997         this.updateHiddenEl();
19998         x.render(this.outerWrap, this.wrap.dom);
19999         // add the image handler..
20000     },
20001     
20002     updateHiddenEl : function()
20003     {
20004         this.validate();
20005         if (!this.hiddenEl) {
20006             return;
20007         }
20008         var ar = [];
20009         var idField = this.combo.valueField;
20010         
20011         this.items.each(function(f) {
20012             ar.push(f.data[idField]);
20013         });
20014         this.hiddenEl.dom.value = ar.join(this.seperator);
20015         this.validate();
20016     },
20017     
20018     reset : function()
20019     {
20020         this.items.clear();
20021         
20022         Roo.each(this.outerWrap.select('.x-cbarray-item', true).elements, function(el){
20023            el.remove();
20024         });
20025         
20026         this.el.dom.value = '';
20027         if (this.hiddenEl) {
20028             this.hiddenEl.dom.value = '';
20029         }
20030         
20031     },
20032     getValue: function()
20033     {
20034         return this.hiddenEl ? this.hiddenEl.dom.value : '';
20035     },
20036     setValue: function(v) // not a valid action - must use addItems..
20037     {
20038         
20039         this.reset();
20040          
20041         if (this.store.isLocal && (typeof(v) == 'string')) {
20042             // then we can use the store to find the values..
20043             // comma seperated at present.. this needs to allow JSON based encoding..
20044             this.hiddenEl.value  = v;
20045             var v_ar = [];
20046             Roo.each(v.split(this.seperator), function(k) {
20047                 Roo.log("CHECK " + this.valueField + ',' + k);
20048                 var li = this.store.query(this.valueField, k);
20049                 if (!li.length) {
20050                     return;
20051                 }
20052                 var add = {};
20053                 add[this.valueField] = k;
20054                 add[this.displayField] = li.item(0).data[this.displayField];
20055                 
20056                 this.addItem(add);
20057             }, this) 
20058              
20059         }
20060         if (typeof(v) == 'object' ) {
20061             // then let's assume it's an array of objects..
20062             Roo.each(v, function(l) {
20063                 this.addItem(l);
20064             }, this);
20065              
20066         }
20067         
20068         
20069     },
20070     setFromData: function(v)
20071     {
20072         // this recieves an object, if setValues is called.
20073         this.reset();
20074         this.el.dom.value = v[this.displayField];
20075         this.hiddenEl.dom.value = v[this.valueField];
20076         if (typeof(v[this.valueField]) != 'string' || !v[this.valueField].length) {
20077             return;
20078         }
20079         var kv = v[this.valueField];
20080         var dv = v[this.displayField];
20081         kv = typeof(kv) != 'string' ? '' : kv;
20082         dv = typeof(dv) != 'string' ? '' : dv;
20083         
20084         
20085         var keys = kv.split(this.seperator);
20086         var display = dv.split(this.seperator);
20087         for (var i = 0 ; i < keys.length; i++) {
20088             add = {};
20089             add[this.valueField] = keys[i];
20090             add[this.displayField] = display[i];
20091             this.addItem(add);
20092         }
20093       
20094         
20095     },
20096     
20097     /**
20098      * Validates the combox array value
20099      * @return {Boolean} True if the value is valid, else false
20100      */
20101     validate : function(){
20102         if(this.disabled || this.validateValue(this.processValue(this.getValue()))){
20103             this.clearInvalid();
20104             return true;
20105         }
20106         return false;
20107     },
20108     
20109     validateValue : function(value){
20110         return Roo.form.ComboBoxArray.superclass.validateValue.call(this, this.getValue());
20111         
20112     },
20113     
20114     /*@
20115      * overide
20116      * 
20117      */
20118     isDirty : function() {
20119         if(this.disabled) {
20120             return false;
20121         }
20122         
20123         try {
20124             var d = Roo.decode(String(this.originalValue));
20125         } catch (e) {
20126             return String(this.getValue()) !== String(this.originalValue);
20127         }
20128         
20129         var originalValue = [];
20130         
20131         for (var i = 0; i < d.length; i++){
20132             originalValue.push(d[i][this.valueField]);
20133         }
20134         
20135         return String(this.getValue()) !== String(originalValue.join(this.seperator));
20136         
20137     }
20138     
20139 });
20140
20141
20142
20143 /**
20144  * @class Roo.form.ComboBoxArray.Item
20145  * @extends Roo.BoxComponent
20146  * A selected item in the list
20147  *  Fred [x]  Brian [x]  [Pick another |v]
20148  * 
20149  * @constructor
20150  * Create a new item.
20151  * @param {Object} config Configuration options
20152  */
20153  
20154 Roo.form.ComboBoxArray.Item = function(config) {
20155     config.id = Roo.id();
20156     Roo.form.ComboBoxArray.Item.superclass.constructor.call(this, config);
20157 }
20158
20159 Roo.extend(Roo.form.ComboBoxArray.Item, Roo.BoxComponent, {
20160     data : {},
20161     cb: false,
20162     displayField : false,
20163     tipField : false,
20164     
20165     
20166     defaultAutoCreate : {
20167         tag: 'div',
20168         cls: 'x-cbarray-item',
20169         cn : [ 
20170             { tag: 'div' },
20171             {
20172                 tag: 'img',
20173                 width:16,
20174                 height : 16,
20175                 src : Roo.BLANK_IMAGE_URL ,
20176                 align: 'center'
20177             }
20178         ]
20179         
20180     },
20181     
20182  
20183     onRender : function(ct, position)
20184     {
20185         Roo.form.Field.superclass.onRender.call(this, ct, position);
20186         
20187         if(!this.el){
20188             var cfg = this.getAutoCreate();
20189             this.el = ct.createChild(cfg, position);
20190         }
20191         
20192         this.el.child('img').dom.setAttribute('src', Roo.BLANK_IMAGE_URL);
20193         
20194         this.el.child('div').dom.innerHTML = this.cb.renderer ? 
20195             this.cb.renderer(this.data) :
20196             String.format('{0}',this.data[this.displayField]);
20197         
20198             
20199         this.el.child('div').dom.setAttribute('qtip',
20200                         String.format('{0}',this.data[this.tipField])
20201         );
20202         
20203         this.el.child('img').on('click', this.remove, this);
20204         
20205     },
20206    
20207     remove : function()
20208     {
20209         if(this.cb.disabled){
20210             return;
20211         }
20212         
20213         if(false !== this.cb.fireEvent('beforeremove', this.cb, this)){
20214             this.cb.items.remove(this);
20215             this.el.child('img').un('click', this.remove, this);
20216             this.el.remove();
20217             this.cb.updateHiddenEl();
20218
20219             this.cb.fireEvent('remove', this.cb, this);
20220         }
20221         
20222     }
20223 });/*
20224  * RooJS Library 1.1.1
20225  * Copyright(c) 2008-2011  Alan Knowles
20226  *
20227  * License - LGPL
20228  */
20229  
20230
20231 /**
20232  * @class Roo.form.ComboNested
20233  * @extends Roo.form.ComboBox
20234  * A combobox for that allows selection of nested items in a list,
20235  * eg.
20236  *
20237  *  Book
20238  *    -> red
20239  *    -> green
20240  *  Table
20241  *    -> square
20242  *      ->red
20243  *      ->green
20244  *    -> rectangle
20245  *      ->green
20246  *      
20247  * 
20248  * @constructor
20249  * Create a new ComboNested
20250  * @param {Object} config Configuration options
20251  */
20252 Roo.form.ComboNested = function(config){
20253     Roo.form.ComboCheck.superclass.constructor.call(this, config);
20254     // should verify some data...
20255     // like
20256     // hiddenName = required..
20257     // displayField = required
20258     // valudField == required
20259     var req= [ 'hiddenName', 'displayField', 'valueField' ];
20260     var _t = this;
20261     Roo.each(req, function(e) {
20262         if ((typeof(_t[e]) == 'undefined' ) || !_t[e].length) {
20263             throw "Roo.form.ComboNested : missing value for: " + e;
20264         }
20265     });
20266      
20267     
20268 };
20269
20270 Roo.extend(Roo.form.ComboNested, Roo.form.ComboBox, {
20271    
20272     /*
20273      * @config {Number} max Number of columns to show
20274      */
20275     
20276     maxColumns : 3,
20277    
20278     list : null, // the outermost div..
20279     innerLists : null, // the
20280     views : null,
20281     stores : null,
20282     // private
20283     loadingChildren : false,
20284     
20285     onRender : function(ct, position)
20286     {
20287         Roo.form.ComboBox.superclass.onRender.call(this, ct, position); // skip parent call - got to above..
20288         
20289         if(this.hiddenName){
20290             this.hiddenField = this.el.insertSibling({tag:'input', type:'hidden', name: this.hiddenName, id:  (this.hiddenId||this.hiddenName)},
20291                     'before', true);
20292             this.hiddenField.value =
20293                 this.hiddenValue !== undefined ? this.hiddenValue :
20294                 this.value !== undefined ? this.value : '';
20295
20296             // prevent input submission
20297             this.el.dom.removeAttribute('name');
20298              
20299              
20300         }
20301         
20302         if(Roo.isGecko){
20303             this.el.dom.setAttribute('autocomplete', 'off');
20304         }
20305
20306         var cls = 'x-combo-list';
20307
20308         this.list = new Roo.Layer({
20309             shadow: this.shadow, cls: [cls, this.listClass].join(' '), constrain:false
20310         });
20311
20312         var lw = this.listWidth || Math.max(this.wrap.getWidth(), this.minListWidth);
20313         this.list.setWidth(lw);
20314         this.list.swallowEvent('mousewheel');
20315         this.assetHeight = 0;
20316
20317         if(this.title){
20318             this.header = this.list.createChild({cls:cls+'-hd', html: this.title});
20319             this.assetHeight += this.header.getHeight();
20320         }
20321         this.innerLists = [];
20322         this.views = [];
20323         this.stores = [];
20324         for (var i =0 ; i < this.maxColumns; i++) {
20325             this.onRenderList( cls, i);
20326         }
20327         
20328         // always needs footer, as we are going to have an 'OK' button.
20329         this.footer = this.list.createChild({cls:cls+'-ft'});
20330         this.pageTb = new Roo.Toolbar(this.footer);  
20331         var _this = this;
20332         this.pageTb.add(  {
20333             
20334             text: 'Done',
20335             handler: function()
20336             {
20337                 _this.collapse();
20338             }
20339         });
20340         
20341         if ( this.allowBlank && !this.disableClear) {
20342             
20343             this.pageTb.add(new Roo.Toolbar.Fill(), {
20344                 cls: 'x-btn-icon x-btn-clear',
20345                 text: '&#160;',
20346                 handler: function()
20347                 {
20348                     _this.collapse();
20349                     _this.clearValue();
20350                     _this.onSelect(false, -1);
20351                 }
20352             });
20353         }
20354         if (this.footer) {
20355             this.assetHeight += this.footer.getHeight();
20356         }
20357         
20358     },
20359     onRenderList : function (  cls, i)
20360     {
20361         
20362         var lw = Math.floor(
20363                 ((this.listWidth * this.maxColumns || Math.max(this.wrap.getWidth(), this.minListWidth)) - this.list.getFrameWidth('lr')) / this.maxColumns
20364         );
20365         
20366         this.list.setWidth(lw); // default to '1'
20367
20368         var il = this.innerLists[i] = this.list.createChild({cls:cls+'-inner'});
20369         //il.on('mouseover', this.onViewOver, this, { list:  i });
20370         //il.on('mousemove', this.onViewMove, this, { list:  i });
20371         il.setWidth(lw);
20372         il.setStyle({ 'overflow-x' : 'hidden'});
20373
20374         if(!this.tpl){
20375             this.tpl = new Roo.Template({
20376                 html :  '<div class="'+cls+'-item '+cls+'-item-{cn:this.isEmpty}">{' + this.displayField + '}</div>',
20377                 isEmpty: function (value, allValues) {
20378                     //Roo.log(value);
20379                     var dl = typeof(value.data) != 'undefined' ? value.data.length : value.length; ///json is a nested response..
20380                     return dl ? 'has-children' : 'no-children'
20381                 }
20382             });
20383         }
20384         
20385         var store  = this.store;
20386         if (i > 0) {
20387             store  = new Roo.data.SimpleStore({
20388                 //fields : this.store.reader.meta.fields,
20389                 reader : this.store.reader,
20390                 data : [ ]
20391             });
20392         }
20393         this.stores[i]  = store;
20394                   
20395         var view = this.views[i] = new Roo.View(
20396             il,
20397             this.tpl,
20398             {
20399                 singleSelect:true,
20400                 store: store,
20401                 selectedClass: this.selectedClass
20402             }
20403         );
20404         view.getEl().setWidth(lw);
20405         view.getEl().setStyle({
20406             position: i < 1 ? 'relative' : 'absolute',
20407             top: 0,
20408             left: (i * lw ) + 'px',
20409             display : i > 0 ? 'none' : 'block'
20410         });
20411         view.on('selectionchange', this.onSelectChange.createDelegate(this, {list : i }, true));
20412         view.on('dblclick', this.onDoubleClick.createDelegate(this, {list : i }, true));
20413         //view.on('click', this.onViewClick, this, { list : i });
20414
20415         store.on('beforeload', this.onBeforeLoad, this);
20416         store.on('load',  this.onLoad, this, { list  : i});
20417         store.on('loadexception', this.onLoadException, this);
20418
20419         // hide the other vies..
20420         
20421         
20422         
20423     },
20424       
20425     restrictHeight : function()
20426     {
20427         var mh = 0;
20428         Roo.each(this.innerLists, function(il,i) {
20429             var el = this.views[i].getEl();
20430             el.dom.style.height = '';
20431             var inner = el.dom;
20432             var h = Math.max(il.clientHeight, il.offsetHeight, il.scrollHeight);
20433             // only adjust heights on other ones..
20434             mh = Math.max(h, mh);
20435             if (i < 1) {
20436                 
20437                 el.setHeight(h < this.maxHeight ? 'auto' : this.maxHeight);
20438                 il.setHeight(h < this.maxHeight ? 'auto' : this.maxHeight);
20439                
20440             }
20441             
20442             
20443         }, this);
20444         
20445         this.list.beginUpdate();
20446         this.list.setHeight(mh+this.list.getFrameWidth('tb')+this.assetHeight);
20447         this.list.alignTo(this.el, this.listAlign);
20448         this.list.endUpdate();
20449         
20450     },
20451      
20452     
20453     // -- store handlers..
20454     // private
20455     onBeforeLoad : function()
20456     {
20457         if(!this.hasFocus){
20458             return;
20459         }
20460         this.innerLists[0].update(this.loadingText ?
20461                '<div class="loading-indicator">'+this.loadingText+'</div>' : '');
20462         this.restrictHeight();
20463         this.selectedIndex = -1;
20464     },
20465     // private
20466     onLoad : function(a,b,c,d)
20467     {
20468         if (!this.loadingChildren) {
20469             // then we are loading the top level. - hide the children
20470             for (var i = 1;i < this.views.length; i++) {
20471                 this.views[i].getEl().setStyle({ display : 'none' });
20472             }
20473             var lw = Math.floor(
20474                 ((this.listWidth * this.maxColumns || Math.max(this.wrap.getWidth(), this.minListWidth)) - this.list.getFrameWidth('lr')) / this.maxColumns
20475             );
20476         
20477              this.list.setWidth(lw); // default to '1'
20478
20479             
20480         }
20481         if(!this.hasFocus){
20482             return;
20483         }
20484         
20485         if(this.store.getCount() > 0) {
20486             this.expand();
20487             this.restrictHeight();   
20488         } else {
20489             this.onEmptyResults();
20490         }
20491         
20492         if (!this.loadingChildren) {
20493             this.selectActive();
20494         }
20495         /*
20496         this.stores[1].loadData([]);
20497         this.stores[2].loadData([]);
20498         this.views
20499         */    
20500     
20501         //this.el.focus();
20502     },
20503     
20504     
20505     // private
20506     onLoadException : function()
20507     {
20508         this.collapse();
20509         Roo.log(this.store.reader.jsonData);
20510         if (this.store && typeof(this.store.reader.jsonData.errorMsg) != 'undefined') {
20511             Roo.MessageBox.alert("Error loading",this.store.reader.jsonData.errorMsg);
20512         }
20513         
20514         
20515     },
20516     // no cleaning of leading spaces on blur here.
20517     cleanLeadingSpace : function(e) { },
20518     
20519
20520     onSelectChange : function (view, sels, opts )
20521     {
20522         var ix = view.getSelectedIndexes();
20523          
20524         if (opts.list > this.maxColumns - 2) {
20525             if (view.store.getCount()<  1) {
20526                 this.views[opts.list ].getEl().setStyle({ display :   'none' });
20527
20528             } else  {
20529                 if (ix.length) {
20530                     // used to clear ?? but if we are loading unselected 
20531                     this.setFromData(view.store.getAt(ix[0]).data);
20532                 }
20533                 
20534             }
20535             
20536             return;
20537         }
20538         
20539         if (!ix.length) {
20540             // this get's fired when trigger opens..
20541            // this.setFromData({});
20542             var str = this.stores[opts.list+1];
20543             str.data.clear(); // removeall wihtout the fire events..
20544             return;
20545         }
20546         
20547         var rec = view.store.getAt(ix[0]);
20548          
20549         this.setFromData(rec.data);
20550         this.fireEvent('select', this, rec, ix[0]);
20551         
20552         var lw = Math.floor(
20553              (
20554                 (this.listWidth * this.maxColumns || Math.max(this.wrap.getWidth(), this.minListWidth)) - this.list.getFrameWidth('lr')
20555              ) / this.maxColumns
20556         );
20557         this.loadingChildren = true;
20558         this.stores[opts.list+1].loadDataFromChildren( rec );
20559         this.loadingChildren = false;
20560         var dl = this.stores[opts.list+1]. getTotalCount();
20561         
20562         this.views[opts.list+1].getEl().setHeight( this.innerLists[0].getHeight());
20563         
20564         this.views[opts.list+1].getEl().setStyle({ display : dl ? 'block' : 'none' });
20565         for (var i = opts.list+2; i < this.views.length;i++) {
20566             this.views[i].getEl().setStyle({ display : 'none' });
20567         }
20568         
20569         this.innerLists[opts.list+1].setHeight( this.innerLists[0].getHeight());
20570         this.list.setWidth(lw * (opts.list + (dl ? 2 : 1)));
20571         
20572         if (this.isLoading) {
20573            // this.selectActive(opts.list);
20574         }
20575          
20576     },
20577     
20578     
20579     
20580     
20581     onDoubleClick : function()
20582     {
20583         this.collapse(); //??
20584     },
20585     
20586      
20587     
20588     
20589     
20590     // private
20591     recordToStack : function(store, prop, value, stack)
20592     {
20593         var cstore = new Roo.data.SimpleStore({
20594             //fields : this.store.reader.meta.fields, // we need array reader.. for
20595             reader : this.store.reader,
20596             data : [ ]
20597         });
20598         var _this = this;
20599         var record  = false;
20600         var srec = false;
20601         if(store.getCount() < 1){
20602             return false;
20603         }
20604         store.each(function(r){
20605             if(r.data[prop] == value){
20606                 record = r;
20607             srec = r;
20608                 return false;
20609             }
20610             if (r.data.cn && r.data.cn.length) {
20611                 cstore.loadDataFromChildren( r);
20612                 var cret = _this.recordToStack(cstore, prop, value, stack);
20613                 if (cret !== false) {
20614                     record = cret;
20615                     srec = r;
20616                     return false;
20617                 }
20618             }
20619              
20620             return true;
20621         });
20622         if (record == false) {
20623             return false
20624         }
20625         stack.unshift(srec);
20626         return record;
20627     },
20628     
20629     /*
20630      * find the stack of stores that match our value.
20631      *
20632      * 
20633      */
20634     
20635     selectActive : function ()
20636     {
20637         // if store is not loaded, then we will need to wait for that to happen first.
20638         var stack = [];
20639         this.recordToStack(this.store, this.valueField, this.getValue(), stack);
20640         for (var i = 0; i < stack.length; i++ ) {
20641             this.views[i].select(stack[i].store.indexOf(stack[i]), false, false );
20642         }
20643         
20644     }
20645         
20646          
20647     
20648     
20649     
20650     
20651 });/*
20652  * Based on:
20653  * Ext JS Library 1.1.1
20654  * Copyright(c) 2006-2007, Ext JS, LLC.
20655  *
20656  * Originally Released Under LGPL - original licence link has changed is not relivant.
20657  *
20658  * Fork - LGPL
20659  * <script type="text/javascript">
20660  */
20661 /**
20662  * @class Roo.form.Checkbox
20663  * @extends Roo.form.Field
20664  * Single checkbox field.  Can be used as a direct replacement for traditional checkbox fields.
20665  * @constructor
20666  * Creates a new Checkbox
20667  * @param {Object} config Configuration options
20668  */
20669 Roo.form.Checkbox = function(config){
20670     Roo.form.Checkbox.superclass.constructor.call(this, config);
20671     this.addEvents({
20672         /**
20673          * @event check
20674          * Fires when the checkbox is checked or unchecked.
20675              * @param {Roo.form.Checkbox} this This checkbox
20676              * @param {Boolean} checked The new checked value
20677              */
20678         check : true
20679     });
20680 };
20681
20682 Roo.extend(Roo.form.Checkbox, Roo.form.Field,  {
20683     /**
20684      * @cfg {String} focusClass The CSS class to use when the checkbox receives focus (defaults to undefined)
20685      */
20686     focusClass : undefined,
20687     /**
20688      * @cfg {String} fieldClass The default CSS class for the checkbox (defaults to "x-form-field")
20689      */
20690     fieldClass: "x-form-field",
20691     /**
20692      * @cfg {Boolean} checked True if the the checkbox should render already checked (defaults to false)
20693      */
20694     checked: false,
20695     /**
20696      * @cfg {String/Object} autoCreate A DomHelper element spec, or true for a default element spec (defaults to
20697      * {tag: "input", type: "checkbox", autocomplete: "off"})
20698      */
20699     defaultAutoCreate : { tag: "input", type: 'hidden', autocomplete: "off"},
20700     /**
20701      * @cfg {String} boxLabel The text that appears beside the checkbox
20702      */
20703     boxLabel : "",
20704     /**
20705      * @cfg {String} inputValue The value that should go into the generated input element's value attribute
20706      */  
20707     inputValue : '1',
20708     /**
20709      * @cfg {String} valueOff The value that should go into the generated input element's value when unchecked.
20710      */
20711      valueOff: '0', // value when not checked..
20712
20713     actionMode : 'viewEl', 
20714     //
20715     // private
20716     itemCls : 'x-menu-check-item x-form-item',
20717     groupClass : 'x-menu-group-item',
20718     inputType : 'hidden',
20719     
20720     
20721     inSetChecked: false, // check that we are not calling self...
20722     
20723     inputElement: false, // real input element?
20724     basedOn: false, // ????
20725     
20726     isFormField: true, // not sure where this is needed!!!!
20727
20728     onResize : function(){
20729         Roo.form.Checkbox.superclass.onResize.apply(this, arguments);
20730         if(!this.boxLabel){
20731             this.el.alignTo(this.wrap, 'c-c');
20732         }
20733     },
20734
20735     initEvents : function(){
20736         Roo.form.Checkbox.superclass.initEvents.call(this);
20737         this.el.on("click", this.onClick,  this);
20738         this.el.on("change", this.onClick,  this);
20739     },
20740
20741
20742     getResizeEl : function(){
20743         return this.wrap;
20744     },
20745
20746     getPositionEl : function(){
20747         return this.wrap;
20748     },
20749
20750     // private
20751     onRender : function(ct, position){
20752         Roo.form.Checkbox.superclass.onRender.call(this, ct, position);
20753         /*
20754         if(this.inputValue !== undefined){
20755             this.el.dom.value = this.inputValue;
20756         }
20757         */
20758         //this.wrap = this.el.wrap({cls: "x-form-check-wrap"});
20759         this.wrap = this.el.wrap({cls: 'x-menu-check-item '});
20760         var viewEl = this.wrap.createChild({ 
20761             tag: 'img', cls: 'x-menu-item-icon', style: 'margin: 0px;' ,src : Roo.BLANK_IMAGE_URL });
20762         this.viewEl = viewEl;   
20763         this.wrap.on('click', this.onClick,  this); 
20764         
20765         this.el.on('DOMAttrModified', this.setFromHidden,  this); //ff
20766         this.el.on('propertychange', this.setFromHidden,  this);  //ie
20767         
20768         
20769         
20770         if(this.boxLabel){
20771             this.wrap.createChild({tag: 'label', htmlFor: this.el.id, cls: 'x-form-cb-label', html: this.boxLabel});
20772         //    viewEl.on('click', this.onClick,  this); 
20773         }
20774         //if(this.checked){
20775             this.setChecked(this.checked);
20776         //}else{
20777             //this.checked = this.el.dom;
20778         //}
20779
20780     },
20781
20782     // private
20783     initValue : Roo.emptyFn,
20784
20785     /**
20786      * Returns the checked state of the checkbox.
20787      * @return {Boolean} True if checked, else false
20788      */
20789     getValue : function(){
20790         if(this.el){
20791             return String(this.el.dom.value) == String(this.inputValue ) ? this.inputValue : this.valueOff;
20792         }
20793         return this.valueOff;
20794         
20795     },
20796
20797         // private
20798     onClick : function(){ 
20799         if (this.disabled) {
20800             return;
20801         }
20802         this.setChecked(!this.checked);
20803
20804         //if(this.el.dom.checked != this.checked){
20805         //    this.setValue(this.el.dom.checked);
20806        // }
20807     },
20808
20809     /**
20810      * Sets the checked state of the checkbox.
20811      * On is always based on a string comparison between inputValue and the param.
20812      * @param {Boolean/String} value - the value to set 
20813      * @param {Boolean/String} suppressEvent - whether to suppress the checkchange event.
20814      */
20815     setValue : function(v,suppressEvent){
20816         
20817         
20818         //this.checked = (v === true || v === 'true' || v == '1' || String(v).toLowerCase() == 'on');
20819         //if(this.el && this.el.dom){
20820         //    this.el.dom.checked = this.checked;
20821         //    this.el.dom.defaultChecked = this.checked;
20822         //}
20823         this.setChecked(String(v) === String(this.inputValue), suppressEvent);
20824         //this.fireEvent("check", this, this.checked);
20825     },
20826     // private..
20827     setChecked : function(state,suppressEvent)
20828     {
20829         if (this.inSetChecked) {
20830             this.checked = state;
20831             return;
20832         }
20833         
20834     
20835         if(this.wrap){
20836             this.wrap[state ? 'addClass' : 'removeClass']('x-menu-item-checked');
20837         }
20838         this.checked = state;
20839         if(suppressEvent !== true){
20840             this.fireEvent('check', this, state);
20841         }
20842         this.inSetChecked = true;
20843         this.el.dom.value = state ? this.inputValue : this.valueOff;
20844         this.inSetChecked = false;
20845         
20846     },
20847     // handle setting of hidden value by some other method!!?!?
20848     setFromHidden: function()
20849     {
20850         if(!this.el){
20851             return;
20852         }
20853         //console.log("SET FROM HIDDEN");
20854         //alert('setFrom hidden');
20855         this.setValue(this.el.dom.value);
20856     },
20857     
20858     onDestroy : function()
20859     {
20860         if(this.viewEl){
20861             Roo.get(this.viewEl).remove();
20862         }
20863          
20864         Roo.form.Checkbox.superclass.onDestroy.call(this);
20865     },
20866     
20867     setBoxLabel : function(str)
20868     {
20869         this.wrap.select('.x-form-cb-label', true).first().dom.innerHTML = str;
20870     }
20871
20872 });/*
20873  * Based on:
20874  * Ext JS Library 1.1.1
20875  * Copyright(c) 2006-2007, Ext JS, LLC.
20876  *
20877  * Originally Released Under LGPL - original licence link has changed is not relivant.
20878  *
20879  * Fork - LGPL
20880  * <script type="text/javascript">
20881  */
20882  
20883 /**
20884  * @class Roo.form.Radio
20885  * @extends Roo.form.Checkbox
20886  * Single radio field.  Same as Checkbox, but provided as a convenience for automatically setting the input type.
20887  * Radio grouping is handled automatically by the browser if you give each radio in a group the same name.
20888  * @constructor
20889  * Creates a new Radio
20890  * @param {Object} config Configuration options
20891  */
20892 Roo.form.Radio = function(){
20893     Roo.form.Radio.superclass.constructor.apply(this, arguments);
20894 };
20895 Roo.extend(Roo.form.Radio, Roo.form.Checkbox, {
20896     inputType: 'radio',
20897
20898     /**
20899      * If this radio is part of a group, it will return the selected value
20900      * @return {String}
20901      */
20902     getGroupValue : function(){
20903         return this.el.up('form').child('input[name='+this.el.dom.name+']:checked', true).value;
20904     },
20905     
20906     
20907     onRender : function(ct, position){
20908         Roo.form.Checkbox.superclass.onRender.call(this, ct, position);
20909         
20910         if(this.inputValue !== undefined){
20911             this.el.dom.value = this.inputValue;
20912         }
20913          
20914         this.wrap = this.el.wrap({cls: "x-form-check-wrap"});
20915         //this.wrap = this.el.wrap({cls: 'x-menu-check-item '});
20916         //var viewEl = this.wrap.createChild({ 
20917         //    tag: 'img', cls: 'x-menu-item-icon', style: 'margin: 0px;' ,src : Roo.BLANK_IMAGE_URL });
20918         //this.viewEl = viewEl;   
20919         //this.wrap.on('click', this.onClick,  this); 
20920         
20921         //this.el.on('DOMAttrModified', this.setFromHidden,  this); //ff
20922         //this.el.on('propertychange', this.setFromHidden,  this);  //ie
20923         
20924         
20925         
20926         if(this.boxLabel){
20927             this.wrap.createChild({tag: 'label', htmlFor: this.el.id, cls: 'x-form-cb-label', html: this.boxLabel});
20928         //    viewEl.on('click', this.onClick,  this); 
20929         }
20930          if(this.checked){
20931             this.el.dom.checked =   'checked' ;
20932         }
20933          
20934     } 
20935     
20936     
20937 });//<script type="text/javascript">
20938
20939 /*
20940  * Based  Ext JS Library 1.1.1
20941  * Copyright(c) 2006-2007, Ext JS, LLC.
20942  * LGPL
20943  *
20944  */
20945  
20946 /**
20947  * @class Roo.HtmlEditorCore
20948  * @extends Roo.Component
20949  * Provides a the editing component for the HTML editors in Roo. (bootstrap and Roo.form)
20950  *
20951  * any element that has display set to 'none' can cause problems in Safari and Firefox.<br/><br/>
20952  */
20953
20954 Roo.HtmlEditorCore = function(config){
20955     
20956     
20957     Roo.HtmlEditorCore.superclass.constructor.call(this, config);
20958     
20959     
20960     this.addEvents({
20961         /**
20962          * @event initialize
20963          * Fires when the editor is fully initialized (including the iframe)
20964          * @param {Roo.HtmlEditorCore} this
20965          */
20966         initialize: true,
20967         /**
20968          * @event activate
20969          * Fires when the editor is first receives the focus. Any insertion must wait
20970          * until after this event.
20971          * @param {Roo.HtmlEditorCore} this
20972          */
20973         activate: true,
20974          /**
20975          * @event beforesync
20976          * Fires before the textarea is updated with content from the editor iframe. Return false
20977          * to cancel the sync.
20978          * @param {Roo.HtmlEditorCore} this
20979          * @param {String} html
20980          */
20981         beforesync: true,
20982          /**
20983          * @event beforepush
20984          * Fires before the iframe editor is updated with content from the textarea. Return false
20985          * to cancel the push.
20986          * @param {Roo.HtmlEditorCore} this
20987          * @param {String} html
20988          */
20989         beforepush: true,
20990          /**
20991          * @event sync
20992          * Fires when the textarea is updated with content from the editor iframe.
20993          * @param {Roo.HtmlEditorCore} this
20994          * @param {String} html
20995          */
20996         sync: true,
20997          /**
20998          * @event push
20999          * Fires when the iframe editor is updated with content from the textarea.
21000          * @param {Roo.HtmlEditorCore} this
21001          * @param {String} html
21002          */
21003         push: true,
21004         
21005         /**
21006          * @event editorevent
21007          * Fires when on any editor (mouse up/down cursor movement etc.) - used for toolbar hooks.
21008          * @param {Roo.HtmlEditorCore} this
21009          */
21010         editorevent: true
21011         
21012     });
21013     
21014     // at this point this.owner is set, so we can start working out the whitelisted / blacklisted elements
21015     
21016     // defaults : white / black...
21017     this.applyBlacklists();
21018     
21019     
21020     
21021 };
21022
21023
21024 Roo.extend(Roo.HtmlEditorCore, Roo.Component,  {
21025
21026
21027      /**
21028      * @cfg {Roo.form.HtmlEditor|Roo.bootstrap.HtmlEditor} the owner field 
21029      */
21030     
21031     owner : false,
21032     
21033      /**
21034      * @cfg {String} resizable  's' or 'se' or 'e' - wrapps the element in a
21035      *                        Roo.resizable.
21036      */
21037     resizable : false,
21038      /**
21039      * @cfg {Number} height (in pixels)
21040      */   
21041     height: 300,
21042    /**
21043      * @cfg {Number} width (in pixels)
21044      */   
21045     width: 500,
21046     
21047     /**
21048      * @cfg {Array} stylesheets url of stylesheets. set to [] to disable stylesheets.
21049      * 
21050      */
21051     stylesheets: false,
21052     
21053     // id of frame..
21054     frameId: false,
21055     
21056     // private properties
21057     validationEvent : false,
21058     deferHeight: true,
21059     initialized : false,
21060     activated : false,
21061     sourceEditMode : false,
21062     onFocus : Roo.emptyFn,
21063     iframePad:3,
21064     hideMode:'offsets',
21065     
21066     clearUp: true,
21067     
21068     // blacklist + whitelisted elements..
21069     black: false,
21070     white: false,
21071      
21072     bodyCls : '',
21073
21074     /**
21075      * Protected method that will not generally be called directly. It
21076      * is called when the editor initializes the iframe with HTML contents. Override this method if you
21077      * want to change the initialization markup of the iframe (e.g. to add stylesheets).
21078      */
21079     getDocMarkup : function(){
21080         // body styles..
21081         var st = '';
21082         
21083         // inherit styels from page...?? 
21084         if (this.stylesheets === false) {
21085             
21086             Roo.get(document.head).select('style').each(function(node) {
21087                 st += node.dom.outerHTML || new XMLSerializer().serializeToString(node.dom);
21088             });
21089             
21090             Roo.get(document.head).select('link').each(function(node) { 
21091                 st += node.dom.outerHTML || new XMLSerializer().serializeToString(node.dom);
21092             });
21093             
21094         } else if (!this.stylesheets.length) {
21095                 // simple..
21096                 st = '<style type="text/css">' +
21097                     'body{border:0;margin:0;padding:3px;height:98%;cursor:text;}' +
21098                    '</style>';
21099         } else { 
21100             st = '<style type="text/css">' +
21101                     this.stylesheets +
21102                 '</style>';
21103         }
21104         
21105         st +=  '<style type="text/css">' +
21106             'IMG { cursor: pointer } ' +
21107         '</style>';
21108
21109         var cls = 'roo-htmleditor-body';
21110         
21111         if(this.bodyCls.length){
21112             cls += ' ' + this.bodyCls;
21113         }
21114         
21115         return '<html><head>' + st  +
21116             //<style type="text/css">' +
21117             //'body{border:0;margin:0;padding:3px;height:98%;cursor:text;}' +
21118             //'</style>' +
21119             ' </head><body class="' +  cls + '"></body></html>';
21120     },
21121
21122     // private
21123     onRender : function(ct, position)
21124     {
21125         var _t = this;
21126         //Roo.HtmlEditorCore.superclass.onRender.call(this, ct, position);
21127         this.el = this.owner.inputEl ? this.owner.inputEl() : this.owner.el;
21128         
21129         
21130         this.el.dom.style.border = '0 none';
21131         this.el.dom.setAttribute('tabIndex', -1);
21132         this.el.addClass('x-hidden hide');
21133         
21134         
21135         
21136         if(Roo.isIE){ // fix IE 1px bogus margin
21137             this.el.applyStyles('margin-top:-1px;margin-bottom:-1px;')
21138         }
21139        
21140         
21141         this.frameId = Roo.id();
21142         
21143          
21144         
21145         var iframe = this.owner.wrap.createChild({
21146             tag: 'iframe',
21147             cls: 'form-control', // bootstrap..
21148             id: this.frameId,
21149             name: this.frameId,
21150             frameBorder : 'no',
21151             'src' : Roo.SSL_SECURE_URL ? Roo.SSL_SECURE_URL  :  "javascript:false"
21152         }, this.el
21153         );
21154         
21155         
21156         this.iframe = iframe.dom;
21157
21158          this.assignDocWin();
21159         
21160         this.doc.designMode = 'on';
21161        
21162         this.doc.open();
21163         this.doc.write(this.getDocMarkup());
21164         this.doc.close();
21165
21166         
21167         var task = { // must defer to wait for browser to be ready
21168             run : function(){
21169                 //console.log("run task?" + this.doc.readyState);
21170                 this.assignDocWin();
21171                 if(this.doc.body || this.doc.readyState == 'complete'){
21172                     try {
21173                         this.doc.designMode="on";
21174                     } catch (e) {
21175                         return;
21176                     }
21177                     Roo.TaskMgr.stop(task);
21178                     this.initEditor.defer(10, this);
21179                 }
21180             },
21181             interval : 10,
21182             duration: 10000,
21183             scope: this
21184         };
21185         Roo.TaskMgr.start(task);
21186
21187     },
21188
21189     // private
21190     onResize : function(w, h)
21191     {
21192          Roo.log('resize: ' +w + ',' + h );
21193         //Roo.HtmlEditorCore.superclass.onResize.apply(this, arguments);
21194         if(!this.iframe){
21195             return;
21196         }
21197         if(typeof w == 'number'){
21198             
21199             this.iframe.style.width = w + 'px';
21200         }
21201         if(typeof h == 'number'){
21202             
21203             this.iframe.style.height = h + 'px';
21204             if(this.doc){
21205                 (this.doc.body || this.doc.documentElement).style.height = (h - (this.iframePad*2)) + 'px';
21206             }
21207         }
21208         
21209     },
21210
21211     /**
21212      * Toggles the editor between standard and source edit mode.
21213      * @param {Boolean} sourceEdit (optional) True for source edit, false for standard
21214      */
21215     toggleSourceEdit : function(sourceEditMode){
21216         
21217         this.sourceEditMode = sourceEditMode === true;
21218         
21219         if(this.sourceEditMode){
21220  
21221             Roo.get(this.iframe).addClass(['x-hidden','hide']);     //FIXME - what's the BS styles for these
21222             
21223         }else{
21224             Roo.get(this.iframe).removeClass(['x-hidden','hide']);
21225             //this.iframe.className = '';
21226             this.deferFocus();
21227         }
21228         //this.setSize(this.owner.wrap.getSize());
21229         //this.fireEvent('editmodechange', this, this.sourceEditMode);
21230     },
21231
21232     
21233   
21234
21235     /**
21236      * Protected method that will not generally be called directly. If you need/want
21237      * custom HTML cleanup, this is the method you should override.
21238      * @param {String} html The HTML to be cleaned
21239      * return {String} The cleaned HTML
21240      */
21241     cleanHtml : function(html){
21242         html = String(html);
21243         if(html.length > 5){
21244             if(Roo.isSafari){ // strip safari nonsense
21245                 html = html.replace(/\sclass="(?:Apple-style-span|khtml-block-placeholder)"/gi, '');
21246             }
21247         }
21248         if(html == '&nbsp;'){
21249             html = '';
21250         }
21251         return html;
21252     },
21253
21254     /**
21255      * HTML Editor -> Textarea
21256      * Protected method that will not generally be called directly. Syncs the contents
21257      * of the editor iframe with the textarea.
21258      */
21259     syncValue : function(){
21260         if(this.initialized){
21261             var bd = (this.doc.body || this.doc.documentElement);
21262             //this.cleanUpPaste(); -- this is done else where and causes havoc..
21263             var html = bd.innerHTML;
21264             if(Roo.isSafari){
21265                 var bs = bd.getAttribute('style'); // Safari puts text-align styles on the body element!
21266                 var m = bs ? bs.match(/text-align:(.*?);/i) : false;
21267                 if(m && m[1]){
21268                     html = '<div style="'+m[0]+'">' + html + '</div>';
21269                 }
21270             }
21271             html = this.cleanHtml(html);
21272             // fix up the special chars.. normaly like back quotes in word...
21273             // however we do not want to do this with chinese..
21274             html = html.replace(/[\uD800-\uDBFF][\uDC00-\uDFFF]|[\u0080-\uFFFF]/g, function(match) {
21275                 
21276                 var cc = match.charCodeAt();
21277
21278                 // Get the character value, handling surrogate pairs
21279                 if (match.length == 2) {
21280                     // It's a surrogate pair, calculate the Unicode code point
21281                     var high = match.charCodeAt(0) - 0xD800;
21282                     var low  = match.charCodeAt(1) - 0xDC00;
21283                     cc = (high * 0x400) + low + 0x10000;
21284                 }  else if (
21285                     (cc >= 0x4E00 && cc < 0xA000 ) ||
21286                     (cc >= 0x3400 && cc < 0x4E00 ) ||
21287                     (cc >= 0xf900 && cc < 0xfb00 )
21288                 ) {
21289                         return match;
21290                 }  
21291          
21292                 // No, use a numeric entity. Here we brazenly (and possibly mistakenly)
21293                 return "&#" + cc + ";";
21294                 
21295                 
21296             });
21297             
21298             
21299              
21300             if(this.owner.fireEvent('beforesync', this, html) !== false){
21301                 this.el.dom.value = html;
21302                 this.owner.fireEvent('sync', this, html);
21303             }
21304         }
21305     },
21306
21307     /**
21308      * Protected method that will not generally be called directly. Pushes the value of the textarea
21309      * into the iframe editor.
21310      */
21311     pushValue : function(){
21312         if(this.initialized){
21313             var v = this.el.dom.value.trim();
21314             
21315 //            if(v.length < 1){
21316 //                v = '&#160;';
21317 //            }
21318             
21319             if(this.owner.fireEvent('beforepush', this, v) !== false){
21320                 var d = (this.doc.body || this.doc.documentElement);
21321                 d.innerHTML = v;
21322                 this.cleanUpPaste();
21323                 this.el.dom.value = d.innerHTML;
21324                 this.owner.fireEvent('push', this, v);
21325             }
21326         }
21327     },
21328
21329     // private
21330     deferFocus : function(){
21331         this.focus.defer(10, this);
21332     },
21333
21334     // doc'ed in Field
21335     focus : function(){
21336         if(this.win && !this.sourceEditMode){
21337             this.win.focus();
21338         }else{
21339             this.el.focus();
21340         }
21341     },
21342     
21343     assignDocWin: function()
21344     {
21345         var iframe = this.iframe;
21346         
21347          if(Roo.isIE){
21348             this.doc = iframe.contentWindow.document;
21349             this.win = iframe.contentWindow;
21350         } else {
21351 //            if (!Roo.get(this.frameId)) {
21352 //                return;
21353 //            }
21354 //            this.doc = (iframe.contentDocument || Roo.get(this.frameId).dom.document);
21355 //            this.win = Roo.get(this.frameId).dom.contentWindow;
21356             
21357             if (!Roo.get(this.frameId) && !iframe.contentDocument) {
21358                 return;
21359             }
21360             
21361             this.doc = (iframe.contentDocument || Roo.get(this.frameId).dom.document);
21362             this.win = (iframe.contentWindow || Roo.get(this.frameId).dom.contentWindow);
21363         }
21364     },
21365     
21366     // private
21367     initEditor : function(){
21368         //console.log("INIT EDITOR");
21369         this.assignDocWin();
21370         
21371         
21372         
21373         this.doc.designMode="on";
21374         this.doc.open();
21375         this.doc.write(this.getDocMarkup());
21376         this.doc.close();
21377         
21378         var dbody = (this.doc.body || this.doc.documentElement);
21379         //var ss = this.el.getStyles('font-size', 'font-family', 'background-image', 'background-repeat');
21380         // this copies styles from the containing element into thsi one..
21381         // not sure why we need all of this..
21382         //var ss = this.el.getStyles('font-size', 'background-image', 'background-repeat');
21383         
21384         //var ss = this.el.getStyles( 'background-image', 'background-repeat');
21385         //ss['background-attachment'] = 'fixed'; // w3c
21386         dbody.bgProperties = 'fixed'; // ie
21387         //Roo.DomHelper.applyStyles(dbody, ss);
21388         Roo.EventManager.on(this.doc, {
21389             //'mousedown': this.onEditorEvent,
21390             'mouseup': this.onEditorEvent,
21391             'dblclick': this.onEditorEvent,
21392             'click': this.onEditorEvent,
21393             'keyup': this.onEditorEvent,
21394             buffer:100,
21395             scope: this
21396         });
21397         if(Roo.isGecko){
21398             Roo.EventManager.on(this.doc, 'keypress', this.mozKeyPress, this);
21399         }
21400         if(Roo.isIE || Roo.isSafari || Roo.isOpera){
21401             Roo.EventManager.on(this.doc, 'keydown', this.fixKeys, this);
21402         }
21403         this.initialized = true;
21404
21405         this.owner.fireEvent('initialize', this);
21406         this.pushValue();
21407     },
21408
21409     // private
21410     onDestroy : function(){
21411         
21412         
21413         
21414         if(this.rendered){
21415             
21416             //for (var i =0; i < this.toolbars.length;i++) {
21417             //    // fixme - ask toolbars for heights?
21418             //    this.toolbars[i].onDestroy();
21419            // }
21420             
21421             //this.wrap.dom.innerHTML = '';
21422             //this.wrap.remove();
21423         }
21424     },
21425
21426     // private
21427     onFirstFocus : function(){
21428         
21429         this.assignDocWin();
21430         
21431         
21432         this.activated = true;
21433          
21434     
21435         if(Roo.isGecko){ // prevent silly gecko errors
21436             this.win.focus();
21437             var s = this.win.getSelection();
21438             if(!s.focusNode || s.focusNode.nodeType != 3){
21439                 var r = s.getRangeAt(0);
21440                 r.selectNodeContents((this.doc.body || this.doc.documentElement));
21441                 r.collapse(true);
21442                 this.deferFocus();
21443             }
21444             try{
21445                 this.execCmd('useCSS', true);
21446                 this.execCmd('styleWithCSS', false);
21447             }catch(e){}
21448         }
21449         this.owner.fireEvent('activate', this);
21450     },
21451
21452     // private
21453     adjustFont: function(btn){
21454         var adjust = btn.cmd == 'increasefontsize' ? 1 : -1;
21455         //if(Roo.isSafari){ // safari
21456         //    adjust *= 2;
21457        // }
21458         var v = parseInt(this.doc.queryCommandValue('FontSize')|| 3, 10);
21459         if(Roo.isSafari){ // safari
21460             var sm = { 10 : 1, 13: 2, 16:3, 18:4, 24: 5, 32:6, 48: 7 };
21461             v =  (v < 10) ? 10 : v;
21462             v =  (v > 48) ? 48 : v;
21463             v = typeof(sm[v]) == 'undefined' ? 1 : sm[v];
21464             
21465         }
21466         
21467         
21468         v = Math.max(1, v+adjust);
21469         
21470         this.execCmd('FontSize', v  );
21471     },
21472
21473     onEditorEvent : function(e)
21474     {
21475         this.owner.fireEvent('editorevent', this, e);
21476       //  this.updateToolbar();
21477         this.syncValue(); //we can not sync so often.. sync cleans, so this breaks stuff
21478     },
21479
21480     insertTag : function(tg)
21481     {
21482         // could be a bit smarter... -> wrap the current selected tRoo..
21483         if (tg.toLowerCase() == 'span' ||
21484             tg.toLowerCase() == 'code' ||
21485             tg.toLowerCase() == 'sup' ||
21486             tg.toLowerCase() == 'sub' 
21487             ) {
21488             
21489             range = this.createRange(this.getSelection());
21490             var wrappingNode = this.doc.createElement(tg.toLowerCase());
21491             wrappingNode.appendChild(range.extractContents());
21492             range.insertNode(wrappingNode);
21493
21494             return;
21495             
21496             
21497             
21498         }
21499         this.execCmd("formatblock",   tg);
21500         
21501     },
21502     
21503     insertText : function(txt)
21504     {
21505         
21506         
21507         var range = this.createRange();
21508         range.deleteContents();
21509                //alert(Sender.getAttribute('label'));
21510                
21511         range.insertNode(this.doc.createTextNode(txt));
21512     } ,
21513     
21514      
21515
21516     /**
21517      * Executes a Midas editor command on the editor document and performs necessary focus and
21518      * toolbar updates. <b>This should only be called after the editor is initialized.</b>
21519      * @param {String} cmd The Midas command
21520      * @param {String/Boolean} value (optional) The value to pass to the command (defaults to null)
21521      */
21522     relayCmd : function(cmd, value){
21523         this.win.focus();
21524         this.execCmd(cmd, value);
21525         this.owner.fireEvent('editorevent', this);
21526         //this.updateToolbar();
21527         this.owner.deferFocus();
21528     },
21529
21530     /**
21531      * Executes a Midas editor command directly on the editor document.
21532      * For visual commands, you should use {@link #relayCmd} instead.
21533      * <b>This should only be called after the editor is initialized.</b>
21534      * @param {String} cmd The Midas command
21535      * @param {String/Boolean} value (optional) The value to pass to the command (defaults to null)
21536      */
21537     execCmd : function(cmd, value){
21538         this.doc.execCommand(cmd, false, value === undefined ? null : value);
21539         this.syncValue();
21540     },
21541  
21542  
21543    
21544     /**
21545      * Inserts the passed text at the current cursor position. Note: the editor must be initialized and activated
21546      * to insert tRoo.
21547      * @param {String} text | dom node.. 
21548      */
21549     insertAtCursor : function(text)
21550     {
21551         
21552         if(!this.activated){
21553             return;
21554         }
21555         /*
21556         if(Roo.isIE){
21557             this.win.focus();
21558             var r = this.doc.selection.createRange();
21559             if(r){
21560                 r.collapse(true);
21561                 r.pasteHTML(text);
21562                 this.syncValue();
21563                 this.deferFocus();
21564             
21565             }
21566             return;
21567         }
21568         */
21569         if(Roo.isGecko || Roo.isOpera || Roo.isSafari){
21570             this.win.focus();
21571             
21572             
21573             // from jquery ui (MIT licenced)
21574             var range, node;
21575             var win = this.win;
21576             
21577             if (win.getSelection && win.getSelection().getRangeAt) {
21578                 range = win.getSelection().getRangeAt(0);
21579                 node = typeof(text) == 'string' ? range.createContextualFragment(text) : text;
21580                 range.insertNode(node);
21581             } else if (win.document.selection && win.document.selection.createRange) {
21582                 // no firefox support
21583                 var txt = typeof(text) == 'string' ? text : text.outerHTML;
21584                 win.document.selection.createRange().pasteHTML(txt);
21585             } else {
21586                 // no firefox support
21587                 var txt = typeof(text) == 'string' ? text : text.outerHTML;
21588                 this.execCmd('InsertHTML', txt);
21589             } 
21590             
21591             this.syncValue();
21592             
21593             this.deferFocus();
21594         }
21595     },
21596  // private
21597     mozKeyPress : function(e){
21598         if(e.ctrlKey){
21599             var c = e.getCharCode(), cmd;
21600           
21601             if(c > 0){
21602                 c = String.fromCharCode(c).toLowerCase();
21603                 switch(c){
21604                     case 'b':
21605                         cmd = 'bold';
21606                         break;
21607                     case 'i':
21608                         cmd = 'italic';
21609                         break;
21610                     
21611                     case 'u':
21612                         cmd = 'underline';
21613                         break;
21614                     
21615                     case 'v':
21616                         this.cleanUpPaste.defer(100, this);
21617                         return;
21618                         
21619                 }
21620                 if(cmd){
21621                     this.win.focus();
21622                     this.execCmd(cmd);
21623                     this.deferFocus();
21624                     e.preventDefault();
21625                 }
21626                 
21627             }
21628         }
21629     },
21630
21631     // private
21632     fixKeys : function(){ // load time branching for fastest keydown performance
21633         if(Roo.isIE){
21634             return function(e){
21635                 var k = e.getKey(), r;
21636                 if(k == e.TAB){
21637                     e.stopEvent();
21638                     r = this.doc.selection.createRange();
21639                     if(r){
21640                         r.collapse(true);
21641                         r.pasteHTML('&#160;&#160;&#160;&#160;');
21642                         this.deferFocus();
21643                     }
21644                     return;
21645                 }
21646                 
21647                 if(k == e.ENTER){
21648                     r = this.doc.selection.createRange();
21649                     if(r){
21650                         var target = r.parentElement();
21651                         if(!target || target.tagName.toLowerCase() != 'li'){
21652                             e.stopEvent();
21653                             r.pasteHTML('<br />');
21654                             r.collapse(false);
21655                             r.select();
21656                         }
21657                     }
21658                 }
21659                 if (String.fromCharCode(k).toLowerCase() == 'v') { // paste
21660                     this.cleanUpPaste.defer(100, this);
21661                     return;
21662                 }
21663                 
21664                 
21665             };
21666         }else if(Roo.isOpera){
21667             return function(e){
21668                 var k = e.getKey();
21669                 if(k == e.TAB){
21670                     e.stopEvent();
21671                     this.win.focus();
21672                     this.execCmd('InsertHTML','&#160;&#160;&#160;&#160;');
21673                     this.deferFocus();
21674                 }
21675                 if (String.fromCharCode(k).toLowerCase() == 'v') { // paste
21676                     this.cleanUpPaste.defer(100, this);
21677                     return;
21678                 }
21679                 
21680             };
21681         }else if(Roo.isSafari){
21682             return function(e){
21683                 var k = e.getKey();
21684                 
21685                 if(k == e.TAB){
21686                     e.stopEvent();
21687                     this.execCmd('InsertText','\t');
21688                     this.deferFocus();
21689                     return;
21690                 }
21691                if (String.fromCharCode(k).toLowerCase() == 'v') { // paste
21692                     this.cleanUpPaste.defer(100, this);
21693                     return;
21694                 }
21695                 
21696              };
21697         }
21698     }(),
21699     
21700     getAllAncestors: function()
21701     {
21702         var p = this.getSelectedNode();
21703         var a = [];
21704         if (!p) {
21705             a.push(p); // push blank onto stack..
21706             p = this.getParentElement();
21707         }
21708         
21709         
21710         while (p && (p.nodeType == 1) && (p.tagName.toLowerCase() != 'body')) {
21711             a.push(p);
21712             p = p.parentNode;
21713         }
21714         a.push(this.doc.body);
21715         return a;
21716     },
21717     lastSel : false,
21718     lastSelNode : false,
21719     
21720     
21721     getSelection : function() 
21722     {
21723         this.assignDocWin();
21724         return Roo.isIE ? this.doc.selection : this.win.getSelection();
21725     },
21726     
21727     getSelectedNode: function() 
21728     {
21729         // this may only work on Gecko!!!
21730         
21731         // should we cache this!!!!
21732         
21733         
21734         
21735          
21736         var range = this.createRange(this.getSelection()).cloneRange();
21737         
21738         if (Roo.isIE) {
21739             var parent = range.parentElement();
21740             while (true) {
21741                 var testRange = range.duplicate();
21742                 testRange.moveToElementText(parent);
21743                 if (testRange.inRange(range)) {
21744                     break;
21745                 }
21746                 if ((parent.nodeType != 1) || (parent.tagName.toLowerCase() == 'body')) {
21747                     break;
21748                 }
21749                 parent = parent.parentElement;
21750             }
21751             return parent;
21752         }
21753         
21754         // is ancestor a text element.
21755         var ac =  range.commonAncestorContainer;
21756         if (ac.nodeType == 3) {
21757             ac = ac.parentNode;
21758         }
21759         
21760         var ar = ac.childNodes;
21761          
21762         var nodes = [];
21763         var other_nodes = [];
21764         var has_other_nodes = false;
21765         for (var i=0;i<ar.length;i++) {
21766             if ((ar[i].nodeType == 3) && (!ar[i].data.length)) { // empty text ? 
21767                 continue;
21768             }
21769             // fullly contained node.
21770             
21771             if (this.rangeIntersectsNode(range,ar[i]) && this.rangeCompareNode(range,ar[i]) == 3) {
21772                 nodes.push(ar[i]);
21773                 continue;
21774             }
21775             
21776             // probably selected..
21777             if ((ar[i].nodeType == 1) && this.rangeIntersectsNode(range,ar[i]) && (this.rangeCompareNode(range,ar[i]) > 0)) {
21778                 other_nodes.push(ar[i]);
21779                 continue;
21780             }
21781             // outer..
21782             if (!this.rangeIntersectsNode(range,ar[i])|| (this.rangeCompareNode(range,ar[i]) == 0))  {
21783                 continue;
21784             }
21785             
21786             
21787             has_other_nodes = true;
21788         }
21789         if (!nodes.length && other_nodes.length) {
21790             nodes= other_nodes;
21791         }
21792         if (has_other_nodes || !nodes.length || (nodes.length > 1)) {
21793             return false;
21794         }
21795         
21796         return nodes[0];
21797     },
21798     createRange: function(sel)
21799     {
21800         // this has strange effects when using with 
21801         // top toolbar - not sure if it's a great idea.
21802         //this.editor.contentWindow.focus();
21803         if (typeof sel != "undefined") {
21804             try {
21805                 return sel.getRangeAt ? sel.getRangeAt(0) : sel.createRange();
21806             } catch(e) {
21807                 return this.doc.createRange();
21808             }
21809         } else {
21810             return this.doc.createRange();
21811         }
21812     },
21813     getParentElement: function()
21814     {
21815         
21816         this.assignDocWin();
21817         var sel = Roo.isIE ? this.doc.selection : this.win.getSelection();
21818         
21819         var range = this.createRange(sel);
21820          
21821         try {
21822             var p = range.commonAncestorContainer;
21823             while (p.nodeType == 3) { // text node
21824                 p = p.parentNode;
21825             }
21826             return p;
21827         } catch (e) {
21828             return null;
21829         }
21830     
21831     },
21832     /***
21833      *
21834      * Range intersection.. the hard stuff...
21835      *  '-1' = before
21836      *  '0' = hits..
21837      *  '1' = after.
21838      *         [ -- selected range --- ]
21839      *   [fail]                        [fail]
21840      *
21841      *    basically..
21842      *      if end is before start or  hits it. fail.
21843      *      if start is after end or hits it fail.
21844      *
21845      *   if either hits (but other is outside. - then it's not 
21846      *   
21847      *    
21848      **/
21849     
21850     
21851     // @see http://www.thismuchiknow.co.uk/?p=64.
21852     rangeIntersectsNode : function(range, node)
21853     {
21854         var nodeRange = node.ownerDocument.createRange();
21855         try {
21856             nodeRange.selectNode(node);
21857         } catch (e) {
21858             nodeRange.selectNodeContents(node);
21859         }
21860     
21861         var rangeStartRange = range.cloneRange();
21862         rangeStartRange.collapse(true);
21863     
21864         var rangeEndRange = range.cloneRange();
21865         rangeEndRange.collapse(false);
21866     
21867         var nodeStartRange = nodeRange.cloneRange();
21868         nodeStartRange.collapse(true);
21869     
21870         var nodeEndRange = nodeRange.cloneRange();
21871         nodeEndRange.collapse(false);
21872     
21873         return rangeStartRange.compareBoundaryPoints(
21874                  Range.START_TO_START, nodeEndRange) == -1 &&
21875                rangeEndRange.compareBoundaryPoints(
21876                  Range.START_TO_START, nodeStartRange) == 1;
21877         
21878          
21879     },
21880     rangeCompareNode : function(range, node)
21881     {
21882         var nodeRange = node.ownerDocument.createRange();
21883         try {
21884             nodeRange.selectNode(node);
21885         } catch (e) {
21886             nodeRange.selectNodeContents(node);
21887         }
21888         
21889         
21890         range.collapse(true);
21891     
21892         nodeRange.collapse(true);
21893      
21894         var ss = range.compareBoundaryPoints( Range.START_TO_START, nodeRange);
21895         var ee = range.compareBoundaryPoints(  Range.END_TO_END, nodeRange);
21896          
21897         //Roo.log(node.tagName + ': ss='+ss +', ee='+ee)
21898         
21899         var nodeIsBefore   =  ss == 1;
21900         var nodeIsAfter    = ee == -1;
21901         
21902         if (nodeIsBefore && nodeIsAfter) {
21903             return 0; // outer
21904         }
21905         if (!nodeIsBefore && nodeIsAfter) {
21906             return 1; //right trailed.
21907         }
21908         
21909         if (nodeIsBefore && !nodeIsAfter) {
21910             return 2;  // left trailed.
21911         }
21912         // fully contined.
21913         return 3;
21914     },
21915
21916     // private? - in a new class?
21917     cleanUpPaste :  function()
21918     {
21919         // cleans up the whole document..
21920         Roo.log('cleanuppaste');
21921         
21922         this.cleanUpChildren(this.doc.body);
21923         var clean = this.cleanWordChars(this.doc.body.innerHTML);
21924         if (clean != this.doc.body.innerHTML) {
21925             this.doc.body.innerHTML = clean;
21926         }
21927         
21928     },
21929     
21930     cleanWordChars : function(input) {// change the chars to hex code
21931         var he = Roo.HtmlEditorCore;
21932         
21933         var output = input;
21934         Roo.each(he.swapCodes, function(sw) { 
21935             var swapper = new RegExp("\\u" + sw[0].toString(16), "g"); // hex codes
21936             
21937             output = output.replace(swapper, sw[1]);
21938         });
21939         
21940         return output;
21941     },
21942     
21943     
21944     cleanUpChildren : function (n)
21945     {
21946         if (!n.childNodes.length) {
21947             return;
21948         }
21949         for (var i = n.childNodes.length-1; i > -1 ; i--) {
21950            this.cleanUpChild(n.childNodes[i]);
21951         }
21952     },
21953     
21954     
21955         
21956     
21957     cleanUpChild : function (node)
21958     {
21959         var ed = this;
21960         //console.log(node);
21961         if (node.nodeName == "#text") {
21962             // clean up silly Windows -- stuff?
21963             return; 
21964         }
21965         if (node.nodeName == "#comment") {
21966             node.parentNode.removeChild(node);
21967             // clean up silly Windows -- stuff?
21968             return; 
21969         }
21970         var lcname = node.tagName.toLowerCase();
21971         // we ignore whitelists... ?? = not really the way to go, but we probably have not got a full
21972         // whitelist of tags..
21973         
21974         if (this.black.indexOf(lcname) > -1 && this.clearUp ) {
21975             // remove node.
21976             node.parentNode.removeChild(node);
21977             return;
21978             
21979         }
21980         
21981         var remove_keep_children= Roo.HtmlEditorCore.remove.indexOf(node.tagName.toLowerCase()) > -1;
21982         
21983         // spans with no attributes - just remove them..
21984         if ((!node.attributes || !node.attributes.length) && lcname == 'span') { 
21985             remove_keep_children = true;
21986         }
21987         
21988         // remove <a name=....> as rendering on yahoo mailer is borked with this.
21989         // this will have to be flaged elsewhere - perhaps ablack=name... on the mailer..
21990         
21991         //if (node.tagName.toLowerCase() == 'a' && !node.hasAttribute('href')) {
21992         //    remove_keep_children = true;
21993         //}
21994         
21995         if (remove_keep_children) {
21996             this.cleanUpChildren(node);
21997             // inserts everything just before this node...
21998             while (node.childNodes.length) {
21999                 var cn = node.childNodes[0];
22000                 node.removeChild(cn);
22001                 node.parentNode.insertBefore(cn, node);
22002             }
22003             node.parentNode.removeChild(node);
22004             return;
22005         }
22006         
22007         if (!node.attributes || !node.attributes.length) {
22008             
22009           
22010             
22011             
22012             this.cleanUpChildren(node);
22013             return;
22014         }
22015         
22016         function cleanAttr(n,v)
22017         {
22018             
22019             if (v.match(/^\./) || v.match(/^\//)) {
22020                 return;
22021             }
22022             if (v.match(/^(http|https):\/\//) || v.match(/^mailto:/) || v.match(/^ftp:/)) {
22023                 return;
22024             }
22025             if (v.match(/^#/)) {
22026                 return;
22027             }
22028 //            Roo.log("(REMOVE TAG)"+ node.tagName +'.' + n + '=' + v);
22029             node.removeAttribute(n);
22030             
22031         }
22032         
22033         var cwhite = this.cwhite;
22034         var cblack = this.cblack;
22035             
22036         function cleanStyle(n,v)
22037         {
22038             if (v.match(/expression/)) { //XSS?? should we even bother..
22039                 node.removeAttribute(n);
22040                 return;
22041             }
22042             
22043             var parts = v.split(/;/);
22044             var clean = [];
22045             
22046             Roo.each(parts, function(p) {
22047                 p = p.replace(/^\s+/g,'').replace(/\s+$/g,'');
22048                 if (!p.length) {
22049                     return true;
22050                 }
22051                 var l = p.split(':').shift().replace(/\s+/g,'');
22052                 l = l.replace(/^\s+/g,'').replace(/\s+$/g,'');
22053                 
22054                 if ( cwhite.length && cblack.indexOf(l) > -1) {
22055 //                    Roo.log('(REMOVE CSS)' + node.tagName +'.' + n + ':'+l + '=' + v);
22056                     //node.removeAttribute(n);
22057                     return true;
22058                 }
22059                 //Roo.log()
22060                 // only allow 'c whitelisted system attributes'
22061                 if ( cwhite.length &&  cwhite.indexOf(l) < 0) {
22062 //                    Roo.log('(REMOVE CSS)' + node.tagName +'.' + n + ':'+l + '=' + v);
22063                     //node.removeAttribute(n);
22064                     return true;
22065                 }
22066                 
22067                 
22068                  
22069                 
22070                 clean.push(p);
22071                 return true;
22072             });
22073             if (clean.length) { 
22074                 node.setAttribute(n, clean.join(';'));
22075             } else {
22076                 node.removeAttribute(n);
22077             }
22078             
22079         }
22080         
22081         
22082         for (var i = node.attributes.length-1; i > -1 ; i--) {
22083             var a = node.attributes[i];
22084             //console.log(a);
22085             
22086             if (a.name.toLowerCase().substr(0,2)=='on')  {
22087                 node.removeAttribute(a.name);
22088                 continue;
22089             }
22090             if (Roo.HtmlEditorCore.ablack.indexOf(a.name.toLowerCase()) > -1) {
22091                 node.removeAttribute(a.name);
22092                 continue;
22093             }
22094             if (Roo.HtmlEditorCore.aclean.indexOf(a.name.toLowerCase()) > -1) {
22095                 cleanAttr(a.name,a.value); // fixme..
22096                 continue;
22097             }
22098             if (a.name == 'style') {
22099                 cleanStyle(a.name,a.value);
22100                 continue;
22101             }
22102             /// clean up MS crap..
22103             // tecnically this should be a list of valid class'es..
22104             
22105             
22106             if (a.name == 'class') {
22107                 if (a.value.match(/^Mso/)) {
22108                     node.removeAttribute('class');
22109                 }
22110                 
22111                 if (a.value.match(/^body$/)) {
22112                     node.removeAttribute('class');
22113                 }
22114                 continue;
22115             }
22116             
22117             // style cleanup!?
22118             // class cleanup?
22119             
22120         }
22121         
22122         
22123         this.cleanUpChildren(node);
22124         
22125         
22126     },
22127     
22128     /**
22129      * Clean up MS wordisms...
22130      */
22131     cleanWord : function(node)
22132     {
22133         if (!node) {
22134             this.cleanWord(this.doc.body);
22135             return;
22136         }
22137         
22138         if(
22139                 node.nodeName == 'SPAN' &&
22140                 !node.hasAttributes() &&
22141                 node.childNodes.length == 1 &&
22142                 node.firstChild.nodeName == "#text"  
22143         ) {
22144             var textNode = node.firstChild;
22145             node.removeChild(textNode);
22146             if (node.getAttribute('lang') != 'zh-CN') {   // do not space pad on chinese characters..
22147                 node.parentNode.insertBefore(node.ownerDocument.createTextNode(" "), node);
22148             }
22149             node.parentNode.insertBefore(textNode, node);
22150             if (node.getAttribute('lang') != 'zh-CN') {   // do not space pad on chinese characters..
22151                 node.parentNode.insertBefore(node.ownerDocument.createTextNode(" ") , node);
22152             }
22153             node.parentNode.removeChild(node);
22154         }
22155         
22156         if (node.nodeName == "#text") {
22157             // clean up silly Windows -- stuff?
22158             return; 
22159         }
22160         if (node.nodeName == "#comment") {
22161             node.parentNode.removeChild(node);
22162             // clean up silly Windows -- stuff?
22163             return; 
22164         }
22165         
22166         if (node.tagName.toLowerCase().match(/^(style|script|applet|embed|noframes|noscript)$/)) {
22167             node.parentNode.removeChild(node);
22168             return;
22169         }
22170         //Roo.log(node.tagName);
22171         // remove - but keep children..
22172         if (node.tagName.toLowerCase().match(/^(meta|link|\\?xml:|st1:|o:|v:|font)/)) {
22173             //Roo.log('-- removed');
22174             while (node.childNodes.length) {
22175                 var cn = node.childNodes[0];
22176                 node.removeChild(cn);
22177                 node.parentNode.insertBefore(cn, node);
22178                 // move node to parent - and clean it..
22179                 this.cleanWord(cn);
22180             }
22181             node.parentNode.removeChild(node);
22182             /// no need to iterate chidlren = it's got none..
22183             //this.iterateChildren(node, this.cleanWord);
22184             return;
22185         }
22186         // clean styles
22187         if (node.className.length) {
22188             
22189             var cn = node.className.split(/\W+/);
22190             var cna = [];
22191             Roo.each(cn, function(cls) {
22192                 if (cls.match(/Mso[a-zA-Z]+/)) {
22193                     return;
22194                 }
22195                 cna.push(cls);
22196             });
22197             node.className = cna.length ? cna.join(' ') : '';
22198             if (!cna.length) {
22199                 node.removeAttribute("class");
22200             }
22201         }
22202         
22203         if (node.hasAttribute("lang")) {
22204             node.removeAttribute("lang");
22205         }
22206         
22207         if (node.hasAttribute("style")) {
22208             
22209             var styles = node.getAttribute("style").split(";");
22210             var nstyle = [];
22211             Roo.each(styles, function(s) {
22212                 if (!s.match(/:/)) {
22213                     return;
22214                 }
22215                 var kv = s.split(":");
22216                 if (kv[0].match(/^(mso-|line|font|background|margin|padding|color)/)) {
22217                     return;
22218                 }
22219                 // what ever is left... we allow.
22220                 nstyle.push(s);
22221             });
22222             node.setAttribute("style", nstyle.length ? nstyle.join(';') : '');
22223             if (!nstyle.length) {
22224                 node.removeAttribute('style');
22225             }
22226         }
22227         this.iterateChildren(node, this.cleanWord);
22228         
22229         
22230         
22231     },
22232     /**
22233      * iterateChildren of a Node, calling fn each time, using this as the scole..
22234      * @param {DomNode} node node to iterate children of.
22235      * @param {Function} fn method of this class to call on each item.
22236      */
22237     iterateChildren : function(node, fn)
22238     {
22239         if (!node.childNodes.length) {
22240                 return;
22241         }
22242         for (var i = node.childNodes.length-1; i > -1 ; i--) {
22243            fn.call(this, node.childNodes[i])
22244         }
22245     },
22246     
22247     
22248     /**
22249      * cleanTableWidths.
22250      *
22251      * Quite often pasting from word etc.. results in tables with column and widths.
22252      * This does not work well on fluid HTML layouts - like emails. - so this code should hunt an destroy them..
22253      *
22254      */
22255     cleanTableWidths : function(node)
22256     {
22257          
22258          
22259         if (!node) {
22260             this.cleanTableWidths(this.doc.body);
22261             return;
22262         }
22263         
22264         // ignore list...
22265         if (node.nodeName == "#text" || node.nodeName == "#comment") {
22266             return; 
22267         }
22268         Roo.log(node.tagName);
22269         if (!node.tagName.toLowerCase().match(/^(table|td|tr)$/)) {
22270             this.iterateChildren(node, this.cleanTableWidths);
22271             return;
22272         }
22273         if (node.hasAttribute('width')) {
22274             node.removeAttribute('width');
22275         }
22276         
22277          
22278         if (node.hasAttribute("style")) {
22279             // pretty basic...
22280             
22281             var styles = node.getAttribute("style").split(";");
22282             var nstyle = [];
22283             Roo.each(styles, function(s) {
22284                 if (!s.match(/:/)) {
22285                     return;
22286                 }
22287                 var kv = s.split(":");
22288                 if (kv[0].match(/^\s*(width|min-width)\s*$/)) {
22289                     return;
22290                 }
22291                 // what ever is left... we allow.
22292                 nstyle.push(s);
22293             });
22294             node.setAttribute("style", nstyle.length ? nstyle.join(';') : '');
22295             if (!nstyle.length) {
22296                 node.removeAttribute('style');
22297             }
22298         }
22299         
22300         this.iterateChildren(node, this.cleanTableWidths);
22301         
22302         
22303     },
22304     
22305     
22306     
22307     
22308     domToHTML : function(currentElement, depth, nopadtext) {
22309         
22310         depth = depth || 0;
22311         nopadtext = nopadtext || false;
22312     
22313         if (!currentElement) {
22314             return this.domToHTML(this.doc.body);
22315         }
22316         
22317         //Roo.log(currentElement);
22318         var j;
22319         var allText = false;
22320         var nodeName = currentElement.nodeName;
22321         var tagName = Roo.util.Format.htmlEncode(currentElement.tagName);
22322         
22323         if  (nodeName == '#text') {
22324             
22325             return nopadtext ? currentElement.nodeValue : currentElement.nodeValue.trim();
22326         }
22327         
22328         
22329         var ret = '';
22330         if (nodeName != 'BODY') {
22331              
22332             var i = 0;
22333             // Prints the node tagName, such as <A>, <IMG>, etc
22334             if (tagName) {
22335                 var attr = [];
22336                 for(i = 0; i < currentElement.attributes.length;i++) {
22337                     // quoting?
22338                     var aname = currentElement.attributes.item(i).name;
22339                     if (!currentElement.attributes.item(i).value.length) {
22340                         continue;
22341                     }
22342                     attr.push(aname + '="' + Roo.util.Format.htmlEncode(currentElement.attributes.item(i).value) + '"' );
22343                 }
22344                 
22345                 ret = "<"+currentElement.tagName+ ( attr.length ? (' ' + attr.join(' ') ) : '') + ">";
22346             } 
22347             else {
22348                 
22349                 // eack
22350             }
22351         } else {
22352             tagName = false;
22353         }
22354         if (['IMG', 'BR', 'HR', 'INPUT'].indexOf(tagName) > -1) {
22355             return ret;
22356         }
22357         if (['PRE', 'TEXTAREA', 'TD', 'A', 'SPAN'].indexOf(tagName) > -1) { // or code?
22358             nopadtext = true;
22359         }
22360         
22361         
22362         // Traverse the tree
22363         i = 0;
22364         var currentElementChild = currentElement.childNodes.item(i);
22365         var allText = true;
22366         var innerHTML  = '';
22367         lastnode = '';
22368         while (currentElementChild) {
22369             // Formatting code (indent the tree so it looks nice on the screen)
22370             var nopad = nopadtext;
22371             if (lastnode == 'SPAN') {
22372                 nopad  = true;
22373             }
22374             // text
22375             if  (currentElementChild.nodeName == '#text') {
22376                 var toadd = Roo.util.Format.htmlEncode(currentElementChild.nodeValue);
22377                 toadd = nopadtext ? toadd : toadd.trim();
22378                 if (!nopad && toadd.length > 80) {
22379                     innerHTML  += "\n" + (new Array( depth + 1 )).join( "  "  );
22380                 }
22381                 innerHTML  += toadd;
22382                 
22383                 i++;
22384                 currentElementChild = currentElement.childNodes.item(i);
22385                 lastNode = '';
22386                 continue;
22387             }
22388             allText = false;
22389             
22390             innerHTML  += nopad ? '' : "\n" + (new Array( depth + 1 )).join( "  "  );
22391                 
22392             // Recursively traverse the tree structure of the child node
22393             innerHTML   += this.domToHTML(currentElementChild, depth+1, nopadtext);
22394             lastnode = currentElementChild.nodeName;
22395             i++;
22396             currentElementChild=currentElement.childNodes.item(i);
22397         }
22398         
22399         ret += innerHTML;
22400         
22401         if (!allText) {
22402                 // The remaining code is mostly for formatting the tree
22403             ret+= nopadtext ? '' : "\n" + (new Array( depth  )).join( "  "  );
22404         }
22405         
22406         
22407         if (tagName) {
22408             ret+= "</"+tagName+">";
22409         }
22410         return ret;
22411         
22412     },
22413         
22414     applyBlacklists : function()
22415     {
22416         var w = typeof(this.owner.white) != 'undefined' && this.owner.white ? this.owner.white  : [];
22417         var b = typeof(this.owner.black) != 'undefined' && this.owner.black ? this.owner.black :  [];
22418         
22419         this.white = [];
22420         this.black = [];
22421         Roo.each(Roo.HtmlEditorCore.white, function(tag) {
22422             if (b.indexOf(tag) > -1) {
22423                 return;
22424             }
22425             this.white.push(tag);
22426             
22427         }, this);
22428         
22429         Roo.each(w, function(tag) {
22430             if (b.indexOf(tag) > -1) {
22431                 return;
22432             }
22433             if (this.white.indexOf(tag) > -1) {
22434                 return;
22435             }
22436             this.white.push(tag);
22437             
22438         }, this);
22439         
22440         
22441         Roo.each(Roo.HtmlEditorCore.black, function(tag) {
22442             if (w.indexOf(tag) > -1) {
22443                 return;
22444             }
22445             this.black.push(tag);
22446             
22447         }, this);
22448         
22449         Roo.each(b, function(tag) {
22450             if (w.indexOf(tag) > -1) {
22451                 return;
22452             }
22453             if (this.black.indexOf(tag) > -1) {
22454                 return;
22455             }
22456             this.black.push(tag);
22457             
22458         }, this);
22459         
22460         
22461         w = typeof(this.owner.cwhite) != 'undefined' && this.owner.cwhite ? this.owner.cwhite  : [];
22462         b = typeof(this.owner.cblack) != 'undefined' && this.owner.cblack ? this.owner.cblack :  [];
22463         
22464         this.cwhite = [];
22465         this.cblack = [];
22466         Roo.each(Roo.HtmlEditorCore.cwhite, function(tag) {
22467             if (b.indexOf(tag) > -1) {
22468                 return;
22469             }
22470             this.cwhite.push(tag);
22471             
22472         }, this);
22473         
22474         Roo.each(w, function(tag) {
22475             if (b.indexOf(tag) > -1) {
22476                 return;
22477             }
22478             if (this.cwhite.indexOf(tag) > -1) {
22479                 return;
22480             }
22481             this.cwhite.push(tag);
22482             
22483         }, this);
22484         
22485         
22486         Roo.each(Roo.HtmlEditorCore.cblack, function(tag) {
22487             if (w.indexOf(tag) > -1) {
22488                 return;
22489             }
22490             this.cblack.push(tag);
22491             
22492         }, this);
22493         
22494         Roo.each(b, function(tag) {
22495             if (w.indexOf(tag) > -1) {
22496                 return;
22497             }
22498             if (this.cblack.indexOf(tag) > -1) {
22499                 return;
22500             }
22501             this.cblack.push(tag);
22502             
22503         }, this);
22504     },
22505     
22506     setStylesheets : function(stylesheets)
22507     {
22508         if(typeof(stylesheets) == 'string'){
22509             Roo.get(this.iframe.contentDocument.head).createChild({
22510                 tag : 'link',
22511                 rel : 'stylesheet',
22512                 type : 'text/css',
22513                 href : stylesheets
22514             });
22515             
22516             return;
22517         }
22518         var _this = this;
22519      
22520         Roo.each(stylesheets, function(s) {
22521             if(!s.length){
22522                 return;
22523             }
22524             
22525             Roo.get(_this.iframe.contentDocument.head).createChild({
22526                 tag : 'link',
22527                 rel : 'stylesheet',
22528                 type : 'text/css',
22529                 href : s
22530             });
22531         });
22532
22533         
22534     },
22535     
22536     removeStylesheets : function()
22537     {
22538         var _this = this;
22539         
22540         Roo.each(Roo.get(_this.iframe.contentDocument.head).select('link[rel=stylesheet]', true).elements, function(s){
22541             s.remove();
22542         });
22543     },
22544     
22545     setStyle : function(style)
22546     {
22547         Roo.get(this.iframe.contentDocument.head).createChild({
22548             tag : 'style',
22549             type : 'text/css',
22550             html : style
22551         });
22552
22553         return;
22554     }
22555     
22556     // hide stuff that is not compatible
22557     /**
22558      * @event blur
22559      * @hide
22560      */
22561     /**
22562      * @event change
22563      * @hide
22564      */
22565     /**
22566      * @event focus
22567      * @hide
22568      */
22569     /**
22570      * @event specialkey
22571      * @hide
22572      */
22573     /**
22574      * @cfg {String} fieldClass @hide
22575      */
22576     /**
22577      * @cfg {String} focusClass @hide
22578      */
22579     /**
22580      * @cfg {String} autoCreate @hide
22581      */
22582     /**
22583      * @cfg {String} inputType @hide
22584      */
22585     /**
22586      * @cfg {String} invalidClass @hide
22587      */
22588     /**
22589      * @cfg {String} invalidText @hide
22590      */
22591     /**
22592      * @cfg {String} msgFx @hide
22593      */
22594     /**
22595      * @cfg {String} validateOnBlur @hide
22596      */
22597 });
22598
22599 Roo.HtmlEditorCore.white = [
22600         'area', 'br', 'img', 'input', 'hr', 'wbr',
22601         
22602        'address', 'blockquote', 'center', 'dd',      'dir',       'div', 
22603        'dl',      'dt',         'h1',     'h2',      'h3',        'h4', 
22604        'h5',      'h6',         'hr',     'isindex', 'listing',   'marquee', 
22605        'menu',    'multicol',   'ol',     'p',       'plaintext', 'pre', 
22606        'table',   'ul',         'xmp', 
22607        
22608        'caption', 'col', 'colgroup', 'tbody', 'td', 'tfoot', 'th', 
22609       'thead',   'tr', 
22610      
22611       'dir', 'menu', 'ol', 'ul', 'dl',
22612        
22613       'embed',  'object'
22614 ];
22615
22616
22617 Roo.HtmlEditorCore.black = [
22618     //    'embed',  'object', // enable - backend responsiblity to clean thiese
22619         'applet', // 
22620         'base',   'basefont', 'bgsound', 'blink',  'body', 
22621         'frame',  'frameset', 'head',    'html',   'ilayer', 
22622         'iframe', 'layer',  'link',     'meta',    'object',   
22623         'script', 'style' ,'title',  'xml' // clean later..
22624 ];
22625 Roo.HtmlEditorCore.clean = [
22626     'script', 'style', 'title', 'xml'
22627 ];
22628 Roo.HtmlEditorCore.remove = [
22629     'font'
22630 ];
22631 // attributes..
22632
22633 Roo.HtmlEditorCore.ablack = [
22634     'on'
22635 ];
22636     
22637 Roo.HtmlEditorCore.aclean = [ 
22638     'action', 'background', 'codebase', 'dynsrc', 'href', 'lowsrc' 
22639 ];
22640
22641 // protocols..
22642 Roo.HtmlEditorCore.pwhite= [
22643         'http',  'https',  'mailto'
22644 ];
22645
22646 // white listed style attributes.
22647 Roo.HtmlEditorCore.cwhite= [
22648       //  'text-align', /// default is to allow most things..
22649       
22650          
22651 //        'font-size'//??
22652 ];
22653
22654 // black listed style attributes.
22655 Roo.HtmlEditorCore.cblack= [
22656       //  'font-size' -- this can be set by the project 
22657 ];
22658
22659
22660 Roo.HtmlEditorCore.swapCodes   =[ 
22661     [    8211, "--" ], 
22662     [    8212, "--" ], 
22663     [    8216,  "'" ],  
22664     [    8217, "'" ],  
22665     [    8220, '"' ],  
22666     [    8221, '"' ],  
22667     [    8226, "*" ],  
22668     [    8230, "..." ]
22669 ]; 
22670
22671     //<script type="text/javascript">
22672
22673 /*
22674  * Ext JS Library 1.1.1
22675  * Copyright(c) 2006-2007, Ext JS, LLC.
22676  * Licence LGPL
22677  * 
22678  */
22679  
22680  
22681 Roo.form.HtmlEditor = function(config){
22682     
22683     
22684     
22685     Roo.form.HtmlEditor.superclass.constructor.call(this, config);
22686     
22687     if (!this.toolbars) {
22688         this.toolbars = [];
22689     }
22690     this.editorcore = new Roo.HtmlEditorCore(Roo.apply({ owner : this} , config));
22691     
22692     
22693 };
22694
22695 /**
22696  * @class Roo.form.HtmlEditor
22697  * @extends Roo.form.Field
22698  * Provides a lightweight HTML Editor component.
22699  *
22700  * This has been tested on Fireforx / Chrome.. IE may not be so great..
22701  * 
22702  * <br><br><b>Note: The focus/blur and validation marking functionality inherited from Ext.form.Field is NOT
22703  * supported by this editor.</b><br/><br/>
22704  * An Editor is a sensitive component that can't be used in all spots standard fields can be used. Putting an Editor within
22705  * any element that has display set to 'none' can cause problems in Safari and Firefox.<br/><br/>
22706  */
22707 Roo.extend(Roo.form.HtmlEditor, Roo.form.Field, {
22708     /**
22709      * @cfg {Boolean} clearUp
22710      */
22711     clearUp : true,
22712       /**
22713      * @cfg {Array} toolbars Array of toolbars. - defaults to just the Standard one
22714      */
22715     toolbars : false,
22716    
22717      /**
22718      * @cfg {String} resizable  's' or 'se' or 'e' - wrapps the element in a
22719      *                        Roo.resizable.
22720      */
22721     resizable : false,
22722      /**
22723      * @cfg {Number} height (in pixels)
22724      */   
22725     height: 300,
22726    /**
22727      * @cfg {Number} width (in pixels)
22728      */   
22729     width: 500,
22730     
22731     /**
22732      * @cfg {Array} stylesheets url of stylesheets. set to [] to disable stylesheets.
22733      * 
22734      */
22735     stylesheets: false,
22736     
22737     
22738      /**
22739      * @cfg {Array} blacklist of css styles style attributes (blacklist overrides whitelist)
22740      * 
22741      */
22742     cblack: false,
22743     /**
22744      * @cfg {Array} whitelist of css styles style attributes (blacklist overrides whitelist)
22745      * 
22746      */
22747     cwhite: false,
22748     
22749      /**
22750      * @cfg {Array} blacklist of html tags - in addition to standard blacklist.
22751      * 
22752      */
22753     black: false,
22754     /**
22755      * @cfg {Array} whitelist of html tags - in addition to statndard whitelist
22756      * 
22757      */
22758     white: false,
22759     
22760     // id of frame..
22761     frameId: false,
22762     
22763     // private properties
22764     validationEvent : false,
22765     deferHeight: true,
22766     initialized : false,
22767     activated : false,
22768     
22769     onFocus : Roo.emptyFn,
22770     iframePad:3,
22771     hideMode:'offsets',
22772     
22773     actionMode : 'container', // defaults to hiding it...
22774     
22775     defaultAutoCreate : { // modified by initCompnoent..
22776         tag: "textarea",
22777         style:"width:500px;height:300px;",
22778         autocomplete: "new-password"
22779     },
22780
22781     // private
22782     initComponent : function(){
22783         this.addEvents({
22784             /**
22785              * @event initialize
22786              * Fires when the editor is fully initialized (including the iframe)
22787              * @param {HtmlEditor} this
22788              */
22789             initialize: true,
22790             /**
22791              * @event activate
22792              * Fires when the editor is first receives the focus. Any insertion must wait
22793              * until after this event.
22794              * @param {HtmlEditor} this
22795              */
22796             activate: true,
22797              /**
22798              * @event beforesync
22799              * Fires before the textarea is updated with content from the editor iframe. Return false
22800              * to cancel the sync.
22801              * @param {HtmlEditor} this
22802              * @param {String} html
22803              */
22804             beforesync: true,
22805              /**
22806              * @event beforepush
22807              * Fires before the iframe editor is updated with content from the textarea. Return false
22808              * to cancel the push.
22809              * @param {HtmlEditor} this
22810              * @param {String} html
22811              */
22812             beforepush: true,
22813              /**
22814              * @event sync
22815              * Fires when the textarea is updated with content from the editor iframe.
22816              * @param {HtmlEditor} this
22817              * @param {String} html
22818              */
22819             sync: true,
22820              /**
22821              * @event push
22822              * Fires when the iframe editor is updated with content from the textarea.
22823              * @param {HtmlEditor} this
22824              * @param {String} html
22825              */
22826             push: true,
22827              /**
22828              * @event editmodechange
22829              * Fires when the editor switches edit modes
22830              * @param {HtmlEditor} this
22831              * @param {Boolean} sourceEdit True if source edit, false if standard editing.
22832              */
22833             editmodechange: true,
22834             /**
22835              * @event editorevent
22836              * Fires when on any editor (mouse up/down cursor movement etc.) - used for toolbar hooks.
22837              * @param {HtmlEditor} this
22838              */
22839             editorevent: true,
22840             /**
22841              * @event firstfocus
22842              * Fires when on first focus - needed by toolbars..
22843              * @param {HtmlEditor} this
22844              */
22845             firstfocus: true,
22846             /**
22847              * @event autosave
22848              * Auto save the htmlEditor value as a file into Events
22849              * @param {HtmlEditor} this
22850              */
22851             autosave: true,
22852             /**
22853              * @event savedpreview
22854              * preview the saved version of htmlEditor
22855              * @param {HtmlEditor} this
22856              */
22857             savedpreview: true,
22858             
22859             /**
22860             * @event stylesheetsclick
22861             * Fires when press the Sytlesheets button
22862             * @param {Roo.HtmlEditorCore} this
22863             */
22864             stylesheetsclick: true
22865         });
22866         this.defaultAutoCreate =  {
22867             tag: "textarea",
22868             style:'width: ' + this.width + 'px;height: ' + this.height + 'px;',
22869             autocomplete: "new-password"
22870         };
22871     },
22872
22873     /**
22874      * Protected method that will not generally be called directly. It
22875      * is called when the editor creates its toolbar. Override this method if you need to
22876      * add custom toolbar buttons.
22877      * @param {HtmlEditor} editor
22878      */
22879     createToolbar : function(editor){
22880         Roo.log("create toolbars");
22881         if (!editor.toolbars || !editor.toolbars.length) {
22882             editor.toolbars = [ new Roo.form.HtmlEditor.ToolbarStandard() ]; // can be empty?
22883         }
22884         
22885         for (var i =0 ; i < editor.toolbars.length;i++) {
22886             editor.toolbars[i] = Roo.factory(
22887                     typeof(editor.toolbars[i]) == 'string' ?
22888                         { xtype: editor.toolbars[i]} : editor.toolbars[i],
22889                 Roo.form.HtmlEditor);
22890             editor.toolbars[i].init(editor);
22891         }
22892          
22893         
22894     },
22895
22896      
22897     // private
22898     onRender : function(ct, position)
22899     {
22900         var _t = this;
22901         Roo.form.HtmlEditor.superclass.onRender.call(this, ct, position);
22902         
22903         this.wrap = this.el.wrap({
22904             cls:'x-html-editor-wrap', cn:{cls:'x-html-editor-tb'}
22905         });
22906         
22907         this.editorcore.onRender(ct, position);
22908          
22909         if (this.resizable) {
22910             this.resizeEl = new Roo.Resizable(this.wrap, {
22911                 pinned : true,
22912                 wrap: true,
22913                 dynamic : true,
22914                 minHeight : this.height,
22915                 height: this.height,
22916                 handles : this.resizable,
22917                 width: this.width,
22918                 listeners : {
22919                     resize : function(r, w, h) {
22920                         _t.onResize(w,h); // -something
22921                     }
22922                 }
22923             });
22924             
22925         }
22926         this.createToolbar(this);
22927        
22928         
22929         if(!this.width){
22930             this.setSize(this.wrap.getSize());
22931         }
22932         if (this.resizeEl) {
22933             this.resizeEl.resizeTo.defer(100, this.resizeEl,[ this.width,this.height ] );
22934             // should trigger onReize..
22935         }
22936         
22937         this.keyNav = new Roo.KeyNav(this.el, {
22938             
22939             "tab" : function(e){
22940                 e.preventDefault();
22941                 
22942                 var value = this.getValue();
22943                 
22944                 var start = this.el.dom.selectionStart;
22945                 var end = this.el.dom.selectionEnd;
22946                 
22947                 if(!e.shiftKey){
22948                     
22949                     this.setValue(value.substring(0, start) + "\t" + value.substring(end));
22950                     this.el.dom.setSelectionRange(end + 1, end + 1);
22951                     return;
22952                 }
22953                 
22954                 var f = value.substring(0, start).split("\t");
22955                 
22956                 if(f.pop().length != 0){
22957                     return;
22958                 }
22959                 
22960                 this.setValue(f.join("\t") + value.substring(end));
22961                 this.el.dom.setSelectionRange(start - 1, start - 1);
22962                 
22963             },
22964             
22965             "home" : function(e){
22966                 e.preventDefault();
22967                 
22968                 var curr = this.el.dom.selectionStart;
22969                 var lines = this.getValue().split("\n");
22970                 
22971                 if(!lines.length){
22972                     return;
22973                 }
22974                 
22975                 if(e.ctrlKey){
22976                     this.el.dom.setSelectionRange(0, 0);
22977                     return;
22978                 }
22979                 
22980                 var pos = 0;
22981                 
22982                 for (var i = 0; i < lines.length;i++) {
22983                     pos += lines[i].length;
22984                     
22985                     if(i != 0){
22986                         pos += 1;
22987                     }
22988                     
22989                     if(pos < curr){
22990                         continue;
22991                     }
22992                     
22993                     pos -= lines[i].length;
22994                     
22995                     break;
22996                 }
22997                 
22998                 if(!e.shiftKey){
22999                     this.el.dom.setSelectionRange(pos, pos);
23000                     return;
23001                 }
23002                 
23003                 this.el.dom.selectionStart = pos;
23004                 this.el.dom.selectionEnd = curr;
23005             },
23006             
23007             "end" : function(e){
23008                 e.preventDefault();
23009                 
23010                 var curr = this.el.dom.selectionStart;
23011                 var lines = this.getValue().split("\n");
23012                 
23013                 if(!lines.length){
23014                     return;
23015                 }
23016                 
23017                 if(e.ctrlKey){
23018                     this.el.dom.setSelectionRange(this.getValue().length, this.getValue().length);
23019                     return;
23020                 }
23021                 
23022                 var pos = 0;
23023                 
23024                 for (var i = 0; i < lines.length;i++) {
23025                     
23026                     pos += lines[i].length;
23027                     
23028                     if(i != 0){
23029                         pos += 1;
23030                     }
23031                     
23032                     if(pos < curr){
23033                         continue;
23034                     }
23035                     
23036                     break;
23037                 }
23038                 
23039                 if(!e.shiftKey){
23040                     this.el.dom.setSelectionRange(pos, pos);
23041                     return;
23042                 }
23043                 
23044                 this.el.dom.selectionStart = curr;
23045                 this.el.dom.selectionEnd = pos;
23046             },
23047
23048             scope : this,
23049
23050             doRelay : function(foo, bar, hname){
23051                 return Roo.KeyNav.prototype.doRelay.apply(this, arguments);
23052             },
23053
23054             forceKeyDown: true
23055         });
23056         
23057 //        if(this.autosave && this.w){
23058 //            this.autoSaveFn = setInterval(this.autosave, 1000);
23059 //        }
23060     },
23061
23062     // private
23063     onResize : function(w, h)
23064     {
23065         Roo.form.HtmlEditor.superclass.onResize.apply(this, arguments);
23066         var ew = false;
23067         var eh = false;
23068         
23069         if(this.el ){
23070             if(typeof w == 'number'){
23071                 var aw = w - this.wrap.getFrameWidth('lr');
23072                 this.el.setWidth(this.adjustWidth('textarea', aw));
23073                 ew = aw;
23074             }
23075             if(typeof h == 'number'){
23076                 var tbh = 0;
23077                 for (var i =0; i < this.toolbars.length;i++) {
23078                     // fixme - ask toolbars for heights?
23079                     tbh += this.toolbars[i].tb.el.getHeight();
23080                     if (this.toolbars[i].footer) {
23081                         tbh += this.toolbars[i].footer.el.getHeight();
23082                     }
23083                 }
23084                 
23085                 
23086                 
23087                 
23088                 var ah = h - this.wrap.getFrameWidth('tb') - tbh;// this.tb.el.getHeight();
23089                 ah -= 5; // knock a few pixes off for look..
23090 //                Roo.log(ah);
23091                 this.el.setHeight(this.adjustWidth('textarea', ah));
23092                 var eh = ah;
23093             }
23094         }
23095         Roo.log('onResize:' + [w,h,ew,eh].join(',') );
23096         this.editorcore.onResize(ew,eh);
23097         
23098     },
23099
23100     /**
23101      * Toggles the editor between standard and source edit mode.
23102      * @param {Boolean} sourceEdit (optional) True for source edit, false for standard
23103      */
23104     toggleSourceEdit : function(sourceEditMode)
23105     {
23106         this.editorcore.toggleSourceEdit(sourceEditMode);
23107         
23108         if(this.editorcore.sourceEditMode){
23109             Roo.log('editor - showing textarea');
23110             
23111 //            Roo.log('in');
23112 //            Roo.log(this.syncValue());
23113             this.editorcore.syncValue();
23114             this.el.removeClass('x-hidden');
23115             this.el.dom.removeAttribute('tabIndex');
23116             this.el.focus();
23117             
23118             for (var i = 0; i < this.toolbars.length; i++) {
23119                 if(this.toolbars[i] instanceof Roo.form.HtmlEditor.ToolbarContext){
23120                     this.toolbars[i].tb.hide();
23121                     this.toolbars[i].footer.hide();
23122                 }
23123             }
23124             
23125         }else{
23126             Roo.log('editor - hiding textarea');
23127 //            Roo.log('out')
23128 //            Roo.log(this.pushValue()); 
23129             this.editorcore.pushValue();
23130             
23131             this.el.addClass('x-hidden');
23132             this.el.dom.setAttribute('tabIndex', -1);
23133             
23134             for (var i = 0; i < this.toolbars.length; i++) {
23135                 if(this.toolbars[i] instanceof Roo.form.HtmlEditor.ToolbarContext){
23136                     this.toolbars[i].tb.show();
23137                     this.toolbars[i].footer.show();
23138                 }
23139             }
23140             
23141             //this.deferFocus();
23142         }
23143         
23144         this.setSize(this.wrap.getSize());
23145         this.onResize(this.wrap.getSize().width, this.wrap.getSize().height);
23146         
23147         this.fireEvent('editmodechange', this, this.editorcore.sourceEditMode);
23148     },
23149  
23150     // private (for BoxComponent)
23151     adjustSize : Roo.BoxComponent.prototype.adjustSize,
23152
23153     // private (for BoxComponent)
23154     getResizeEl : function(){
23155         return this.wrap;
23156     },
23157
23158     // private (for BoxComponent)
23159     getPositionEl : function(){
23160         return this.wrap;
23161     },
23162
23163     // private
23164     initEvents : function(){
23165         this.originalValue = this.getValue();
23166     },
23167
23168     /**
23169      * Overridden and disabled. The editor element does not support standard valid/invalid marking. @hide
23170      * @method
23171      */
23172     markInvalid : Roo.emptyFn,
23173     /**
23174      * Overridden and disabled. The editor element does not support standard valid/invalid marking. @hide
23175      * @method
23176      */
23177     clearInvalid : Roo.emptyFn,
23178
23179     setValue : function(v){
23180         Roo.form.HtmlEditor.superclass.setValue.call(this, v);
23181         this.editorcore.pushValue();
23182     },
23183
23184      
23185     // private
23186     deferFocus : function(){
23187         this.focus.defer(10, this);
23188     },
23189
23190     // doc'ed in Field
23191     focus : function(){
23192         this.editorcore.focus();
23193         
23194     },
23195       
23196
23197     // private
23198     onDestroy : function(){
23199         
23200         
23201         
23202         if(this.rendered){
23203             
23204             for (var i =0; i < this.toolbars.length;i++) {
23205                 // fixme - ask toolbars for heights?
23206                 this.toolbars[i].onDestroy();
23207             }
23208             
23209             this.wrap.dom.innerHTML = '';
23210             this.wrap.remove();
23211         }
23212     },
23213
23214     // private
23215     onFirstFocus : function(){
23216         //Roo.log("onFirstFocus");
23217         this.editorcore.onFirstFocus();
23218          for (var i =0; i < this.toolbars.length;i++) {
23219             this.toolbars[i].onFirstFocus();
23220         }
23221         
23222     },
23223     
23224     // private
23225     syncValue : function()
23226     {
23227         this.editorcore.syncValue();
23228     },
23229     
23230     pushValue : function()
23231     {
23232         this.editorcore.pushValue();
23233     },
23234     
23235     setStylesheets : function(stylesheets)
23236     {
23237         this.editorcore.setStylesheets(stylesheets);
23238     },
23239     
23240     removeStylesheets : function()
23241     {
23242         this.editorcore.removeStylesheets();
23243     }
23244      
23245     
23246     // hide stuff that is not compatible
23247     /**
23248      * @event blur
23249      * @hide
23250      */
23251     /**
23252      * @event change
23253      * @hide
23254      */
23255     /**
23256      * @event focus
23257      * @hide
23258      */
23259     /**
23260      * @event specialkey
23261      * @hide
23262      */
23263     /**
23264      * @cfg {String} fieldClass @hide
23265      */
23266     /**
23267      * @cfg {String} focusClass @hide
23268      */
23269     /**
23270      * @cfg {String} autoCreate @hide
23271      */
23272     /**
23273      * @cfg {String} inputType @hide
23274      */
23275     /**
23276      * @cfg {String} invalidClass @hide
23277      */
23278     /**
23279      * @cfg {String} invalidText @hide
23280      */
23281     /**
23282      * @cfg {String} msgFx @hide
23283      */
23284     /**
23285      * @cfg {String} validateOnBlur @hide
23286      */
23287 });
23288  
23289     // <script type="text/javascript">
23290 /*
23291  * Based on
23292  * Ext JS Library 1.1.1
23293  * Copyright(c) 2006-2007, Ext JS, LLC.
23294  *  
23295  
23296  */
23297
23298 /**
23299  * @class Roo.form.HtmlEditorToolbar1
23300  * Basic Toolbar
23301  * 
23302  * Usage:
23303  *
23304  new Roo.form.HtmlEditor({
23305     ....
23306     toolbars : [
23307         new Roo.form.HtmlEditorToolbar1({
23308             disable : { fonts: 1 , format: 1, ..., ... , ...],
23309             btns : [ .... ]
23310         })
23311     }
23312      
23313  * 
23314  * @cfg {Object} disable List of elements to disable..
23315  * @cfg {Array} btns List of additional buttons.
23316  * 
23317  * 
23318  * NEEDS Extra CSS? 
23319  * .x-html-editor-tb .x-edit-none .x-btn-text { background: none; }
23320  */
23321  
23322 Roo.form.HtmlEditor.ToolbarStandard = function(config)
23323 {
23324     
23325     Roo.apply(this, config);
23326     
23327     // default disabled, based on 'good practice'..
23328     this.disable = this.disable || {};
23329     Roo.applyIf(this.disable, {
23330         fontSize : true,
23331         colors : true,
23332         specialElements : true
23333     });
23334     
23335     
23336     //Roo.form.HtmlEditorToolbar1.superclass.constructor.call(this, editor.wrap.dom.firstChild, [], config);
23337     // dont call parent... till later.
23338 }
23339
23340 Roo.apply(Roo.form.HtmlEditor.ToolbarStandard.prototype,  {
23341     
23342     tb: false,
23343     
23344     rendered: false,
23345     
23346     editor : false,
23347     editorcore : false,
23348     /**
23349      * @cfg {Object} disable  List of toolbar elements to disable
23350          
23351      */
23352     disable : false,
23353     
23354     
23355      /**
23356      * @cfg {String} createLinkText The default text for the create link prompt
23357      */
23358     createLinkText : 'Please enter the URL for the link:',
23359     /**
23360      * @cfg {String} defaultLinkValue The default value for the create link prompt (defaults to http:/ /)
23361      */
23362     defaultLinkValue : 'http:/'+'/',
23363    
23364     
23365       /**
23366      * @cfg {Array} fontFamilies An array of available font families
23367      */
23368     fontFamilies : [
23369         'Arial',
23370         'Courier New',
23371         'Tahoma',
23372         'Times New Roman',
23373         'Verdana'
23374     ],
23375     
23376     specialChars : [
23377            "&#169;",
23378           "&#174;",     
23379           "&#8482;",    
23380           "&#163;" ,    
23381          // "&#8212;",    
23382           "&#8230;",    
23383           "&#247;" ,    
23384         //  "&#225;" ,     ?? a acute?
23385            "&#8364;"    , //Euro
23386        //   "&#8220;"    ,
23387         //  "&#8221;"    ,
23388         //  "&#8226;"    ,
23389           "&#176;"  //   , // degrees
23390
23391          // "&#233;"     , // e ecute
23392          // "&#250;"     , // u ecute?
23393     ],
23394     
23395     specialElements : [
23396         {
23397             text: "Insert Table",
23398             xtype: 'MenuItem',
23399             xns : Roo.Menu,
23400             ihtml :  '<table><tr><td>Cell</td></tr></table>' 
23401                 
23402         },
23403         {    
23404             text: "Insert Image",
23405             xtype: 'MenuItem',
23406             xns : Roo.Menu,
23407             ihtml : '<img src="about:blank"/>'
23408             
23409         }
23410         
23411          
23412     ],
23413     
23414     
23415     inputElements : [ 
23416             "form", "input:text", "input:hidden", "input:checkbox", "input:radio", "input:password", 
23417             "input:submit", "input:button", "select", "textarea", "label" ],
23418     formats : [
23419         ["p"] ,  
23420         ["h1"],["h2"],["h3"],["h4"],["h5"],["h6"], 
23421         ["pre"],[ "code"], 
23422         ["abbr"],[ "acronym"],[ "address"],[ "cite"],[ "samp"],[ "var"],
23423         ['div'],['span'],
23424         ['sup'],['sub']
23425     ],
23426     
23427     cleanStyles : [
23428         "font-size"
23429     ],
23430      /**
23431      * @cfg {String} defaultFont default font to use.
23432      */
23433     defaultFont: 'tahoma',
23434    
23435     fontSelect : false,
23436     
23437     
23438     formatCombo : false,
23439     
23440     init : function(editor)
23441     {
23442         this.editor = editor;
23443         this.editorcore = editor.editorcore ? editor.editorcore : editor;
23444         var editorcore = this.editorcore;
23445         
23446         var _t = this;
23447         
23448         var fid = editorcore.frameId;
23449         var etb = this;
23450         function btn(id, toggle, handler){
23451             var xid = fid + '-'+ id ;
23452             return {
23453                 id : xid,
23454                 cmd : id,
23455                 cls : 'x-btn-icon x-edit-'+id,
23456                 enableToggle:toggle !== false,
23457                 scope: _t, // was editor...
23458                 handler:handler||_t.relayBtnCmd,
23459                 clickEvent:'mousedown',
23460                 tooltip: etb.buttonTips[id] || undefined, ///tips ???
23461                 tabIndex:-1
23462             };
23463         }
23464         
23465         
23466         
23467         var tb = new Roo.Toolbar(editor.wrap.dom.firstChild);
23468         this.tb = tb;
23469          // stop form submits
23470         tb.el.on('click', function(e){
23471             e.preventDefault(); // what does this do?
23472         });
23473
23474         if(!this.disable.font) { // && !Roo.isSafari){
23475             /* why no safari for fonts 
23476             editor.fontSelect = tb.el.createChild({
23477                 tag:'select',
23478                 tabIndex: -1,
23479                 cls:'x-font-select',
23480                 html: this.createFontOptions()
23481             });
23482             
23483             editor.fontSelect.on('change', function(){
23484                 var font = editor.fontSelect.dom.value;
23485                 editor.relayCmd('fontname', font);
23486                 editor.deferFocus();
23487             }, editor);
23488             
23489             tb.add(
23490                 editor.fontSelect.dom,
23491                 '-'
23492             );
23493             */
23494             
23495         };
23496         if(!this.disable.formats){
23497             this.formatCombo = new Roo.form.ComboBox({
23498                 store: new Roo.data.SimpleStore({
23499                     id : 'tag',
23500                     fields: ['tag'],
23501                     data : this.formats // from states.js
23502                 }),
23503                 blockFocus : true,
23504                 name : '',
23505                 //autoCreate : {tag: "div",  size: "20"},
23506                 displayField:'tag',
23507                 typeAhead: false,
23508                 mode: 'local',
23509                 editable : false,
23510                 triggerAction: 'all',
23511                 emptyText:'Add tag',
23512                 selectOnFocus:true,
23513                 width:135,
23514                 listeners : {
23515                     'select': function(c, r, i) {
23516                         editorcore.insertTag(r.get('tag'));
23517                         editor.focus();
23518                     }
23519                 }
23520
23521             });
23522             tb.addField(this.formatCombo);
23523             
23524         }
23525         
23526         if(!this.disable.format){
23527             tb.add(
23528                 btn('bold'),
23529                 btn('italic'),
23530                 btn('underline'),
23531                 btn('strikethrough')
23532             );
23533         };
23534         if(!this.disable.fontSize){
23535             tb.add(
23536                 '-',
23537                 
23538                 
23539                 btn('increasefontsize', false, editorcore.adjustFont),
23540                 btn('decreasefontsize', false, editorcore.adjustFont)
23541             );
23542         };
23543         
23544         
23545         if(!this.disable.colors){
23546             tb.add(
23547                 '-', {
23548                     id:editorcore.frameId +'-forecolor',
23549                     cls:'x-btn-icon x-edit-forecolor',
23550                     clickEvent:'mousedown',
23551                     tooltip: this.buttonTips['forecolor'] || undefined,
23552                     tabIndex:-1,
23553                     menu : new Roo.menu.ColorMenu({
23554                         allowReselect: true,
23555                         focus: Roo.emptyFn,
23556                         value:'000000',
23557                         plain:true,
23558                         selectHandler: function(cp, color){
23559                             editorcore.execCmd('forecolor', Roo.isSafari || Roo.isIE ? '#'+color : color);
23560                             editor.deferFocus();
23561                         },
23562                         scope: editorcore,
23563                         clickEvent:'mousedown'
23564                     })
23565                 }, {
23566                     id:editorcore.frameId +'backcolor',
23567                     cls:'x-btn-icon x-edit-backcolor',
23568                     clickEvent:'mousedown',
23569                     tooltip: this.buttonTips['backcolor'] || undefined,
23570                     tabIndex:-1,
23571                     menu : new Roo.menu.ColorMenu({
23572                         focus: Roo.emptyFn,
23573                         value:'FFFFFF',
23574                         plain:true,
23575                         allowReselect: true,
23576                         selectHandler: function(cp, color){
23577                             if(Roo.isGecko){
23578                                 editorcore.execCmd('useCSS', false);
23579                                 editorcore.execCmd('hilitecolor', color);
23580                                 editorcore.execCmd('useCSS', true);
23581                                 editor.deferFocus();
23582                             }else{
23583                                 editorcore.execCmd(Roo.isOpera ? 'hilitecolor' : 'backcolor', 
23584                                     Roo.isSafari || Roo.isIE ? '#'+color : color);
23585                                 editor.deferFocus();
23586                             }
23587                         },
23588                         scope:editorcore,
23589                         clickEvent:'mousedown'
23590                     })
23591                 }
23592             );
23593         };
23594         // now add all the items...
23595         
23596
23597         if(!this.disable.alignments){
23598             tb.add(
23599                 '-',
23600                 btn('justifyleft'),
23601                 btn('justifycenter'),
23602                 btn('justifyright')
23603             );
23604         };
23605
23606         //if(!Roo.isSafari){
23607             if(!this.disable.links){
23608                 tb.add(
23609                     '-',
23610                     btn('createlink', false, this.createLink)    /// MOVE TO HERE?!!?!?!?!
23611                 );
23612             };
23613
23614             if(!this.disable.lists){
23615                 tb.add(
23616                     '-',
23617                     btn('insertorderedlist'),
23618                     btn('insertunorderedlist')
23619                 );
23620             }
23621             if(!this.disable.sourceEdit){
23622                 tb.add(
23623                     '-',
23624                     btn('sourceedit', true, function(btn){
23625                         this.toggleSourceEdit(btn.pressed);
23626                     })
23627                 );
23628             }
23629         //}
23630         
23631         var smenu = { };
23632         // special menu.. - needs to be tidied up..
23633         if (!this.disable.special) {
23634             smenu = {
23635                 text: "&#169;",
23636                 cls: 'x-edit-none',
23637                 
23638                 menu : {
23639                     items : []
23640                 }
23641             };
23642             for (var i =0; i < this.specialChars.length; i++) {
23643                 smenu.menu.items.push({
23644                     
23645                     html: this.specialChars[i],
23646                     handler: function(a,b) {
23647                         editorcore.insertAtCursor(String.fromCharCode(a.html.replace('&#','').replace(';', '')));
23648                         //editor.insertAtCursor(a.html);
23649                         
23650                     },
23651                     tabIndex:-1
23652                 });
23653             }
23654             
23655             
23656             tb.add(smenu);
23657             
23658             
23659         }
23660         
23661         var cmenu = { };
23662         if (!this.disable.cleanStyles) {
23663             cmenu = {
23664                 cls: 'x-btn-icon x-btn-clear',
23665                 
23666                 menu : {
23667                     items : []
23668                 }
23669             };
23670             for (var i =0; i < this.cleanStyles.length; i++) {
23671                 cmenu.menu.items.push({
23672                     actiontype : this.cleanStyles[i],
23673                     html: 'Remove ' + this.cleanStyles[i],
23674                     handler: function(a,b) {
23675 //                        Roo.log(a);
23676 //                        Roo.log(b);
23677                         var c = Roo.get(editorcore.doc.body);
23678                         c.select('[style]').each(function(s) {
23679                             s.dom.style.removeProperty(a.actiontype);
23680                         });
23681                         editorcore.syncValue();
23682                     },
23683                     tabIndex:-1
23684                 });
23685             }
23686              cmenu.menu.items.push({
23687                 actiontype : 'tablewidths',
23688                 html: 'Remove Table Widths',
23689                 handler: function(a,b) {
23690                     editorcore.cleanTableWidths();
23691                     editorcore.syncValue();
23692                 },
23693                 tabIndex:-1
23694             });
23695             cmenu.menu.items.push({
23696                 actiontype : 'word',
23697                 html: 'Remove MS Word Formating',
23698                 handler: function(a,b) {
23699                     editorcore.cleanWord();
23700                     editorcore.syncValue();
23701                 },
23702                 tabIndex:-1
23703             });
23704             
23705             cmenu.menu.items.push({
23706                 actiontype : 'all',
23707                 html: 'Remove All Styles',
23708                 handler: function(a,b) {
23709                     
23710                     var c = Roo.get(editorcore.doc.body);
23711                     c.select('[style]').each(function(s) {
23712                         s.dom.removeAttribute('style');
23713                     });
23714                     editorcore.syncValue();
23715                 },
23716                 tabIndex:-1
23717             });
23718             
23719             cmenu.menu.items.push({
23720                 actiontype : 'all',
23721                 html: 'Remove All CSS Classes',
23722                 handler: function(a,b) {
23723                     
23724                     var c = Roo.get(editorcore.doc.body);
23725                     c.select('[class]').each(function(s) {
23726                         s.dom.removeAttribute('class');
23727                     });
23728                     editorcore.cleanWord();
23729                     editorcore.syncValue();
23730                 },
23731                 tabIndex:-1
23732             });
23733             
23734              cmenu.menu.items.push({
23735                 actiontype : 'tidy',
23736                 html: 'Tidy HTML Source',
23737                 handler: function(a,b) {
23738                     editorcore.doc.body.innerHTML = editorcore.domToHTML();
23739                     editorcore.syncValue();
23740                 },
23741                 tabIndex:-1
23742             });
23743             
23744             
23745             tb.add(cmenu);
23746         }
23747          
23748         if (!this.disable.specialElements) {
23749             var semenu = {
23750                 text: "Other;",
23751                 cls: 'x-edit-none',
23752                 menu : {
23753                     items : []
23754                 }
23755             };
23756             for (var i =0; i < this.specialElements.length; i++) {
23757                 semenu.menu.items.push(
23758                     Roo.apply({ 
23759                         handler: function(a,b) {
23760                             editor.insertAtCursor(this.ihtml);
23761                         }
23762                     }, this.specialElements[i])
23763                 );
23764                     
23765             }
23766             
23767             tb.add(semenu);
23768             
23769             
23770         }
23771          
23772         
23773         if (this.btns) {
23774             for(var i =0; i< this.btns.length;i++) {
23775                 var b = Roo.factory(this.btns[i],Roo.form);
23776                 b.cls =  'x-edit-none';
23777                 
23778                 if(typeof(this.btns[i].cls) != 'undefined' && this.btns[i].cls.indexOf('x-init-enable') !== -1){
23779                     b.cls += ' x-init-enable';
23780                 }
23781                 
23782                 b.scope = editorcore;
23783                 tb.add(b);
23784             }
23785         
23786         }
23787         
23788         
23789         
23790         // disable everything...
23791         
23792         this.tb.items.each(function(item){
23793             
23794            if(
23795                 item.id != editorcore.frameId+ '-sourceedit' && 
23796                 (typeof(item.cls) != 'undefined' && item.cls.indexOf('x-init-enable') === -1)
23797             ){
23798                 
23799                 item.disable();
23800             }
23801         });
23802         this.rendered = true;
23803         
23804         // the all the btns;
23805         editor.on('editorevent', this.updateToolbar, this);
23806         // other toolbars need to implement this..
23807         //editor.on('editmodechange', this.updateToolbar, this);
23808     },
23809     
23810     
23811     relayBtnCmd : function(btn) {
23812         this.editorcore.relayCmd(btn.cmd);
23813     },
23814     // private used internally
23815     createLink : function(){
23816         Roo.log("create link?");
23817         var url = prompt(this.createLinkText, this.defaultLinkValue);
23818         if(url && url != 'http:/'+'/'){
23819             this.editorcore.relayCmd('createlink', url);
23820         }
23821     },
23822
23823     
23824     /**
23825      * Protected method that will not generally be called directly. It triggers
23826      * a toolbar update by reading the markup state of the current selection in the editor.
23827      */
23828     updateToolbar: function(){
23829
23830         if(!this.editorcore.activated){
23831             this.editor.onFirstFocus();
23832             return;
23833         }
23834
23835         var btns = this.tb.items.map, 
23836             doc = this.editorcore.doc,
23837             frameId = this.editorcore.frameId;
23838
23839         if(!this.disable.font && !Roo.isSafari){
23840             /*
23841             var name = (doc.queryCommandValue('FontName')||this.editor.defaultFont).toLowerCase();
23842             if(name != this.fontSelect.dom.value){
23843                 this.fontSelect.dom.value = name;
23844             }
23845             */
23846         }
23847         if(!this.disable.format){
23848             btns[frameId + '-bold'].toggle(doc.queryCommandState('bold'));
23849             btns[frameId + '-italic'].toggle(doc.queryCommandState('italic'));
23850             btns[frameId + '-underline'].toggle(doc.queryCommandState('underline'));
23851             btns[frameId + '-strikethrough'].toggle(doc.queryCommandState('strikethrough'));
23852         }
23853         if(!this.disable.alignments){
23854             btns[frameId + '-justifyleft'].toggle(doc.queryCommandState('justifyleft'));
23855             btns[frameId + '-justifycenter'].toggle(doc.queryCommandState('justifycenter'));
23856             btns[frameId + '-justifyright'].toggle(doc.queryCommandState('justifyright'));
23857         }
23858         if(!Roo.isSafari && !this.disable.lists){
23859             btns[frameId + '-insertorderedlist'].toggle(doc.queryCommandState('insertorderedlist'));
23860             btns[frameId + '-insertunorderedlist'].toggle(doc.queryCommandState('insertunorderedlist'));
23861         }
23862         
23863         var ans = this.editorcore.getAllAncestors();
23864         if (this.formatCombo) {
23865             
23866             
23867             var store = this.formatCombo.store;
23868             this.formatCombo.setValue("");
23869             for (var i =0; i < ans.length;i++) {
23870                 if (ans[i] && store.query('tag',ans[i].tagName.toLowerCase(), false).length) {
23871                     // select it..
23872                     this.formatCombo.setValue(ans[i].tagName.toLowerCase());
23873                     break;
23874                 }
23875             }
23876         }
23877         
23878         
23879         
23880         // hides menus... - so this cant be on a menu...
23881         Roo.menu.MenuMgr.hideAll();
23882
23883         //this.editorsyncValue();
23884     },
23885    
23886     
23887     createFontOptions : function(){
23888         var buf = [], fs = this.fontFamilies, ff, lc;
23889         
23890         
23891         
23892         for(var i = 0, len = fs.length; i< len; i++){
23893             ff = fs[i];
23894             lc = ff.toLowerCase();
23895             buf.push(
23896                 '<option value="',lc,'" style="font-family:',ff,';"',
23897                     (this.defaultFont == lc ? ' selected="true">' : '>'),
23898                     ff,
23899                 '</option>'
23900             );
23901         }
23902         return buf.join('');
23903     },
23904     
23905     toggleSourceEdit : function(sourceEditMode){
23906         
23907         Roo.log("toolbar toogle");
23908         if(sourceEditMode === undefined){
23909             sourceEditMode = !this.sourceEditMode;
23910         }
23911         this.sourceEditMode = sourceEditMode === true;
23912         var btn = this.tb.items.get(this.editorcore.frameId +'-sourceedit');
23913         // just toggle the button?
23914         if(btn.pressed !== this.sourceEditMode){
23915             btn.toggle(this.sourceEditMode);
23916             return;
23917         }
23918         
23919         if(sourceEditMode){
23920             Roo.log("disabling buttons");
23921             this.tb.items.each(function(item){
23922                 if(item.cmd != 'sourceedit' && (typeof(item.cls) != 'undefined' && item.cls.indexOf('x-init-enable') === -1)){
23923                     item.disable();
23924                 }
23925             });
23926           
23927         }else{
23928             Roo.log("enabling buttons");
23929             if(this.editorcore.initialized){
23930                 this.tb.items.each(function(item){
23931                     item.enable();
23932                 });
23933             }
23934             
23935         }
23936         Roo.log("calling toggole on editor");
23937         // tell the editor that it's been pressed..
23938         this.editor.toggleSourceEdit(sourceEditMode);
23939        
23940     },
23941      /**
23942      * Object collection of toolbar tooltips for the buttons in the editor. The key
23943      * is the command id associated with that button and the value is a valid QuickTips object.
23944      * For example:
23945 <pre><code>
23946 {
23947     bold : {
23948         title: 'Bold (Ctrl+B)',
23949         text: 'Make the selected text bold.',
23950         cls: 'x-html-editor-tip'
23951     },
23952     italic : {
23953         title: 'Italic (Ctrl+I)',
23954         text: 'Make the selected text italic.',
23955         cls: 'x-html-editor-tip'
23956     },
23957     ...
23958 </code></pre>
23959     * @type Object
23960      */
23961     buttonTips : {
23962         bold : {
23963             title: 'Bold (Ctrl+B)',
23964             text: 'Make the selected text bold.',
23965             cls: 'x-html-editor-tip'
23966         },
23967         italic : {
23968             title: 'Italic (Ctrl+I)',
23969             text: 'Make the selected text italic.',
23970             cls: 'x-html-editor-tip'
23971         },
23972         underline : {
23973             title: 'Underline (Ctrl+U)',
23974             text: 'Underline the selected text.',
23975             cls: 'x-html-editor-tip'
23976         },
23977         strikethrough : {
23978             title: 'Strikethrough',
23979             text: 'Strikethrough the selected text.',
23980             cls: 'x-html-editor-tip'
23981         },
23982         increasefontsize : {
23983             title: 'Grow Text',
23984             text: 'Increase the font size.',
23985             cls: 'x-html-editor-tip'
23986         },
23987         decreasefontsize : {
23988             title: 'Shrink Text',
23989             text: 'Decrease the font size.',
23990             cls: 'x-html-editor-tip'
23991         },
23992         backcolor : {
23993             title: 'Text Highlight Color',
23994             text: 'Change the background color of the selected text.',
23995             cls: 'x-html-editor-tip'
23996         },
23997         forecolor : {
23998             title: 'Font Color',
23999             text: 'Change the color of the selected text.',
24000             cls: 'x-html-editor-tip'
24001         },
24002         justifyleft : {
24003             title: 'Align Text Left',
24004             text: 'Align text to the left.',
24005             cls: 'x-html-editor-tip'
24006         },
24007         justifycenter : {
24008             title: 'Center Text',
24009             text: 'Center text in the editor.',
24010             cls: 'x-html-editor-tip'
24011         },
24012         justifyright : {
24013             title: 'Align Text Right',
24014             text: 'Align text to the right.',
24015             cls: 'x-html-editor-tip'
24016         },
24017         insertunorderedlist : {
24018             title: 'Bullet List',
24019             text: 'Start a bulleted list.',
24020             cls: 'x-html-editor-tip'
24021         },
24022         insertorderedlist : {
24023             title: 'Numbered List',
24024             text: 'Start a numbered list.',
24025             cls: 'x-html-editor-tip'
24026         },
24027         createlink : {
24028             title: 'Hyperlink',
24029             text: 'Make the selected text a hyperlink.',
24030             cls: 'x-html-editor-tip'
24031         },
24032         sourceedit : {
24033             title: 'Source Edit',
24034             text: 'Switch to source editing mode.',
24035             cls: 'x-html-editor-tip'
24036         }
24037     },
24038     // private
24039     onDestroy : function(){
24040         if(this.rendered){
24041             
24042             this.tb.items.each(function(item){
24043                 if(item.menu){
24044                     item.menu.removeAll();
24045                     if(item.menu.el){
24046                         item.menu.el.destroy();
24047                     }
24048                 }
24049                 item.destroy();
24050             });
24051              
24052         }
24053     },
24054     onFirstFocus: function() {
24055         this.tb.items.each(function(item){
24056            item.enable();
24057         });
24058     }
24059 });
24060
24061
24062
24063
24064 // <script type="text/javascript">
24065 /*
24066  * Based on
24067  * Ext JS Library 1.1.1
24068  * Copyright(c) 2006-2007, Ext JS, LLC.
24069  *  
24070  
24071  */
24072
24073  
24074 /**
24075  * @class Roo.form.HtmlEditor.ToolbarContext
24076  * Context Toolbar
24077  * 
24078  * Usage:
24079  *
24080  new Roo.form.HtmlEditor({
24081     ....
24082     toolbars : [
24083         { xtype: 'ToolbarStandard', styles : {} }
24084         { xtype: 'ToolbarContext', disable : {} }
24085     ]
24086 })
24087
24088      
24089  * 
24090  * @config : {Object} disable List of elements to disable.. (not done yet.)
24091  * @config : {Object} styles  Map of styles available.
24092  * 
24093  */
24094
24095 Roo.form.HtmlEditor.ToolbarContext = function(config)
24096 {
24097     
24098     Roo.apply(this, config);
24099     //Roo.form.HtmlEditorToolbar1.superclass.constructor.call(this, editor.wrap.dom.firstChild, [], config);
24100     // dont call parent... till later.
24101     this.styles = this.styles || {};
24102 }
24103
24104  
24105
24106 Roo.form.HtmlEditor.ToolbarContext.types = {
24107     'IMG' : {
24108         width : {
24109             title: "Width",
24110             width: 40
24111         },
24112         height:  {
24113             title: "Height",
24114             width: 40
24115         },
24116         align: {
24117             title: "Align",
24118             opts : [ [""],[ "left"],[ "right"],[ "center"],[ "top"]],
24119             width : 80
24120             
24121         },
24122         border: {
24123             title: "Border",
24124             width: 40
24125         },
24126         alt: {
24127             title: "Alt",
24128             width: 120
24129         },
24130         src : {
24131             title: "Src",
24132             width: 220
24133         }
24134         
24135     },
24136     'A' : {
24137         name : {
24138             title: "Name",
24139             width: 50
24140         },
24141         target:  {
24142             title: "Target",
24143             width: 120
24144         },
24145         href:  {
24146             title: "Href",
24147             width: 220
24148         } // border?
24149         
24150     },
24151     'TABLE' : {
24152         rows : {
24153             title: "Rows",
24154             width: 20
24155         },
24156         cols : {
24157             title: "Cols",
24158             width: 20
24159         },
24160         width : {
24161             title: "Width",
24162             width: 40
24163         },
24164         height : {
24165             title: "Height",
24166             width: 40
24167         },
24168         border : {
24169             title: "Border",
24170             width: 20
24171         }
24172     },
24173     'TD' : {
24174         width : {
24175             title: "Width",
24176             width: 40
24177         },
24178         height : {
24179             title: "Height",
24180             width: 40
24181         },   
24182         align: {
24183             title: "Align",
24184             opts : [[""],[ "left"],[ "center"],[ "right"],[ "justify"],[ "char"]],
24185             width: 80
24186         },
24187         valign: {
24188             title: "Valign",
24189             opts : [[""],[ "top"],[ "middle"],[ "bottom"],[ "baseline"]],
24190             width: 80
24191         },
24192         colspan: {
24193             title: "Colspan",
24194             width: 20
24195             
24196         },
24197          'font-family'  : {
24198             title : "Font",
24199             style : 'fontFamily',
24200             displayField: 'display',
24201             optname : 'font-family',
24202             width: 140
24203         }
24204     },
24205     'INPUT' : {
24206         name : {
24207             title: "name",
24208             width: 120
24209         },
24210         value : {
24211             title: "Value",
24212             width: 120
24213         },
24214         width : {
24215             title: "Width",
24216             width: 40
24217         }
24218     },
24219     'LABEL' : {
24220         'for' : {
24221             title: "For",
24222             width: 120
24223         }
24224     },
24225     'TEXTAREA' : {
24226           name : {
24227             title: "name",
24228             width: 120
24229         },
24230         rows : {
24231             title: "Rows",
24232             width: 20
24233         },
24234         cols : {
24235             title: "Cols",
24236             width: 20
24237         }
24238     },
24239     'SELECT' : {
24240         name : {
24241             title: "name",
24242             width: 120
24243         },
24244         selectoptions : {
24245             title: "Options",
24246             width: 200
24247         }
24248     },
24249     
24250     // should we really allow this??
24251     // should this just be 
24252     'BODY' : {
24253         title : {
24254             title: "Title",
24255             width: 200,
24256             disabled : true
24257         }
24258     },
24259     'SPAN' : {
24260         'font-family'  : {
24261             title : "Font",
24262             style : 'fontFamily',
24263             displayField: 'display',
24264             optname : 'font-family',
24265             width: 140
24266         }
24267     },
24268     'DIV' : {
24269         'font-family'  : {
24270             title : "Font",
24271             style : 'fontFamily',
24272             displayField: 'display',
24273             optname : 'font-family',
24274             width: 140
24275         }
24276     },
24277      'P' : {
24278         'font-family'  : {
24279             title : "Font",
24280             style : 'fontFamily',
24281             displayField: 'display',
24282             optname : 'font-family',
24283             width: 140
24284         }
24285     },
24286     
24287     '*' : {
24288         // empty..
24289     }
24290
24291 };
24292
24293 // this should be configurable.. - you can either set it up using stores, or modify options somehwere..
24294 Roo.form.HtmlEditor.ToolbarContext.stores = false;
24295
24296 Roo.form.HtmlEditor.ToolbarContext.options = {
24297         'font-family'  : [ 
24298                 [ 'Helvetica,Arial,sans-serif', 'Helvetica'],
24299                 [ 'Courier New', 'Courier New'],
24300                 [ 'Tahoma', 'Tahoma'],
24301                 [ 'Times New Roman,serif', 'Times'],
24302                 [ 'Verdana','Verdana' ]
24303         ]
24304 };
24305
24306 // fixme - these need to be configurable..
24307  
24308
24309 //Roo.form.HtmlEditor.ToolbarContext.types
24310
24311
24312 Roo.apply(Roo.form.HtmlEditor.ToolbarContext.prototype,  {
24313     
24314     tb: false,
24315     
24316     rendered: false,
24317     
24318     editor : false,
24319     editorcore : false,
24320     /**
24321      * @cfg {Object} disable  List of toolbar elements to disable
24322          
24323      */
24324     disable : false,
24325     /**
24326      * @cfg {Object} styles List of styles 
24327      *    eg. { '*' : [ 'headline' ] , 'TD' : [ 'underline', 'double-underline' ] } 
24328      *
24329      * These must be defined in the page, so they get rendered correctly..
24330      * .headline { }
24331      * TD.underline { }
24332      * 
24333      */
24334     styles : false,
24335     
24336     options: false,
24337     
24338     toolbars : false,
24339     
24340     init : function(editor)
24341     {
24342         this.editor = editor;
24343         this.editorcore = editor.editorcore ? editor.editorcore : editor;
24344         var editorcore = this.editorcore;
24345         
24346         var fid = editorcore.frameId;
24347         var etb = this;
24348         function btn(id, toggle, handler){
24349             var xid = fid + '-'+ id ;
24350             return {
24351                 id : xid,
24352                 cmd : id,
24353                 cls : 'x-btn-icon x-edit-'+id,
24354                 enableToggle:toggle !== false,
24355                 scope: editorcore, // was editor...
24356                 handler:handler||editorcore.relayBtnCmd,
24357                 clickEvent:'mousedown',
24358                 tooltip: etb.buttonTips[id] || undefined, ///tips ???
24359                 tabIndex:-1
24360             };
24361         }
24362         // create a new element.
24363         var wdiv = editor.wrap.createChild({
24364                 tag: 'div'
24365             }, editor.wrap.dom.firstChild.nextSibling, true);
24366         
24367         // can we do this more than once??
24368         
24369          // stop form submits
24370       
24371  
24372         // disable everything...
24373         var ty= Roo.form.HtmlEditor.ToolbarContext.types;
24374         this.toolbars = {};
24375            
24376         for (var i in  ty) {
24377           
24378             this.toolbars[i] = this.buildToolbar(ty[i],i);
24379         }
24380         this.tb = this.toolbars.BODY;
24381         this.tb.el.show();
24382         this.buildFooter();
24383         this.footer.show();
24384         editor.on('hide', function( ) { this.footer.hide() }, this);
24385         editor.on('show', function( ) { this.footer.show() }, this);
24386         
24387          
24388         this.rendered = true;
24389         
24390         // the all the btns;
24391         editor.on('editorevent', this.updateToolbar, this);
24392         // other toolbars need to implement this..
24393         //editor.on('editmodechange', this.updateToolbar, this);
24394     },
24395     
24396     
24397     
24398     /**
24399      * Protected method that will not generally be called directly. It triggers
24400      * a toolbar update by reading the markup state of the current selection in the editor.
24401      *
24402      * Note you can force an update by calling on('editorevent', scope, false)
24403      */
24404     updateToolbar: function(editor,ev,sel){
24405
24406         //Roo.log(ev);
24407         // capture mouse up - this is handy for selecting images..
24408         // perhaps should go somewhere else...
24409         if(!this.editorcore.activated){
24410              this.editor.onFirstFocus();
24411             return;
24412         }
24413         
24414         
24415         
24416         // http://developer.yahoo.com/yui/docs/simple-editor.js.html
24417         // selectNode - might want to handle IE?
24418         if (ev &&
24419             (ev.type == 'mouseup' || ev.type == 'click' ) &&
24420             ev.target && ev.target.tagName == 'IMG') {
24421             // they have click on an image...
24422             // let's see if we can change the selection...
24423             sel = ev.target;
24424          
24425               var nodeRange = sel.ownerDocument.createRange();
24426             try {
24427                 nodeRange.selectNode(sel);
24428             } catch (e) {
24429                 nodeRange.selectNodeContents(sel);
24430             }
24431             //nodeRange.collapse(true);
24432             var s = this.editorcore.win.getSelection();
24433             s.removeAllRanges();
24434             s.addRange(nodeRange);
24435         }  
24436         
24437       
24438         var updateFooter = sel ? false : true;
24439         
24440         
24441         var ans = this.editorcore.getAllAncestors();
24442         
24443         // pick
24444         var ty= Roo.form.HtmlEditor.ToolbarContext.types;
24445         
24446         if (!sel) { 
24447             sel = ans.length ? (ans[0] ?  ans[0]  : ans[1]) : this.editorcore.doc.body;
24448             sel = sel ? sel : this.editorcore.doc.body;
24449             sel = sel.tagName.length ? sel : this.editorcore.doc.body;
24450             
24451         }
24452         // pick a menu that exists..
24453         var tn = sel.tagName.toUpperCase();
24454         //sel = typeof(ty[tn]) != 'undefined' ? sel : this.editor.doc.body;
24455         
24456         tn = sel.tagName.toUpperCase();
24457         
24458         var lastSel = this.tb.selectedNode;
24459         
24460         this.tb.selectedNode = sel;
24461         
24462         // if current menu does not match..
24463         
24464         if ((this.tb.name != tn) || (lastSel != this.tb.selectedNode) || ev === false) {
24465                 
24466             this.tb.el.hide();
24467             ///console.log("show: " + tn);
24468             this.tb =  typeof(ty[tn]) != 'undefined' ? this.toolbars[tn] : this.toolbars['*'];
24469             this.tb.el.show();
24470             // update name
24471             this.tb.items.first().el.innerHTML = tn + ':&nbsp;';
24472             
24473             
24474             // update attributes
24475             if (this.tb.fields) {
24476                 this.tb.fields.each(function(e) {
24477                     if (e.stylename) {
24478                         e.setValue(sel.style[e.stylename]);
24479                         return;
24480                     } 
24481                    e.setValue(sel.getAttribute(e.attrname));
24482                 });
24483             }
24484             
24485             var hasStyles = false;
24486             for(var i in this.styles) {
24487                 hasStyles = true;
24488                 break;
24489             }
24490             
24491             // update styles
24492             if (hasStyles) { 
24493                 var st = this.tb.fields.item(0);
24494                 
24495                 st.store.removeAll();
24496                
24497                 
24498                 var cn = sel.className.split(/\s+/);
24499                 
24500                 var avs = [];
24501                 if (this.styles['*']) {
24502                     
24503                     Roo.each(this.styles['*'], function(v) {
24504                         avs.push( [ v , cn.indexOf(v) > -1 ? 1 : 0 ] );         
24505                     });
24506                 }
24507                 if (this.styles[tn]) { 
24508                     Roo.each(this.styles[tn], function(v) {
24509                         avs.push( [ v , cn.indexOf(v) > -1 ? 1 : 0 ] );         
24510                     });
24511                 }
24512                 
24513                 st.store.loadData(avs);
24514                 st.collapse();
24515                 st.setValue(cn);
24516             }
24517             // flag our selected Node.
24518             this.tb.selectedNode = sel;
24519            
24520            
24521             Roo.menu.MenuMgr.hideAll();
24522
24523         }
24524         
24525         if (!updateFooter) {
24526             //this.footDisp.dom.innerHTML = ''; 
24527             return;
24528         }
24529         // update the footer
24530         //
24531         var html = '';
24532         
24533         this.footerEls = ans.reverse();
24534         Roo.each(this.footerEls, function(a,i) {
24535             if (!a) { return; }
24536             html += html.length ? ' &gt; '  :  '';
24537             
24538             html += '<span class="x-ed-loc-' + i + '">' + a.tagName + '</span>';
24539             
24540         });
24541        
24542         // 
24543         var sz = this.footDisp.up('td').getSize();
24544         this.footDisp.dom.style.width = (sz.width -10) + 'px';
24545         this.footDisp.dom.style.marginLeft = '5px';
24546         
24547         this.footDisp.dom.style.overflow = 'hidden';
24548         
24549         this.footDisp.dom.innerHTML = html;
24550             
24551         //this.editorsyncValue();
24552     },
24553      
24554     
24555    
24556        
24557     // private
24558     onDestroy : function(){
24559         if(this.rendered){
24560             
24561             this.tb.items.each(function(item){
24562                 if(item.menu){
24563                     item.menu.removeAll();
24564                     if(item.menu.el){
24565                         item.menu.el.destroy();
24566                     }
24567                 }
24568                 item.destroy();
24569             });
24570              
24571         }
24572     },
24573     onFirstFocus: function() {
24574         // need to do this for all the toolbars..
24575         this.tb.items.each(function(item){
24576            item.enable();
24577         });
24578     },
24579     buildToolbar: function(tlist, nm)
24580     {
24581         var editor = this.editor;
24582         var editorcore = this.editorcore;
24583          // create a new element.
24584         var wdiv = editor.wrap.createChild({
24585                 tag: 'div'
24586             }, editor.wrap.dom.firstChild.nextSibling, true);
24587         
24588        
24589         var tb = new Roo.Toolbar(wdiv);
24590         // add the name..
24591         
24592         tb.add(nm+ ":&nbsp;");
24593         
24594         var styles = [];
24595         for(var i in this.styles) {
24596             styles.push(i);
24597         }
24598         
24599         // styles...
24600         if (styles && styles.length) {
24601             
24602             // this needs a multi-select checkbox...
24603             tb.addField( new Roo.form.ComboBox({
24604                 store: new Roo.data.SimpleStore({
24605                     id : 'val',
24606                     fields: ['val', 'selected'],
24607                     data : [] 
24608                 }),
24609                 name : '-roo-edit-className',
24610                 attrname : 'className',
24611                 displayField: 'val',
24612                 typeAhead: false,
24613                 mode: 'local',
24614                 editable : false,
24615                 triggerAction: 'all',
24616                 emptyText:'Select Style',
24617                 selectOnFocus:true,
24618                 width: 130,
24619                 listeners : {
24620                     'select': function(c, r, i) {
24621                         // initial support only for on class per el..
24622                         tb.selectedNode.className =  r ? r.get('val') : '';
24623                         editorcore.syncValue();
24624                     }
24625                 }
24626     
24627             }));
24628         }
24629         
24630         var tbc = Roo.form.HtmlEditor.ToolbarContext;
24631         var tbops = tbc.options;
24632         
24633         for (var i in tlist) {
24634             
24635             var item = tlist[i];
24636             tb.add(item.title + ":&nbsp;");
24637             
24638             
24639             //optname == used so you can configure the options available..
24640             var opts = item.opts ? item.opts : false;
24641             if (item.optname) {
24642                 opts = tbops[item.optname];
24643            
24644             }
24645             
24646             if (opts) {
24647                 // opts == pulldown..
24648                 tb.addField( new Roo.form.ComboBox({
24649                     store:   typeof(tbc.stores[i]) != 'undefined' ?  Roo.factory(tbc.stores[i],Roo.data) : new Roo.data.SimpleStore({
24650                         id : 'val',
24651                         fields: ['val', 'display'],
24652                         data : opts  
24653                     }),
24654                     name : '-roo-edit-' + i,
24655                     attrname : i,
24656                     stylename : item.style ? item.style : false,
24657                     displayField: item.displayField ? item.displayField : 'val',
24658                     valueField :  'val',
24659                     typeAhead: false,
24660                     mode: typeof(tbc.stores[i]) != 'undefined'  ? 'remote' : 'local',
24661                     editable : false,
24662                     triggerAction: 'all',
24663                     emptyText:'Select',
24664                     selectOnFocus:true,
24665                     width: item.width ? item.width  : 130,
24666                     listeners : {
24667                         'select': function(c, r, i) {
24668                             if (c.stylename) {
24669                                 tb.selectedNode.style[c.stylename] =  r.get('val');
24670                                 return;
24671                             }
24672                             tb.selectedNode.setAttribute(c.attrname, r.get('val'));
24673                         }
24674                     }
24675
24676                 }));
24677                 continue;
24678                     
24679                  
24680                 
24681                 tb.addField( new Roo.form.TextField({
24682                     name: i,
24683                     width: 100,
24684                     //allowBlank:false,
24685                     value: ''
24686                 }));
24687                 continue;
24688             }
24689             tb.addField( new Roo.form.TextField({
24690                 name: '-roo-edit-' + i,
24691                 attrname : i,
24692                 
24693                 width: item.width,
24694                 //allowBlank:true,
24695                 value: '',
24696                 listeners: {
24697                     'change' : function(f, nv, ov) {
24698                         tb.selectedNode.setAttribute(f.attrname, nv);
24699                         editorcore.syncValue();
24700                     }
24701                 }
24702             }));
24703              
24704         }
24705         
24706         var _this = this;
24707         
24708         if(nm == 'BODY'){
24709             tb.addSeparator();
24710         
24711             tb.addButton( {
24712                 text: 'Stylesheets',
24713
24714                 listeners : {
24715                     click : function ()
24716                     {
24717                         _this.editor.fireEvent('stylesheetsclick', _this.editor);
24718                     }
24719                 }
24720             });
24721         }
24722         
24723         tb.addFill();
24724         tb.addButton( {
24725             text: 'Remove Tag',
24726     
24727             listeners : {
24728                 click : function ()
24729                 {
24730                     // remove
24731                     // undo does not work.
24732                      
24733                     var sn = tb.selectedNode;
24734                     
24735                     var pn = sn.parentNode;
24736                     
24737                     var stn =  sn.childNodes[0];
24738                     var en = sn.childNodes[sn.childNodes.length - 1 ];
24739                     while (sn.childNodes.length) {
24740                         var node = sn.childNodes[0];
24741                         sn.removeChild(node);
24742                         //Roo.log(node);
24743                         pn.insertBefore(node, sn);
24744                         
24745                     }
24746                     pn.removeChild(sn);
24747                     var range = editorcore.createRange();
24748         
24749                     range.setStart(stn,0);
24750                     range.setEnd(en,0); //????
24751                     //range.selectNode(sel);
24752                     
24753                     
24754                     var selection = editorcore.getSelection();
24755                     selection.removeAllRanges();
24756                     selection.addRange(range);
24757                     
24758                     
24759                     
24760                     //_this.updateToolbar(null, null, pn);
24761                     _this.updateToolbar(null, null, null);
24762                     _this.footDisp.dom.innerHTML = ''; 
24763                 }
24764             }
24765             
24766                     
24767                 
24768             
24769         });
24770         
24771         
24772         tb.el.on('click', function(e){
24773             e.preventDefault(); // what does this do?
24774         });
24775         tb.el.setVisibilityMode( Roo.Element.DISPLAY);
24776         tb.el.hide();
24777         tb.name = nm;
24778         // dont need to disable them... as they will get hidden
24779         return tb;
24780          
24781         
24782     },
24783     buildFooter : function()
24784     {
24785         
24786         var fel = this.editor.wrap.createChild();
24787         this.footer = new Roo.Toolbar(fel);
24788         // toolbar has scrolly on left / right?
24789         var footDisp= new Roo.Toolbar.Fill();
24790         var _t = this;
24791         this.footer.add(
24792             {
24793                 text : '&lt;',
24794                 xtype: 'Button',
24795                 handler : function() {
24796                     _t.footDisp.scrollTo('left',0,true)
24797                 }
24798             }
24799         );
24800         this.footer.add( footDisp );
24801         this.footer.add( 
24802             {
24803                 text : '&gt;',
24804                 xtype: 'Button',
24805                 handler : function() {
24806                     // no animation..
24807                     _t.footDisp.select('span').last().scrollIntoView(_t.footDisp,true);
24808                 }
24809             }
24810         );
24811         var fel = Roo.get(footDisp.el);
24812         fel.addClass('x-editor-context');
24813         this.footDispWrap = fel; 
24814         this.footDispWrap.overflow  = 'hidden';
24815         
24816         this.footDisp = fel.createChild();
24817         this.footDispWrap.on('click', this.onContextClick, this)
24818         
24819         
24820     },
24821     onContextClick : function (ev,dom)
24822     {
24823         ev.preventDefault();
24824         var  cn = dom.className;
24825         //Roo.log(cn);
24826         if (!cn.match(/x-ed-loc-/)) {
24827             return;
24828         }
24829         var n = cn.split('-').pop();
24830         var ans = this.footerEls;
24831         var sel = ans[n];
24832         
24833          // pick
24834         var range = this.editorcore.createRange();
24835         
24836         range.selectNodeContents(sel);
24837         //range.selectNode(sel);
24838         
24839         
24840         var selection = this.editorcore.getSelection();
24841         selection.removeAllRanges();
24842         selection.addRange(range);
24843         
24844         
24845         
24846         this.updateToolbar(null, null, sel);
24847         
24848         
24849     }
24850     
24851     
24852     
24853     
24854     
24855 });
24856
24857
24858
24859
24860
24861 /*
24862  * Based on:
24863  * Ext JS Library 1.1.1
24864  * Copyright(c) 2006-2007, Ext JS, LLC.
24865  *
24866  * Originally Released Under LGPL - original licence link has changed is not relivant.
24867  *
24868  * Fork - LGPL
24869  * <script type="text/javascript">
24870  */
24871  
24872 /**
24873  * @class Roo.form.BasicForm
24874  * @extends Roo.util.Observable
24875  * Supplies the functionality to do "actions" on forms and initialize Roo.form.Field types on existing markup.
24876  * @constructor
24877  * @param {String/HTMLElement/Roo.Element} el The form element or its id
24878  * @param {Object} config Configuration options
24879  */
24880 Roo.form.BasicForm = function(el, config){
24881     this.allItems = [];
24882     this.childForms = [];
24883     Roo.apply(this, config);
24884     /*
24885      * The Roo.form.Field items in this form.
24886      * @type MixedCollection
24887      */
24888      
24889      
24890     this.items = new Roo.util.MixedCollection(false, function(o){
24891         return o.id || (o.id = Roo.id());
24892     });
24893     this.addEvents({
24894         /**
24895          * @event beforeaction
24896          * Fires before any action is performed. Return false to cancel the action.
24897          * @param {Form} this
24898          * @param {Action} action The action to be performed
24899          */
24900         beforeaction: true,
24901         /**
24902          * @event actionfailed
24903          * Fires when an action fails.
24904          * @param {Form} this
24905          * @param {Action} action The action that failed
24906          */
24907         actionfailed : true,
24908         /**
24909          * @event actioncomplete
24910          * Fires when an action is completed.
24911          * @param {Form} this
24912          * @param {Action} action The action that completed
24913          */
24914         actioncomplete : true
24915     });
24916     if(el){
24917         this.initEl(el);
24918     }
24919     Roo.form.BasicForm.superclass.constructor.call(this);
24920     
24921     Roo.form.BasicForm.popover.apply();
24922 };
24923
24924 Roo.extend(Roo.form.BasicForm, Roo.util.Observable, {
24925     /**
24926      * @cfg {String} method
24927      * The request method to use (GET or POST) for form actions if one isn't supplied in the action options.
24928      */
24929     /**
24930      * @cfg {DataReader} reader
24931      * An Roo.data.DataReader (e.g. {@link Roo.data.XmlReader}) to be used to read data when executing "load" actions.
24932      * This is optional as there is built-in support for processing JSON.
24933      */
24934     /**
24935      * @cfg {DataReader} errorReader
24936      * An Roo.data.DataReader (e.g. {@link Roo.data.XmlReader}) to be used to read data when reading validation errors on "submit" actions.
24937      * This is completely optional as there is built-in support for processing JSON.
24938      */
24939     /**
24940      * @cfg {String} url
24941      * The URL to use for form actions if one isn't supplied in the action options.
24942      */
24943     /**
24944      * @cfg {Boolean} fileUpload
24945      * Set to true if this form is a file upload.
24946      */
24947      
24948     /**
24949      * @cfg {Object} baseParams
24950      * Parameters to pass with all requests. e.g. baseParams: {id: '123', foo: 'bar'}.
24951      */
24952      /**
24953      
24954     /**
24955      * @cfg {Number} timeout Timeout for form actions in seconds (default is 30 seconds).
24956      */
24957     timeout: 30,
24958
24959     // private
24960     activeAction : null,
24961
24962     /**
24963      * @cfg {Boolean} trackResetOnLoad If set to true, form.reset() resets to the last loaded
24964      * or setValues() data instead of when the form was first created.
24965      */
24966     trackResetOnLoad : false,
24967     
24968     
24969     /**
24970      * childForms - used for multi-tab forms
24971      * @type {Array}
24972      */
24973     childForms : false,
24974     
24975     /**
24976      * allItems - full list of fields.
24977      * @type {Array}
24978      */
24979     allItems : false,
24980     
24981     /**
24982      * By default wait messages are displayed with Roo.MessageBox.wait. You can target a specific
24983      * element by passing it or its id or mask the form itself by passing in true.
24984      * @type Mixed
24985      */
24986     waitMsgTarget : false,
24987     
24988     /**
24989      * @type Boolean
24990      */
24991     disableMask : false,
24992     
24993     /**
24994      * @cfg {Boolean} errorMask (true|false) default false
24995      */
24996     errorMask : false,
24997     
24998     /**
24999      * @cfg {Number} maskOffset Default 100
25000      */
25001     maskOffset : 100,
25002
25003     // private
25004     initEl : function(el){
25005         this.el = Roo.get(el);
25006         this.id = this.el.id || Roo.id();
25007         this.el.on('submit', this.onSubmit, this);
25008         this.el.addClass('x-form');
25009     },
25010
25011     // private
25012     onSubmit : function(e){
25013         e.stopEvent();
25014     },
25015
25016     /**
25017      * Returns true if client-side validation on the form is successful.
25018      * @return Boolean
25019      */
25020     isValid : function(){
25021         var valid = true;
25022         var target = false;
25023         this.items.each(function(f){
25024             if(f.validate()){
25025                 return;
25026             }
25027             
25028             valid = false;
25029                 
25030             if(!target && f.el.isVisible(true)){
25031                 target = f;
25032             }
25033         });
25034         
25035         if(this.errorMask && !valid){
25036             Roo.form.BasicForm.popover.mask(this, target);
25037         }
25038         
25039         return valid;
25040     },
25041
25042     /**
25043      * DEPRICATED Returns true if any fields in this form have changed since their original load. 
25044      * @return Boolean
25045      */
25046     isDirty : function(){
25047         var dirty = false;
25048         this.items.each(function(f){
25049            if(f.isDirty()){
25050                dirty = true;
25051                return false;
25052            }
25053         });
25054         return dirty;
25055     },
25056     
25057     /**
25058      * Returns true if any fields in this form have changed since their original load. (New version)
25059      * @return Boolean
25060      */
25061     
25062     hasChanged : function()
25063     {
25064         var dirty = false;
25065         this.items.each(function(f){
25066            if(f.hasChanged()){
25067                dirty = true;
25068                return false;
25069            }
25070         });
25071         return dirty;
25072         
25073     },
25074     /**
25075      * Resets all hasChanged to 'false' -
25076      * The old 'isDirty' used 'original value..' however this breaks reset() and a few other things.
25077      * So hasChanged storage is only to be used for this purpose
25078      * @return Boolean
25079      */
25080     resetHasChanged : function()
25081     {
25082         this.items.each(function(f){
25083            f.resetHasChanged();
25084         });
25085         
25086     },
25087     
25088     
25089     /**
25090      * Performs a predefined action (submit or load) or custom actions you define on this form.
25091      * @param {String} actionName The name of the action type
25092      * @param {Object} options (optional) The options to pass to the action.  All of the config options listed
25093      * below are supported by both the submit and load actions unless otherwise noted (custom actions could also
25094      * accept other config options):
25095      * <pre>
25096 Property          Type             Description
25097 ----------------  ---------------  ----------------------------------------------------------------------------------
25098 url               String           The url for the action (defaults to the form's url)
25099 method            String           The form method to use (defaults to the form's method, or POST if not defined)
25100 params            String/Object    The params to pass (defaults to the form's baseParams, or none if not defined)
25101 clientValidation  Boolean          Applies to submit only.  Pass true to call form.isValid() prior to posting to
25102                                    validate the form on the client (defaults to false)
25103      * </pre>
25104      * @return {BasicForm} this
25105      */
25106     doAction : function(action, options){
25107         if(typeof action == 'string'){
25108             action = new Roo.form.Action.ACTION_TYPES[action](this, options);
25109         }
25110         if(this.fireEvent('beforeaction', this, action) !== false){
25111             this.beforeAction(action);
25112             action.run.defer(100, action);
25113         }
25114         return this;
25115     },
25116
25117     /**
25118      * Shortcut to do a submit action.
25119      * @param {Object} options The options to pass to the action (see {@link #doAction} for details)
25120      * @return {BasicForm} this
25121      */
25122     submit : function(options){
25123         this.doAction('submit', options);
25124         return this;
25125     },
25126
25127     /**
25128      * Shortcut to do a load action.
25129      * @param {Object} options The options to pass to the action (see {@link #doAction} for details)
25130      * @return {BasicForm} this
25131      */
25132     load : function(options){
25133         this.doAction('load', options);
25134         return this;
25135     },
25136
25137     /**
25138      * Persists the values in this form into the passed Roo.data.Record object in a beginEdit/endEdit block.
25139      * @param {Record} record The record to edit
25140      * @return {BasicForm} this
25141      */
25142     updateRecord : function(record){
25143         record.beginEdit();
25144         var fs = record.fields;
25145         fs.each(function(f){
25146             var field = this.findField(f.name);
25147             if(field){
25148                 record.set(f.name, field.getValue());
25149             }
25150         }, this);
25151         record.endEdit();
25152         return this;
25153     },
25154
25155     /**
25156      * Loads an Roo.data.Record into this form.
25157      * @param {Record} record The record to load
25158      * @return {BasicForm} this
25159      */
25160     loadRecord : function(record){
25161         this.setValues(record.data);
25162         return this;
25163     },
25164
25165     // private
25166     beforeAction : function(action){
25167         var o = action.options;
25168         
25169         if(!this.disableMask) {
25170             if(this.waitMsgTarget === true){
25171                 this.el.mask(o.waitMsg || "Sending", 'x-mask-loading');
25172             }else if(this.waitMsgTarget){
25173                 this.waitMsgTarget = Roo.get(this.waitMsgTarget);
25174                 this.waitMsgTarget.mask(o.waitMsg || "Sending", 'x-mask-loading');
25175             }else {
25176                 Roo.MessageBox.wait(o.waitMsg || "Sending", o.waitTitle || this.waitTitle || 'Please Wait...');
25177             }
25178         }
25179         
25180          
25181     },
25182
25183     // private
25184     afterAction : function(action, success){
25185         this.activeAction = null;
25186         var o = action.options;
25187         
25188         if(!this.disableMask) {
25189             if(this.waitMsgTarget === true){
25190                 this.el.unmask();
25191             }else if(this.waitMsgTarget){
25192                 this.waitMsgTarget.unmask();
25193             }else{
25194                 Roo.MessageBox.updateProgress(1);
25195                 Roo.MessageBox.hide();
25196             }
25197         }
25198         
25199         if(success){
25200             if(o.reset){
25201                 this.reset();
25202             }
25203             Roo.callback(o.success, o.scope, [this, action]);
25204             this.fireEvent('actioncomplete', this, action);
25205             
25206         }else{
25207             
25208             // failure condition..
25209             // we have a scenario where updates need confirming.
25210             // eg. if a locking scenario exists..
25211             // we look for { errors : { needs_confirm : true }} in the response.
25212             if (
25213                 (typeof(action.result) != 'undefined')  &&
25214                 (typeof(action.result.errors) != 'undefined')  &&
25215                 (typeof(action.result.errors.needs_confirm) != 'undefined')
25216            ){
25217                 var _t = this;
25218                 Roo.MessageBox.confirm(
25219                     "Change requires confirmation",
25220                     action.result.errorMsg,
25221                     function(r) {
25222                         if (r != 'yes') {
25223                             return;
25224                         }
25225                         _t.doAction('submit', { params :  { _submit_confirmed : 1 } }  );
25226                     }
25227                     
25228                 );
25229                 
25230                 
25231                 
25232                 return;
25233             }
25234             
25235             Roo.callback(o.failure, o.scope, [this, action]);
25236             // show an error message if no failed handler is set..
25237             if (!this.hasListener('actionfailed')) {
25238                 Roo.MessageBox.alert("Error",
25239                     (typeof(action.result) != 'undefined' && typeof(action.result.errorMsg) != 'undefined') ?
25240                         action.result.errorMsg :
25241                         "Saving Failed, please check your entries or try again"
25242                 );
25243             }
25244             
25245             this.fireEvent('actionfailed', this, action);
25246         }
25247         
25248     },
25249
25250     /**
25251      * Find a Roo.form.Field in this form by id, dataIndex, name or hiddenName
25252      * @param {String} id The value to search for
25253      * @return Field
25254      */
25255     findField : function(id){
25256         var field = this.items.get(id);
25257         if(!field){
25258             this.items.each(function(f){
25259                 if(f.isFormField && (f.dataIndex == id || f.id == id || f.getName() == id)){
25260                     field = f;
25261                     return false;
25262                 }
25263             });
25264         }
25265         return field || null;
25266     },
25267
25268     /**
25269      * Add a secondary form to this one, 
25270      * Used to provide tabbed forms. One form is primary, with hidden values 
25271      * which mirror the elements from the other forms.
25272      * 
25273      * @param {Roo.form.Form} form to add.
25274      * 
25275      */
25276     addForm : function(form)
25277     {
25278        
25279         if (this.childForms.indexOf(form) > -1) {
25280             // already added..
25281             return;
25282         }
25283         this.childForms.push(form);
25284         var n = '';
25285         Roo.each(form.allItems, function (fe) {
25286             
25287             n = typeof(fe.getName) == 'undefined' ? fe.name : fe.getName();
25288             if (this.findField(n)) { // already added..
25289                 return;
25290             }
25291             var add = new Roo.form.Hidden({
25292                 name : n
25293             });
25294             add.render(this.el);
25295             
25296             this.add( add );
25297         }, this);
25298         
25299     },
25300     /**
25301      * Mark fields in this form invalid in bulk.
25302      * @param {Array/Object} errors Either an array in the form [{id:'fieldId', msg:'The message'},...] or an object hash of {id: msg, id2: msg2}
25303      * @return {BasicForm} this
25304      */
25305     markInvalid : function(errors){
25306         if(errors instanceof Array){
25307             for(var i = 0, len = errors.length; i < len; i++){
25308                 var fieldError = errors[i];
25309                 var f = this.findField(fieldError.id);
25310                 if(f){
25311                     f.markInvalid(fieldError.msg);
25312                 }
25313             }
25314         }else{
25315             var field, id;
25316             for(id in errors){
25317                 if(typeof errors[id] != 'function' && (field = this.findField(id))){
25318                     field.markInvalid(errors[id]);
25319                 }
25320             }
25321         }
25322         Roo.each(this.childForms || [], function (f) {
25323             f.markInvalid(errors);
25324         });
25325         
25326         return this;
25327     },
25328
25329     /**
25330      * Set values for fields in this form in bulk.
25331      * @param {Array/Object} values Either an array in the form [{id:'fieldId', value:'foo'},...] or an object hash of {id: value, id2: value2}
25332      * @return {BasicForm} this
25333      */
25334     setValues : function(values){
25335         if(values instanceof Array){ // array of objects
25336             for(var i = 0, len = values.length; i < len; i++){
25337                 var v = values[i];
25338                 var f = this.findField(v.id);
25339                 if(f){
25340                     f.setValue(v.value);
25341                     if(this.trackResetOnLoad){
25342                         f.originalValue = f.getValue();
25343                     }
25344                 }
25345             }
25346         }else{ // object hash
25347             var field, id;
25348             for(id in values){
25349                 if(typeof values[id] != 'function' && (field = this.findField(id))){
25350                     
25351                     if (field.setFromData && 
25352                         field.valueField && 
25353                         field.displayField &&
25354                         // combos' with local stores can 
25355                         // be queried via setValue()
25356                         // to set their value..
25357                         (field.store && !field.store.isLocal)
25358                         ) {
25359                         // it's a combo
25360                         var sd = { };
25361                         sd[field.valueField] = typeof(values[field.hiddenName]) == 'undefined' ? '' : values[field.hiddenName];
25362                         sd[field.displayField] = typeof(values[field.name]) == 'undefined' ? '' : values[field.name];
25363                         field.setFromData(sd);
25364                         
25365                     } else {
25366                         field.setValue(values[id]);
25367                     }
25368                     
25369                     
25370                     if(this.trackResetOnLoad){
25371                         field.originalValue = field.getValue();
25372                     }
25373                 }
25374             }
25375         }
25376         this.resetHasChanged();
25377         
25378         
25379         Roo.each(this.childForms || [], function (f) {
25380             f.setValues(values);
25381             f.resetHasChanged();
25382         });
25383                 
25384         return this;
25385     },
25386  
25387     /**
25388      * Returns the fields in this form as an object with key/value pairs. If multiple fields exist with the same name
25389      * they are returned as an array.
25390      * @param {Boolean} asString
25391      * @return {Object}
25392      */
25393     getValues : function(asString){
25394         if (this.childForms) {
25395             // copy values from the child forms
25396             Roo.each(this.childForms, function (f) {
25397                 this.setValues(f.getValues());
25398             }, this);
25399         }
25400         
25401         // use formdata
25402         if (typeof(FormData) != 'undefined' && asString !== true) {
25403             // this relies on a 'recent' version of chrome apparently...
25404             try {
25405                 var fd = (new FormData(this.el.dom)).entries();
25406                 var ret = {};
25407                 var ent = fd.next();
25408                 while (!ent.done) {
25409                     ret[ent.value[0]] = ent.value[1]; // not sure how this will handle duplicates..
25410                     ent = fd.next();
25411                 };
25412                 return ret;
25413             } catch(e) {
25414                 
25415             }
25416             
25417         }
25418         
25419         
25420         var fs = Roo.lib.Ajax.serializeForm(this.el.dom);
25421         if(asString === true){
25422             return fs;
25423         }
25424         return Roo.urlDecode(fs);
25425     },
25426     
25427     /**
25428      * Returns the fields in this form as an object with key/value pairs. 
25429      * This differs from getValues as it calls getValue on each child item, rather than using dom data.
25430      * @return {Object}
25431      */
25432     getFieldValues : function(with_hidden)
25433     {
25434         if (this.childForms) {
25435             // copy values from the child forms
25436             // should this call getFieldValues - probably not as we do not currently copy
25437             // hidden fields when we generate..
25438             Roo.each(this.childForms, function (f) {
25439                 this.setValues(f.getValues());
25440             }, this);
25441         }
25442         
25443         var ret = {};
25444         this.items.each(function(f){
25445             if (!f.getName()) {
25446                 return;
25447             }
25448             var v = f.getValue();
25449             if (f.inputType =='radio') {
25450                 if (typeof(ret[f.getName()]) == 'undefined') {
25451                     ret[f.getName()] = ''; // empty..
25452                 }
25453                 
25454                 if (!f.el.dom.checked) {
25455                     return;
25456                     
25457                 }
25458                 v = f.el.dom.value;
25459                 
25460             }
25461             
25462             // not sure if this supported any more..
25463             if ((typeof(v) == 'object') && f.getRawValue) {
25464                 v = f.getRawValue() ; // dates..
25465             }
25466             // combo boxes where name != hiddenName...
25467             if (f.name != f.getName()) {
25468                 ret[f.name] = f.getRawValue();
25469             }
25470             ret[f.getName()] = v;
25471         });
25472         
25473         return ret;
25474     },
25475
25476     /**
25477      * Clears all invalid messages in this form.
25478      * @return {BasicForm} this
25479      */
25480     clearInvalid : function(){
25481         this.items.each(function(f){
25482            f.clearInvalid();
25483         });
25484         
25485         Roo.each(this.childForms || [], function (f) {
25486             f.clearInvalid();
25487         });
25488         
25489         
25490         return this;
25491     },
25492
25493     /**
25494      * Resets this form.
25495      * @return {BasicForm} this
25496      */
25497     reset : function(){
25498         this.items.each(function(f){
25499             f.reset();
25500         });
25501         
25502         Roo.each(this.childForms || [], function (f) {
25503             f.reset();
25504         });
25505         this.resetHasChanged();
25506         
25507         return this;
25508     },
25509
25510     /**
25511      * Add Roo.form components to this form.
25512      * @param {Field} field1
25513      * @param {Field} field2 (optional)
25514      * @param {Field} etc (optional)
25515      * @return {BasicForm} this
25516      */
25517     add : function(){
25518         this.items.addAll(Array.prototype.slice.call(arguments, 0));
25519         return this;
25520     },
25521
25522
25523     /**
25524      * Removes a field from the items collection (does NOT remove its markup).
25525      * @param {Field} field
25526      * @return {BasicForm} this
25527      */
25528     remove : function(field){
25529         this.items.remove(field);
25530         return this;
25531     },
25532
25533     /**
25534      * Looks at the fields in this form, checks them for an id attribute,
25535      * and calls applyTo on the existing dom element with that id.
25536      * @return {BasicForm} this
25537      */
25538     render : function(){
25539         this.items.each(function(f){
25540             if(f.isFormField && !f.rendered && document.getElementById(f.id)){ // if the element exists
25541                 f.applyTo(f.id);
25542             }
25543         });
25544         return this;
25545     },
25546
25547     /**
25548      * Calls {@link Ext#apply} for all fields in this form with the passed object.
25549      * @param {Object} values
25550      * @return {BasicForm} this
25551      */
25552     applyToFields : function(o){
25553         this.items.each(function(f){
25554            Roo.apply(f, o);
25555         });
25556         return this;
25557     },
25558
25559     /**
25560      * Calls {@link Ext#applyIf} for all field in this form with the passed object.
25561      * @param {Object} values
25562      * @return {BasicForm} this
25563      */
25564     applyIfToFields : function(o){
25565         this.items.each(function(f){
25566            Roo.applyIf(f, o);
25567         });
25568         return this;
25569     }
25570 });
25571
25572 // back compat
25573 Roo.BasicForm = Roo.form.BasicForm;
25574
25575 Roo.apply(Roo.form.BasicForm, {
25576     
25577     popover : {
25578         
25579         padding : 5,
25580         
25581         isApplied : false,
25582         
25583         isMasked : false,
25584         
25585         form : false,
25586         
25587         target : false,
25588         
25589         intervalID : false,
25590         
25591         maskEl : false,
25592         
25593         apply : function()
25594         {
25595             if(this.isApplied){
25596                 return;
25597             }
25598             
25599             this.maskEl = {
25600                 top : Roo.DomHelper.append(Roo.get(document.body), { tag: "div", cls:"x-dlg-mask roo-form-top-mask" }, true),
25601                 left : Roo.DomHelper.append(Roo.get(document.body), { tag: "div", cls:"x-dlg-mask roo-form-left-mask" }, true),
25602                 bottom : Roo.DomHelper.append(Roo.get(document.body), { tag: "div", cls:"x-dlg-mask roo-form-bottom-mask" }, true),
25603                 right : Roo.DomHelper.append(Roo.get(document.body), { tag: "div", cls:"x-dlg-mask roo-form-right-mask" }, true)
25604             };
25605             
25606             this.maskEl.top.enableDisplayMode("block");
25607             this.maskEl.left.enableDisplayMode("block");
25608             this.maskEl.bottom.enableDisplayMode("block");
25609             this.maskEl.right.enableDisplayMode("block");
25610             
25611             Roo.get(document.body).on('click', function(){
25612                 this.unmask();
25613             }, this);
25614             
25615             Roo.get(document.body).on('touchstart', function(){
25616                 this.unmask();
25617             }, this);
25618             
25619             this.isApplied = true
25620         },
25621         
25622         mask : function(form, target)
25623         {
25624             this.form = form;
25625             
25626             this.target = target;
25627             
25628             if(!this.form.errorMask || !target.el){
25629                 return;
25630             }
25631             
25632             var scrollable = this.target.el.findScrollableParent() || this.target.el.findParent('div.x-layout-active-content', 100, true) || Roo.get(document.body);
25633             
25634             var ot = this.target.el.calcOffsetsTo(scrollable);
25635             
25636             var scrollTo = ot[1] - this.form.maskOffset;
25637             
25638             scrollTo = Math.min(scrollTo, scrollable.dom.scrollHeight);
25639             
25640             scrollable.scrollTo('top', scrollTo);
25641             
25642             var el = this.target.wrap || this.target.el;
25643             
25644             var box = el.getBox();
25645             
25646             this.maskEl.top.setStyle('position', 'absolute');
25647             this.maskEl.top.setStyle('z-index', 10000);
25648             this.maskEl.top.setSize(Roo.lib.Dom.getDocumentWidth(), box.y - this.padding);
25649             this.maskEl.top.setLeft(0);
25650             this.maskEl.top.setTop(0);
25651             this.maskEl.top.show();
25652             
25653             this.maskEl.left.setStyle('position', 'absolute');
25654             this.maskEl.left.setStyle('z-index', 10000);
25655             this.maskEl.left.setSize(box.x - this.padding, box.height + this.padding * 2);
25656             this.maskEl.left.setLeft(0);
25657             this.maskEl.left.setTop(box.y - this.padding);
25658             this.maskEl.left.show();
25659
25660             this.maskEl.bottom.setStyle('position', 'absolute');
25661             this.maskEl.bottom.setStyle('z-index', 10000);
25662             this.maskEl.bottom.setSize(Roo.lib.Dom.getDocumentWidth(), Roo.lib.Dom.getDocumentHeight() - box.bottom - this.padding);
25663             this.maskEl.bottom.setLeft(0);
25664             this.maskEl.bottom.setTop(box.bottom + this.padding);
25665             this.maskEl.bottom.show();
25666
25667             this.maskEl.right.setStyle('position', 'absolute');
25668             this.maskEl.right.setStyle('z-index', 10000);
25669             this.maskEl.right.setSize(Roo.lib.Dom.getDocumentWidth() - box.right - this.padding, box.height + this.padding * 2);
25670             this.maskEl.right.setLeft(box.right + this.padding);
25671             this.maskEl.right.setTop(box.y - this.padding);
25672             this.maskEl.right.show();
25673
25674             this.intervalID = window.setInterval(function() {
25675                 Roo.form.BasicForm.popover.unmask();
25676             }, 10000);
25677
25678             window.onwheel = function(){ return false;};
25679             
25680             (function(){ this.isMasked = true; }).defer(500, this);
25681             
25682         },
25683         
25684         unmask : function()
25685         {
25686             if(!this.isApplied || !this.isMasked || !this.form || !this.target || !this.form.errorMask){
25687                 return;
25688             }
25689             
25690             this.maskEl.top.setStyle('position', 'absolute');
25691             this.maskEl.top.setSize(0, 0).setXY([0, 0]);
25692             this.maskEl.top.hide();
25693
25694             this.maskEl.left.setStyle('position', 'absolute');
25695             this.maskEl.left.setSize(0, 0).setXY([0, 0]);
25696             this.maskEl.left.hide();
25697
25698             this.maskEl.bottom.setStyle('position', 'absolute');
25699             this.maskEl.bottom.setSize(0, 0).setXY([0, 0]);
25700             this.maskEl.bottom.hide();
25701
25702             this.maskEl.right.setStyle('position', 'absolute');
25703             this.maskEl.right.setSize(0, 0).setXY([0, 0]);
25704             this.maskEl.right.hide();
25705             
25706             window.onwheel = function(){ return true;};
25707             
25708             if(this.intervalID){
25709                 window.clearInterval(this.intervalID);
25710                 this.intervalID = false;
25711             }
25712             
25713             this.isMasked = false;
25714             
25715         }
25716         
25717     }
25718     
25719 });/*
25720  * Based on:
25721  * Ext JS Library 1.1.1
25722  * Copyright(c) 2006-2007, Ext JS, LLC.
25723  *
25724  * Originally Released Under LGPL - original licence link has changed is not relivant.
25725  *
25726  * Fork - LGPL
25727  * <script type="text/javascript">
25728  */
25729
25730 /**
25731  * @class Roo.form.Form
25732  * @extends Roo.form.BasicForm
25733  * Adds the ability to dynamically render forms with JavaScript to {@link Roo.form.BasicForm}.
25734  * @constructor
25735  * @param {Object} config Configuration options
25736  */
25737 Roo.form.Form = function(config){
25738     var xitems =  [];
25739     if (config.items) {
25740         xitems = config.items;
25741         delete config.items;
25742     }
25743    
25744     
25745     Roo.form.Form.superclass.constructor.call(this, null, config);
25746     this.url = this.url || this.action;
25747     if(!this.root){
25748         this.root = new Roo.form.Layout(Roo.applyIf({
25749             id: Roo.id()
25750         }, config));
25751     }
25752     this.active = this.root;
25753     /**
25754      * Array of all the buttons that have been added to this form via {@link addButton}
25755      * @type Array
25756      */
25757     this.buttons = [];
25758     this.allItems = [];
25759     this.addEvents({
25760         /**
25761          * @event clientvalidation
25762          * If the monitorValid config option is true, this event fires repetitively to notify of valid state
25763          * @param {Form} this
25764          * @param {Boolean} valid true if the form has passed client-side validation
25765          */
25766         clientvalidation: true,
25767         /**
25768          * @event rendered
25769          * Fires when the form is rendered
25770          * @param {Roo.form.Form} form
25771          */
25772         rendered : true
25773     });
25774     
25775     if (this.progressUrl) {
25776             // push a hidden field onto the list of fields..
25777             this.addxtype( {
25778                     xns: Roo.form, 
25779                     xtype : 'Hidden', 
25780                     name : 'UPLOAD_IDENTIFIER' 
25781             });
25782         }
25783         
25784     
25785     Roo.each(xitems, this.addxtype, this);
25786     
25787 };
25788
25789 Roo.extend(Roo.form.Form, Roo.form.BasicForm, {
25790     /**
25791      * @cfg {Number} labelWidth The width of labels. This property cascades to child containers.
25792      */
25793     /**
25794      * @cfg {String} itemCls A css class to apply to the x-form-item of fields. This property cascades to child containers.
25795      */
25796     /**
25797      * @cfg {String} buttonAlign Valid values are "left," "center" and "right" (defaults to "center")
25798      */
25799     buttonAlign:'center',
25800
25801     /**
25802      * @cfg {Number} minButtonWidth Minimum width of all buttons in pixels (defaults to 75)
25803      */
25804     minButtonWidth:75,
25805
25806     /**
25807      * @cfg {String} labelAlign Valid values are "left," "top" and "right" (defaults to "left").
25808      * This property cascades to child containers if not set.
25809      */
25810     labelAlign:'left',
25811
25812     /**
25813      * @cfg {Boolean} monitorValid If true the form monitors its valid state <b>client-side</b> and
25814      * fires a looping event with that state. This is required to bind buttons to the valid
25815      * state using the config value formBind:true on the button.
25816      */
25817     monitorValid : false,
25818
25819     /**
25820      * @cfg {Number} monitorPoll The milliseconds to poll valid state, ignored if monitorValid is not true (defaults to 200)
25821      */
25822     monitorPoll : 200,
25823     
25824     /**
25825      * @cfg {String} progressUrl - Url to return progress data 
25826      */
25827     
25828     progressUrl : false,
25829     /**
25830      * @cfg {boolean|FormData} formData - true to use new 'FormData' post, or set to a new FormData({dom form}) Object, if
25831      * sending a formdata with extra parameters - eg uploaded elements.
25832      */
25833     
25834     formData : false,
25835     
25836     /**
25837      * Opens a new {@link Roo.form.Column} container in the layout stack. If fields are passed after the config, the
25838      * fields are added and the column is closed. If no fields are passed the column remains open
25839      * until end() is called.
25840      * @param {Object} config The config to pass to the column
25841      * @param {Field} field1 (optional)
25842      * @param {Field} field2 (optional)
25843      * @param {Field} etc (optional)
25844      * @return Column The column container object
25845      */
25846     column : function(c){
25847         var col = new Roo.form.Column(c);
25848         this.start(col);
25849         if(arguments.length > 1){ // duplicate code required because of Opera
25850             this.add.apply(this, Array.prototype.slice.call(arguments, 1));
25851             this.end();
25852         }
25853         return col;
25854     },
25855
25856     /**
25857      * Opens a new {@link Roo.form.FieldSet} container in the layout stack. If fields are passed after the config, the
25858      * fields are added and the fieldset is closed. If no fields are passed the fieldset remains open
25859      * until end() is called.
25860      * @param {Object} config The config to pass to the fieldset
25861      * @param {Field} field1 (optional)
25862      * @param {Field} field2 (optional)
25863      * @param {Field} etc (optional)
25864      * @return FieldSet The fieldset container object
25865      */
25866     fieldset : function(c){
25867         var fs = new Roo.form.FieldSet(c);
25868         this.start(fs);
25869         if(arguments.length > 1){ // duplicate code required because of Opera
25870             this.add.apply(this, Array.prototype.slice.call(arguments, 1));
25871             this.end();
25872         }
25873         return fs;
25874     },
25875
25876     /**
25877      * Opens a new {@link Roo.form.Layout} container in the layout stack. If fields are passed after the config, the
25878      * fields are added and the container is closed. If no fields are passed the container remains open
25879      * until end() is called.
25880      * @param {Object} config The config to pass to the Layout
25881      * @param {Field} field1 (optional)
25882      * @param {Field} field2 (optional)
25883      * @param {Field} etc (optional)
25884      * @return Layout The container object
25885      */
25886     container : function(c){
25887         var l = new Roo.form.Layout(c);
25888         this.start(l);
25889         if(arguments.length > 1){ // duplicate code required because of Opera
25890             this.add.apply(this, Array.prototype.slice.call(arguments, 1));
25891             this.end();
25892         }
25893         return l;
25894     },
25895
25896     /**
25897      * Opens the passed container in the layout stack. The container can be any {@link Roo.form.Layout} or subclass.
25898      * @param {Object} container A Roo.form.Layout or subclass of Layout
25899      * @return {Form} this
25900      */
25901     start : function(c){
25902         // cascade label info
25903         Roo.applyIf(c, {'labelAlign': this.active.labelAlign, 'labelWidth': this.active.labelWidth, 'itemCls': this.active.itemCls});
25904         this.active.stack.push(c);
25905         c.ownerCt = this.active;
25906         this.active = c;
25907         return this;
25908     },
25909
25910     /**
25911      * Closes the current open container
25912      * @return {Form} this
25913      */
25914     end : function(){
25915         if(this.active == this.root){
25916             return this;
25917         }
25918         this.active = this.active.ownerCt;
25919         return this;
25920     },
25921
25922     /**
25923      * Add Roo.form components to the current open container (e.g. column, fieldset, etc.).  Fields added via this method
25924      * can also be passed with an additional property of fieldLabel, which if supplied, will provide the text to display
25925      * as the label of the field.
25926      * @param {Field} field1
25927      * @param {Field} field2 (optional)
25928      * @param {Field} etc. (optional)
25929      * @return {Form} this
25930      */
25931     add : function(){
25932         this.active.stack.push.apply(this.active.stack, arguments);
25933         this.allItems.push.apply(this.allItems,arguments);
25934         var r = [];
25935         for(var i = 0, a = arguments, len = a.length; i < len; i++) {
25936             if(a[i].isFormField){
25937                 r.push(a[i]);
25938             }
25939         }
25940         if(r.length > 0){
25941             Roo.form.Form.superclass.add.apply(this, r);
25942         }
25943         return this;
25944     },
25945     
25946
25947     
25948     
25949     
25950      /**
25951      * Find any element that has been added to a form, using it's ID or name
25952      * This can include framesets, columns etc. along with regular fields..
25953      * @param {String} id - id or name to find.
25954      
25955      * @return {Element} e - or false if nothing found.
25956      */
25957     findbyId : function(id)
25958     {
25959         var ret = false;
25960         if (!id) {
25961             return ret;
25962         }
25963         Roo.each(this.allItems, function(f){
25964             if (f.id == id || f.name == id ){
25965                 ret = f;
25966                 return false;
25967             }
25968         });
25969         return ret;
25970     },
25971
25972     
25973     
25974     /**
25975      * Render this form into the passed container. This should only be called once!
25976      * @param {String/HTMLElement/Element} container The element this component should be rendered into
25977      * @return {Form} this
25978      */
25979     render : function(ct)
25980     {
25981         
25982         
25983         
25984         ct = Roo.get(ct);
25985         var o = this.autoCreate || {
25986             tag: 'form',
25987             method : this.method || 'POST',
25988             id : this.id || Roo.id()
25989         };
25990         this.initEl(ct.createChild(o));
25991
25992         this.root.render(this.el);
25993         
25994        
25995              
25996         this.items.each(function(f){
25997             f.render('x-form-el-'+f.id);
25998         });
25999
26000         if(this.buttons.length > 0){
26001             // tables are required to maintain order and for correct IE layout
26002             var tb = this.el.createChild({cls:'x-form-btns-ct', cn: {
26003                 cls:"x-form-btns x-form-btns-"+this.buttonAlign,
26004                 html:'<table cellspacing="0"><tbody><tr></tr></tbody></table><div class="x-clear"></div>'
26005             }}, null, true);
26006             var tr = tb.getElementsByTagName('tr')[0];
26007             for(var i = 0, len = this.buttons.length; i < len; i++) {
26008                 var b = this.buttons[i];
26009                 var td = document.createElement('td');
26010                 td.className = 'x-form-btn-td';
26011                 b.render(tr.appendChild(td));
26012             }
26013         }
26014         if(this.monitorValid){ // initialize after render
26015             this.startMonitoring();
26016         }
26017         this.fireEvent('rendered', this);
26018         return this;
26019     },
26020
26021     /**
26022      * Adds a button to the footer of the form - this <b>must</b> be called before the form is rendered.
26023      * @param {String/Object} config A string becomes the button text, an object can either be a Button config
26024      * object or a valid Roo.DomHelper element config
26025      * @param {Function} handler The function called when the button is clicked
26026      * @param {Object} scope (optional) The scope of the handler function
26027      * @return {Roo.Button}
26028      */
26029     addButton : function(config, handler, scope){
26030         var bc = {
26031             handler: handler,
26032             scope: scope,
26033             minWidth: this.minButtonWidth,
26034             hideParent:true
26035         };
26036         if(typeof config == "string"){
26037             bc.text = config;
26038         }else{
26039             Roo.apply(bc, config);
26040         }
26041         var btn = new Roo.Button(null, bc);
26042         this.buttons.push(btn);
26043         return btn;
26044     },
26045
26046      /**
26047      * Adds a series of form elements (using the xtype property as the factory method.
26048      * Valid xtypes are:  TextField, TextArea .... Button, Layout, FieldSet, Column, (and 'end' to close a block)
26049      * @param {Object} config 
26050      */
26051     
26052     addxtype : function()
26053     {
26054         var ar = Array.prototype.slice.call(arguments, 0);
26055         var ret = false;
26056         for(var i = 0; i < ar.length; i++) {
26057             if (!ar[i]) {
26058                 continue; // skip -- if this happends something invalid got sent, we 
26059                 // should ignore it, as basically that interface element will not show up
26060                 // and that should be pretty obvious!!
26061             }
26062             
26063             if (Roo.form[ar[i].xtype]) {
26064                 ar[i].form = this;
26065                 var fe = Roo.factory(ar[i], Roo.form);
26066                 if (!ret) {
26067                     ret = fe;
26068                 }
26069                 fe.form = this;
26070                 if (fe.store) {
26071                     fe.store.form = this;
26072                 }
26073                 if (fe.isLayout) {  
26074                          
26075                     this.start(fe);
26076                     this.allItems.push(fe);
26077                     if (fe.items && fe.addxtype) {
26078                         fe.addxtype.apply(fe, fe.items);
26079                         delete fe.items;
26080                     }
26081                      this.end();
26082                     continue;
26083                 }
26084                 
26085                 
26086                  
26087                 this.add(fe);
26088               //  console.log('adding ' + ar[i].xtype);
26089             }
26090             if (ar[i].xtype == 'Button') {  
26091                 //console.log('adding button');
26092                 //console.log(ar[i]);
26093                 this.addButton(ar[i]);
26094                 this.allItems.push(fe);
26095                 continue;
26096             }
26097             
26098             if (ar[i].xtype == 'end') { // so we can add fieldsets... / layout etc.
26099                 alert('end is not supported on xtype any more, use items');
26100             //    this.end();
26101             //    //console.log('adding end');
26102             }
26103             
26104         }
26105         return ret;
26106     },
26107     
26108     /**
26109      * Starts monitoring of the valid state of this form. Usually this is done by passing the config
26110      * option "monitorValid"
26111      */
26112     startMonitoring : function(){
26113         if(!this.bound){
26114             this.bound = true;
26115             Roo.TaskMgr.start({
26116                 run : this.bindHandler,
26117                 interval : this.monitorPoll || 200,
26118                 scope: this
26119             });
26120         }
26121     },
26122
26123     /**
26124      * Stops monitoring of the valid state of this form
26125      */
26126     stopMonitoring : function(){
26127         this.bound = false;
26128     },
26129
26130     // private
26131     bindHandler : function(){
26132         if(!this.bound){
26133             return false; // stops binding
26134         }
26135         var valid = true;
26136         this.items.each(function(f){
26137             if(!f.isValid(true)){
26138                 valid = false;
26139                 return false;
26140             }
26141         });
26142         for(var i = 0, len = this.buttons.length; i < len; i++){
26143             var btn = this.buttons[i];
26144             if(btn.formBind === true && btn.disabled === valid){
26145                 btn.setDisabled(!valid);
26146             }
26147         }
26148         this.fireEvent('clientvalidation', this, valid);
26149     }
26150     
26151     
26152     
26153     
26154     
26155     
26156     
26157     
26158 });
26159
26160
26161 // back compat
26162 Roo.Form = Roo.form.Form;
26163 /*
26164  * Based on:
26165  * Ext JS Library 1.1.1
26166  * Copyright(c) 2006-2007, Ext JS, LLC.
26167  *
26168  * Originally Released Under LGPL - original licence link has changed is not relivant.
26169  *
26170  * Fork - LGPL
26171  * <script type="text/javascript">
26172  */
26173
26174 // as we use this in bootstrap.
26175 Roo.namespace('Roo.form');
26176  /**
26177  * @class Roo.form.Action
26178  * Internal Class used to handle form actions
26179  * @constructor
26180  * @param {Roo.form.BasicForm} el The form element or its id
26181  * @param {Object} config Configuration options
26182  */
26183
26184  
26185  
26186 // define the action interface
26187 Roo.form.Action = function(form, options){
26188     this.form = form;
26189     this.options = options || {};
26190 };
26191 /**
26192  * Client Validation Failed
26193  * @const 
26194  */
26195 Roo.form.Action.CLIENT_INVALID = 'client';
26196 /**
26197  * Server Validation Failed
26198  * @const 
26199  */
26200 Roo.form.Action.SERVER_INVALID = 'server';
26201  /**
26202  * Connect to Server Failed
26203  * @const 
26204  */
26205 Roo.form.Action.CONNECT_FAILURE = 'connect';
26206 /**
26207  * Reading Data from Server Failed
26208  * @const 
26209  */
26210 Roo.form.Action.LOAD_FAILURE = 'load';
26211
26212 Roo.form.Action.prototype = {
26213     type : 'default',
26214     failureType : undefined,
26215     response : undefined,
26216     result : undefined,
26217
26218     // interface method
26219     run : function(options){
26220
26221     },
26222
26223     // interface method
26224     success : function(response){
26225
26226     },
26227
26228     // interface method
26229     handleResponse : function(response){
26230
26231     },
26232
26233     // default connection failure
26234     failure : function(response){
26235         
26236         this.response = response;
26237         this.failureType = Roo.form.Action.CONNECT_FAILURE;
26238         this.form.afterAction(this, false);
26239     },
26240
26241     processResponse : function(response){
26242         this.response = response;
26243         if(!response.responseText){
26244             return true;
26245         }
26246         this.result = this.handleResponse(response);
26247         return this.result;
26248     },
26249
26250     // utility functions used internally
26251     getUrl : function(appendParams){
26252         var url = this.options.url || this.form.url || this.form.el.dom.action;
26253         if(appendParams){
26254             var p = this.getParams();
26255             if(p){
26256                 url += (url.indexOf('?') != -1 ? '&' : '?') + p;
26257             }
26258         }
26259         return url;
26260     },
26261
26262     getMethod : function(){
26263         return (this.options.method || this.form.method || this.form.el.dom.method || 'POST').toUpperCase();
26264     },
26265
26266     getParams : function(){
26267         var bp = this.form.baseParams;
26268         var p = this.options.params;
26269         if(p){
26270             if(typeof p == "object"){
26271                 p = Roo.urlEncode(Roo.applyIf(p, bp));
26272             }else if(typeof p == 'string' && bp){
26273                 p += '&' + Roo.urlEncode(bp);
26274             }
26275         }else if(bp){
26276             p = Roo.urlEncode(bp);
26277         }
26278         return p;
26279     },
26280
26281     createCallback : function(){
26282         return {
26283             success: this.success,
26284             failure: this.failure,
26285             scope: this,
26286             timeout: (this.form.timeout*1000),
26287             upload: this.form.fileUpload ? this.success : undefined
26288         };
26289     }
26290 };
26291
26292 Roo.form.Action.Submit = function(form, options){
26293     Roo.form.Action.Submit.superclass.constructor.call(this, form, options);
26294 };
26295
26296 Roo.extend(Roo.form.Action.Submit, Roo.form.Action, {
26297     type : 'submit',
26298
26299     haveProgress : false,
26300     uploadComplete : false,
26301     
26302     // uploadProgress indicator.
26303     uploadProgress : function()
26304     {
26305         if (!this.form.progressUrl) {
26306             return;
26307         }
26308         
26309         if (!this.haveProgress) {
26310             Roo.MessageBox.progress("Uploading", "Uploading");
26311         }
26312         if (this.uploadComplete) {
26313            Roo.MessageBox.hide();
26314            return;
26315         }
26316         
26317         this.haveProgress = true;
26318    
26319         var uid = this.form.findField('UPLOAD_IDENTIFIER').getValue();
26320         
26321         var c = new Roo.data.Connection();
26322         c.request({
26323             url : this.form.progressUrl,
26324             params: {
26325                 id : uid
26326             },
26327             method: 'GET',
26328             success : function(req){
26329                //console.log(data);
26330                 var rdata = false;
26331                 var edata;
26332                 try  {
26333                    rdata = Roo.decode(req.responseText)
26334                 } catch (e) {
26335                     Roo.log("Invalid data from server..");
26336                     Roo.log(edata);
26337                     return;
26338                 }
26339                 if (!rdata || !rdata.success) {
26340                     Roo.log(rdata);
26341                     Roo.MessageBox.alert(Roo.encode(rdata));
26342                     return;
26343                 }
26344                 var data = rdata.data;
26345                 
26346                 if (this.uploadComplete) {
26347                    Roo.MessageBox.hide();
26348                    return;
26349                 }
26350                    
26351                 if (data){
26352                     Roo.MessageBox.updateProgress(data.bytes_uploaded/data.bytes_total,
26353                        Math.floor((data.bytes_total - data.bytes_uploaded)/1000) + 'k remaining'
26354                     );
26355                 }
26356                 this.uploadProgress.defer(2000,this);
26357             },
26358        
26359             failure: function(data) {
26360                 Roo.log('progress url failed ');
26361                 Roo.log(data);
26362             },
26363             scope : this
26364         });
26365            
26366     },
26367     
26368     
26369     run : function()
26370     {
26371         // run get Values on the form, so it syncs any secondary forms.
26372         this.form.getValues();
26373         
26374         var o = this.options;
26375         var method = this.getMethod();
26376         var isPost = method == 'POST';
26377         if(o.clientValidation === false || this.form.isValid()){
26378             
26379             if (this.form.progressUrl) {
26380                 this.form.findField('UPLOAD_IDENTIFIER').setValue(
26381                     (new Date() * 1) + '' + Math.random());
26382                     
26383             } 
26384             
26385             
26386             Roo.Ajax.request(Roo.apply(this.createCallback(), {
26387                 form:this.form.el.dom,
26388                 url:this.getUrl(!isPost),
26389                 method: method,
26390                 params:isPost ? this.getParams() : null,
26391                 isUpload: this.form.fileUpload,
26392                 formData : this.form.formData
26393             }));
26394             
26395             this.uploadProgress();
26396
26397         }else if (o.clientValidation !== false){ // client validation failed
26398             this.failureType = Roo.form.Action.CLIENT_INVALID;
26399             this.form.afterAction(this, false);
26400         }
26401     },
26402
26403     success : function(response)
26404     {
26405         this.uploadComplete= true;
26406         if (this.haveProgress) {
26407             Roo.MessageBox.hide();
26408         }
26409         
26410         
26411         var result = this.processResponse(response);
26412         if(result === true || result.success){
26413             this.form.afterAction(this, true);
26414             return;
26415         }
26416         if(result.errors){
26417             this.form.markInvalid(result.errors);
26418             this.failureType = Roo.form.Action.SERVER_INVALID;
26419         }
26420         this.form.afterAction(this, false);
26421     },
26422     failure : function(response)
26423     {
26424         this.uploadComplete= true;
26425         if (this.haveProgress) {
26426             Roo.MessageBox.hide();
26427         }
26428         
26429         this.response = response;
26430         this.failureType = Roo.form.Action.CONNECT_FAILURE;
26431         this.form.afterAction(this, false);
26432     },
26433     
26434     handleResponse : function(response){
26435         if(this.form.errorReader){
26436             var rs = this.form.errorReader.read(response);
26437             var errors = [];
26438             if(rs.records){
26439                 for(var i = 0, len = rs.records.length; i < len; i++) {
26440                     var r = rs.records[i];
26441                     errors[i] = r.data;
26442                 }
26443             }
26444             if(errors.length < 1){
26445                 errors = null;
26446             }
26447             return {
26448                 success : rs.success,
26449                 errors : errors
26450             };
26451         }
26452         var ret = false;
26453         try {
26454             ret = Roo.decode(response.responseText);
26455         } catch (e) {
26456             ret = {
26457                 success: false,
26458                 errorMsg: "Failed to read server message: " + (response ? response.responseText : ' - no message'),
26459                 errors : []
26460             };
26461         }
26462         return ret;
26463         
26464     }
26465 });
26466
26467
26468 Roo.form.Action.Load = function(form, options){
26469     Roo.form.Action.Load.superclass.constructor.call(this, form, options);
26470     this.reader = this.form.reader;
26471 };
26472
26473 Roo.extend(Roo.form.Action.Load, Roo.form.Action, {
26474     type : 'load',
26475
26476     run : function(){
26477         
26478         Roo.Ajax.request(Roo.apply(
26479                 this.createCallback(), {
26480                     method:this.getMethod(),
26481                     url:this.getUrl(false),
26482                     params:this.getParams()
26483         }));
26484     },
26485
26486     success : function(response){
26487         
26488         var result = this.processResponse(response);
26489         if(result === true || !result.success || !result.data){
26490             this.failureType = Roo.form.Action.LOAD_FAILURE;
26491             this.form.afterAction(this, false);
26492             return;
26493         }
26494         this.form.clearInvalid();
26495         this.form.setValues(result.data);
26496         this.form.afterAction(this, true);
26497     },
26498
26499     handleResponse : function(response){
26500         if(this.form.reader){
26501             var rs = this.form.reader.read(response);
26502             var data = rs.records && rs.records[0] ? rs.records[0].data : null;
26503             return {
26504                 success : rs.success,
26505                 data : data
26506             };
26507         }
26508         return Roo.decode(response.responseText);
26509     }
26510 });
26511
26512 Roo.form.Action.ACTION_TYPES = {
26513     'load' : Roo.form.Action.Load,
26514     'submit' : Roo.form.Action.Submit
26515 };/*
26516  * Based on:
26517  * Ext JS Library 1.1.1
26518  * Copyright(c) 2006-2007, Ext JS, LLC.
26519  *
26520  * Originally Released Under LGPL - original licence link has changed is not relivant.
26521  *
26522  * Fork - LGPL
26523  * <script type="text/javascript">
26524  */
26525  
26526 /**
26527  * @class Roo.form.Layout
26528  * @extends Roo.Component
26529  * Creates a container for layout and rendering of fields in an {@link Roo.form.Form}.
26530  * @constructor
26531  * @param {Object} config Configuration options
26532  */
26533 Roo.form.Layout = function(config){
26534     var xitems = [];
26535     if (config.items) {
26536         xitems = config.items;
26537         delete config.items;
26538     }
26539     Roo.form.Layout.superclass.constructor.call(this, config);
26540     this.stack = [];
26541     Roo.each(xitems, this.addxtype, this);
26542      
26543 };
26544
26545 Roo.extend(Roo.form.Layout, Roo.Component, {
26546     /**
26547      * @cfg {String/Object} autoCreate
26548      * A DomHelper element spec used to autocreate the layout (defaults to {tag: 'div', cls: 'x-form-ct'})
26549      */
26550     /**
26551      * @cfg {String/Object/Function} style
26552      * A style specification string, e.g. "width:100px", or object in the form {width:"100px"}, or
26553      * a function which returns such a specification.
26554      */
26555     /**
26556      * @cfg {String} labelAlign
26557      * Valid values are "left," "top" and "right" (defaults to "left")
26558      */
26559     /**
26560      * @cfg {Number} labelWidth
26561      * Fixed width in pixels of all field labels (defaults to undefined)
26562      */
26563     /**
26564      * @cfg {Boolean} clear
26565      * True to add a clearing element at the end of this layout, equivalent to CSS clear: both (defaults to true)
26566      */
26567     clear : true,
26568     /**
26569      * @cfg {String} labelSeparator
26570      * The separator to use after field labels (defaults to ':')
26571      */
26572     labelSeparator : ':',
26573     /**
26574      * @cfg {Boolean} hideLabels
26575      * True to suppress the display of field labels in this layout (defaults to false)
26576      */
26577     hideLabels : false,
26578
26579     // private
26580     defaultAutoCreate : {tag: 'div', cls: 'x-form-ct'},
26581     
26582     isLayout : true,
26583     
26584     // private
26585     onRender : function(ct, position){
26586         if(this.el){ // from markup
26587             this.el = Roo.get(this.el);
26588         }else {  // generate
26589             var cfg = this.getAutoCreate();
26590             this.el = ct.createChild(cfg, position);
26591         }
26592         if(this.style){
26593             this.el.applyStyles(this.style);
26594         }
26595         if(this.labelAlign){
26596             this.el.addClass('x-form-label-'+this.labelAlign);
26597         }
26598         if(this.hideLabels){
26599             this.labelStyle = "display:none";
26600             this.elementStyle = "padding-left:0;";
26601         }else{
26602             if(typeof this.labelWidth == 'number'){
26603                 this.labelStyle = "width:"+this.labelWidth+"px;";
26604                 this.elementStyle = "padding-left:"+((this.labelWidth+(typeof this.labelPad == 'number' ? this.labelPad : 5))+'px')+";";
26605             }
26606             if(this.labelAlign == 'top'){
26607                 this.labelStyle = "width:auto;";
26608                 this.elementStyle = "padding-left:0;";
26609             }
26610         }
26611         var stack = this.stack;
26612         var slen = stack.length;
26613         if(slen > 0){
26614             if(!this.fieldTpl){
26615                 var t = new Roo.Template(
26616                     '<div class="x-form-item {5}">',
26617                         '<label for="{0}" style="{2}">{1}{4}</label>',
26618                         '<div class="x-form-element" id="x-form-el-{0}" style="{3}">',
26619                         '</div>',
26620                     '</div><div class="x-form-clear-left"></div>'
26621                 );
26622                 t.disableFormats = true;
26623                 t.compile();
26624                 Roo.form.Layout.prototype.fieldTpl = t;
26625             }
26626             for(var i = 0; i < slen; i++) {
26627                 if(stack[i].isFormField){
26628                     this.renderField(stack[i]);
26629                 }else{
26630                     this.renderComponent(stack[i]);
26631                 }
26632             }
26633         }
26634         if(this.clear){
26635             this.el.createChild({cls:'x-form-clear'});
26636         }
26637     },
26638
26639     // private
26640     renderField : function(f){
26641         f.fieldEl = Roo.get(this.fieldTpl.append(this.el, [
26642                f.id, //0
26643                f.fieldLabel, //1
26644                f.labelStyle||this.labelStyle||'', //2
26645                this.elementStyle||'', //3
26646                typeof f.labelSeparator == 'undefined' ? this.labelSeparator : f.labelSeparator, //4
26647                f.itemCls||this.itemCls||''  //5
26648        ], true).getPrevSibling());
26649     },
26650
26651     // private
26652     renderComponent : function(c){
26653         c.render(c.isLayout ? this.el : this.el.createChild());    
26654     },
26655     /**
26656      * Adds a object form elements (using the xtype property as the factory method.)
26657      * Valid xtypes are:  TextField, TextArea .... Button, Layout, FieldSet, Column
26658      * @param {Object} config 
26659      */
26660     addxtype : function(o)
26661     {
26662         // create the lement.
26663         o.form = this.form;
26664         var fe = Roo.factory(o, Roo.form);
26665         this.form.allItems.push(fe);
26666         this.stack.push(fe);
26667         
26668         if (fe.isFormField) {
26669             this.form.items.add(fe);
26670         }
26671          
26672         return fe;
26673     }
26674 });
26675
26676 /**
26677  * @class Roo.form.Column
26678  * @extends Roo.form.Layout
26679  * Creates a column container for layout and rendering of fields in an {@link Roo.form.Form}.
26680  * @constructor
26681  * @param {Object} config Configuration options
26682  */
26683 Roo.form.Column = function(config){
26684     Roo.form.Column.superclass.constructor.call(this, config);
26685 };
26686
26687 Roo.extend(Roo.form.Column, Roo.form.Layout, {
26688     /**
26689      * @cfg {Number/String} width
26690      * The fixed width of the column in pixels or CSS value (defaults to "auto")
26691      */
26692     /**
26693      * @cfg {String/Object} autoCreate
26694      * A DomHelper element spec used to autocreate the column (defaults to {tag: 'div', cls: 'x-form-ct x-form-column'})
26695      */
26696
26697     // private
26698     defaultAutoCreate : {tag: 'div', cls: 'x-form-ct x-form-column'},
26699
26700     // private
26701     onRender : function(ct, position){
26702         Roo.form.Column.superclass.onRender.call(this, ct, position);
26703         if(this.width){
26704             this.el.setWidth(this.width);
26705         }
26706     }
26707 });
26708
26709
26710 /**
26711  * @class Roo.form.Row
26712  * @extends Roo.form.Layout
26713  * Creates a row container for layout and rendering of fields in an {@link Roo.form.Form}.
26714  * @constructor
26715  * @param {Object} config Configuration options
26716  */
26717
26718  
26719 Roo.form.Row = function(config){
26720     Roo.form.Row.superclass.constructor.call(this, config);
26721 };
26722  
26723 Roo.extend(Roo.form.Row, Roo.form.Layout, {
26724       /**
26725      * @cfg {Number/String} width
26726      * The fixed width of the column in pixels or CSS value (defaults to "auto")
26727      */
26728     /**
26729      * @cfg {Number/String} height
26730      * The fixed height of the column in pixels or CSS value (defaults to "auto")
26731      */
26732     defaultAutoCreate : {tag: 'div', cls: 'x-form-ct x-form-row'},
26733     
26734     padWidth : 20,
26735     // private
26736     onRender : function(ct, position){
26737         //console.log('row render');
26738         if(!this.rowTpl){
26739             var t = new Roo.Template(
26740                 '<div class="x-form-item {5}" style="float:left;width:{6}px">',
26741                     '<label for="{0}" style="{2}">{1}{4}</label>',
26742                     '<div class="x-form-element" id="x-form-el-{0}" style="{3}">',
26743                     '</div>',
26744                 '</div>'
26745             );
26746             t.disableFormats = true;
26747             t.compile();
26748             Roo.form.Layout.prototype.rowTpl = t;
26749         }
26750         this.fieldTpl = this.rowTpl;
26751         
26752         //console.log('lw' + this.labelWidth +', la:' + this.labelAlign);
26753         var labelWidth = 100;
26754         
26755         if ((this.labelAlign != 'top')) {
26756             if (typeof this.labelWidth == 'number') {
26757                 labelWidth = this.labelWidth
26758             }
26759             this.padWidth =  20 + labelWidth;
26760             
26761         }
26762         
26763         Roo.form.Column.superclass.onRender.call(this, ct, position);
26764         if(this.width){
26765             this.el.setWidth(this.width);
26766         }
26767         if(this.height){
26768             this.el.setHeight(this.height);
26769         }
26770     },
26771     
26772     // private
26773     renderField : function(f){
26774         f.fieldEl = this.fieldTpl.append(this.el, [
26775                f.id, f.fieldLabel,
26776                f.labelStyle||this.labelStyle||'',
26777                this.elementStyle||'',
26778                typeof f.labelSeparator == 'undefined' ? this.labelSeparator : f.labelSeparator,
26779                f.itemCls||this.itemCls||'',
26780                f.width ? f.width + this.padWidth : 160 + this.padWidth
26781        ],true);
26782     }
26783 });
26784  
26785
26786 /**
26787  * @class Roo.form.FieldSet
26788  * @extends Roo.form.Layout
26789  * Creates a fieldset container for layout and rendering of fields in an {@link Roo.form.Form}.
26790  * @constructor
26791  * @param {Object} config Configuration options
26792  */
26793 Roo.form.FieldSet = function(config){
26794     Roo.form.FieldSet.superclass.constructor.call(this, config);
26795 };
26796
26797 Roo.extend(Roo.form.FieldSet, Roo.form.Layout, {
26798     /**
26799      * @cfg {String} legend
26800      * The text to display as the legend for the FieldSet (defaults to '')
26801      */
26802     /**
26803      * @cfg {String/Object} autoCreate
26804      * A DomHelper element spec used to autocreate the fieldset (defaults to {tag: 'fieldset', cn: {tag:'legend'}})
26805      */
26806
26807     // private
26808     defaultAutoCreate : {tag: 'fieldset', cn: {tag:'legend'}},
26809
26810     // private
26811     onRender : function(ct, position){
26812         Roo.form.FieldSet.superclass.onRender.call(this, ct, position);
26813         if(this.legend){
26814             this.setLegend(this.legend);
26815         }
26816     },
26817
26818     // private
26819     setLegend : function(text){
26820         if(this.rendered){
26821             this.el.child('legend').update(text);
26822         }
26823     }
26824 });/*
26825  * Based on:
26826  * Ext JS Library 1.1.1
26827  * Copyright(c) 2006-2007, Ext JS, LLC.
26828  *
26829  * Originally Released Under LGPL - original licence link has changed is not relivant.
26830  *
26831  * Fork - LGPL
26832  * <script type="text/javascript">
26833  */
26834 /**
26835  * @class Roo.form.VTypes
26836  * Overridable validation definitions. The validations provided are basic and intended to be easily customizable and extended.
26837  * @singleton
26838  */
26839 Roo.form.VTypes = function(){
26840     // closure these in so they are only created once.
26841     var alpha = /^[a-zA-Z_]+$/;
26842     var alphanum = /^[a-zA-Z0-9_]+$/;
26843     var email = /^([\w]+)(.[\w]+)*@([\w-]+\.){1,5}([A-Za-z]){2,24}$/;
26844     var url = /(((https?)|(ftp)):\/\/([\-\w]+\.)+\w{2,3}(\/[%\-\w]+(\.\w{2,})?)*(([\w\-\.\?\\\/+@&#;`~=%!]*)(\.\w{2,})?)*\/?)/i;
26845
26846     // All these messages and functions are configurable
26847     return {
26848         /**
26849          * The function used to validate email addresses
26850          * @param {String} value The email address
26851          */
26852         'email' : function(v){
26853             return email.test(v);
26854         },
26855         /**
26856          * The error text to display when the email validation function returns false
26857          * @type String
26858          */
26859         'emailText' : 'This field should be an e-mail address in the format "user@domain.com"',
26860         /**
26861          * The keystroke filter mask to be applied on email input
26862          * @type RegExp
26863          */
26864         'emailMask' : /[a-z0-9_\.\-@]/i,
26865
26866         /**
26867          * The function used to validate URLs
26868          * @param {String} value The URL
26869          */
26870         'url' : function(v){
26871             return url.test(v);
26872         },
26873         /**
26874          * The error text to display when the url validation function returns false
26875          * @type String
26876          */
26877         'urlText' : 'This field should be a URL in the format "http:/'+'/www.domain.com"',
26878         
26879         /**
26880          * The function used to validate alpha values
26881          * @param {String} value The value
26882          */
26883         'alpha' : function(v){
26884             return alpha.test(v);
26885         },
26886         /**
26887          * The error text to display when the alpha validation function returns false
26888          * @type String
26889          */
26890         'alphaText' : 'This field should only contain letters and _',
26891         /**
26892          * The keystroke filter mask to be applied on alpha input
26893          * @type RegExp
26894          */
26895         'alphaMask' : /[a-z_]/i,
26896
26897         /**
26898          * The function used to validate alphanumeric values
26899          * @param {String} value The value
26900          */
26901         'alphanum' : function(v){
26902             return alphanum.test(v);
26903         },
26904         /**
26905          * The error text to display when the alphanumeric validation function returns false
26906          * @type String
26907          */
26908         'alphanumText' : 'This field should only contain letters, numbers and _',
26909         /**
26910          * The keystroke filter mask to be applied on alphanumeric input
26911          * @type RegExp
26912          */
26913         'alphanumMask' : /[a-z0-9_]/i
26914     };
26915 }();//<script type="text/javascript">
26916
26917 /**
26918  * @class Roo.form.FCKeditor
26919  * @extends Roo.form.TextArea
26920  * Wrapper around the FCKEditor http://www.fckeditor.net
26921  * @constructor
26922  * Creates a new FCKeditor
26923  * @param {Object} config Configuration options
26924  */
26925 Roo.form.FCKeditor = function(config){
26926     Roo.form.FCKeditor.superclass.constructor.call(this, config);
26927     this.addEvents({
26928          /**
26929          * @event editorinit
26930          * Fired when the editor is initialized - you can add extra handlers here..
26931          * @param {FCKeditor} this
26932          * @param {Object} the FCK object.
26933          */
26934         editorinit : true
26935     });
26936     
26937     
26938 };
26939 Roo.form.FCKeditor.editors = { };
26940 Roo.extend(Roo.form.FCKeditor, Roo.form.TextArea,
26941 {
26942     //defaultAutoCreate : {
26943     //    tag : "textarea",style   : "width:100px;height:60px;" ,autocomplete    : "off"
26944     //},
26945     // private
26946     /**
26947      * @cfg {Object} fck options - see fck manual for details.
26948      */
26949     fckconfig : false,
26950     
26951     /**
26952      * @cfg {Object} fck toolbar set (Basic or Default)
26953      */
26954     toolbarSet : 'Basic',
26955     /**
26956      * @cfg {Object} fck BasePath
26957      */ 
26958     basePath : '/fckeditor/',
26959     
26960     
26961     frame : false,
26962     
26963     value : '',
26964     
26965    
26966     onRender : function(ct, position)
26967     {
26968         if(!this.el){
26969             this.defaultAutoCreate = {
26970                 tag: "textarea",
26971                 style:"width:300px;height:60px;",
26972                 autocomplete: "new-password"
26973             };
26974         }
26975         Roo.form.FCKeditor.superclass.onRender.call(this, ct, position);
26976         /*
26977         if(this.grow){
26978             this.textSizeEl = Roo.DomHelper.append(document.body, {tag: "pre", cls: "x-form-grow-sizer"});
26979             if(this.preventScrollbars){
26980                 this.el.setStyle("overflow", "hidden");
26981             }
26982             this.el.setHeight(this.growMin);
26983         }
26984         */
26985         //console.log('onrender' + this.getId() );
26986         Roo.form.FCKeditor.editors[this.getId()] = this;
26987          
26988
26989         this.replaceTextarea() ;
26990         
26991     },
26992     
26993     getEditor : function() {
26994         return this.fckEditor;
26995     },
26996     /**
26997      * Sets a data value into the field and validates it.  To set the value directly without validation see {@link #setRawValue}.
26998      * @param {Mixed} value The value to set
26999      */
27000     
27001     
27002     setValue : function(value)
27003     {
27004         //console.log('setValue: ' + value);
27005         
27006         if(typeof(value) == 'undefined') { // not sure why this is happending...
27007             return;
27008         }
27009         Roo.form.FCKeditor.superclass.setValue.apply(this,[value]);
27010         
27011         //if(!this.el || !this.getEditor()) {
27012         //    this.value = value;
27013             //this.setValue.defer(100,this,[value]);    
27014         //    return;
27015         //} 
27016         
27017         if(!this.getEditor()) {
27018             return;
27019         }
27020         
27021         this.getEditor().SetData(value);
27022         
27023         //
27024
27025     },
27026
27027     /**
27028      * Returns the normalized data value (undefined or emptyText will be returned as '').  To return the raw value see {@link #getRawValue}.
27029      * @return {Mixed} value The field value
27030      */
27031     getValue : function()
27032     {
27033         
27034         if (this.frame && this.frame.dom.style.display == 'none') {
27035             return Roo.form.FCKeditor.superclass.getValue.call(this);
27036         }
27037         
27038         if(!this.el || !this.getEditor()) {
27039            
27040            // this.getValue.defer(100,this); 
27041             return this.value;
27042         }
27043        
27044         
27045         var value=this.getEditor().GetData();
27046         Roo.form.FCKeditor.superclass.setValue.apply(this,[value]);
27047         return Roo.form.FCKeditor.superclass.getValue.call(this);
27048         
27049
27050     },
27051
27052     /**
27053      * Returns the raw data value which may or may not be a valid, defined value.  To return a normalized value see {@link #getValue}.
27054      * @return {Mixed} value The field value
27055      */
27056     getRawValue : function()
27057     {
27058         if (this.frame && this.frame.dom.style.display == 'none') {
27059             return Roo.form.FCKeditor.superclass.getRawValue.call(this);
27060         }
27061         
27062         if(!this.el || !this.getEditor()) {
27063             //this.getRawValue.defer(100,this); 
27064             return this.value;
27065             return;
27066         }
27067         
27068         
27069         
27070         var value=this.getEditor().GetData();
27071         Roo.form.FCKeditor.superclass.setRawValue.apply(this,[value]);
27072         return Roo.form.FCKeditor.superclass.getRawValue.call(this);
27073          
27074     },
27075     
27076     setSize : function(w,h) {
27077         
27078         
27079         
27080         //if (this.frame && this.frame.dom.style.display == 'none') {
27081         //    Roo.form.FCKeditor.superclass.setSize.apply(this, [w, h]);
27082         //    return;
27083         //}
27084         //if(!this.el || !this.getEditor()) {
27085         //    this.setSize.defer(100,this, [w,h]); 
27086         //    return;
27087         //}
27088         
27089         
27090         
27091         Roo.form.FCKeditor.superclass.setSize.apply(this, [w, h]);
27092         
27093         this.frame.dom.setAttribute('width', w);
27094         this.frame.dom.setAttribute('height', h);
27095         this.frame.setSize(w,h);
27096         
27097     },
27098     
27099     toggleSourceEdit : function(value) {
27100         
27101       
27102          
27103         this.el.dom.style.display = value ? '' : 'none';
27104         this.frame.dom.style.display = value ?  'none' : '';
27105         
27106     },
27107     
27108     
27109     focus: function(tag)
27110     {
27111         if (this.frame.dom.style.display == 'none') {
27112             return Roo.form.FCKeditor.superclass.focus.call(this);
27113         }
27114         if(!this.el || !this.getEditor()) {
27115             this.focus.defer(100,this, [tag]); 
27116             return;
27117         }
27118         
27119         
27120         
27121         
27122         var tgs = this.getEditor().EditorDocument.getElementsByTagName(tag);
27123         this.getEditor().Focus();
27124         if (tgs.length) {
27125             if (!this.getEditor().Selection.GetSelection()) {
27126                 this.focus.defer(100,this, [tag]); 
27127                 return;
27128             }
27129             
27130             
27131             var r = this.getEditor().EditorDocument.createRange();
27132             r.setStart(tgs[0],0);
27133             r.setEnd(tgs[0],0);
27134             this.getEditor().Selection.GetSelection().removeAllRanges();
27135             this.getEditor().Selection.GetSelection().addRange(r);
27136             this.getEditor().Focus();
27137         }
27138         
27139     },
27140     
27141     
27142     
27143     replaceTextarea : function()
27144     {
27145         if ( document.getElementById( this.getId() + '___Frame' ) ) {
27146             return ;
27147         }
27148         //if ( !this.checkBrowser || this._isCompatibleBrowser() )
27149         //{
27150             // We must check the elements firstly using the Id and then the name.
27151         var oTextarea = document.getElementById( this.getId() );
27152         
27153         var colElementsByName = document.getElementsByName( this.getId() ) ;
27154          
27155         oTextarea.style.display = 'none' ;
27156
27157         if ( oTextarea.tabIndex ) {            
27158             this.TabIndex = oTextarea.tabIndex ;
27159         }
27160         
27161         this._insertHtmlBefore( this._getConfigHtml(), oTextarea ) ;
27162         this._insertHtmlBefore( this._getIFrameHtml(), oTextarea ) ;
27163         this.frame = Roo.get(this.getId() + '___Frame')
27164     },
27165     
27166     _getConfigHtml : function()
27167     {
27168         var sConfig = '' ;
27169
27170         for ( var o in this.fckconfig ) {
27171             sConfig += sConfig.length > 0  ? '&amp;' : '';
27172             sConfig += encodeURIComponent( o ) + '=' + encodeURIComponent( this.fckconfig[o] ) ;
27173         }
27174
27175         return '<input type="hidden" id="' + this.getId() + '___Config" value="' + sConfig + '" style="display:none" />' ;
27176     },
27177     
27178     
27179     _getIFrameHtml : function()
27180     {
27181         var sFile = 'fckeditor.html' ;
27182         /* no idea what this is about..
27183         try
27184         {
27185             if ( (/fcksource=true/i).test( window.top.location.search ) )
27186                 sFile = 'fckeditor.original.html' ;
27187         }
27188         catch (e) { 
27189         */
27190
27191         var sLink = this.basePath + 'editor/' + sFile + '?InstanceName=' + encodeURIComponent( this.getId() ) ;
27192         sLink += this.toolbarSet ? ( '&amp;Toolbar=' + this.toolbarSet)  : '';
27193         
27194         
27195         var html = '<iframe id="' + this.getId() +
27196             '___Frame" src="' + sLink +
27197             '" width="' + this.width +
27198             '" height="' + this.height + '"' +
27199             (this.tabIndex ?  ' tabindex="' + this.tabIndex + '"' :'' ) +
27200             ' frameborder="0" scrolling="no"></iframe>' ;
27201
27202         return html ;
27203     },
27204     
27205     _insertHtmlBefore : function( html, element )
27206     {
27207         if ( element.insertAdjacentHTML )       {
27208             // IE
27209             element.insertAdjacentHTML( 'beforeBegin', html ) ;
27210         } else { // Gecko
27211             var oRange = document.createRange() ;
27212             oRange.setStartBefore( element ) ;
27213             var oFragment = oRange.createContextualFragment( html );
27214             element.parentNode.insertBefore( oFragment, element ) ;
27215         }
27216     }
27217     
27218     
27219   
27220     
27221     
27222     
27223     
27224
27225 });
27226
27227 //Roo.reg('fckeditor', Roo.form.FCKeditor);
27228
27229 function FCKeditor_OnComplete(editorInstance){
27230     var f = Roo.form.FCKeditor.editors[editorInstance.Name];
27231     f.fckEditor = editorInstance;
27232     //console.log("loaded");
27233     f.fireEvent('editorinit', f, editorInstance);
27234
27235   
27236
27237  
27238
27239
27240
27241
27242
27243
27244
27245
27246
27247
27248
27249
27250
27251
27252
27253 //<script type="text/javascript">
27254 /**
27255  * @class Roo.form.GridField
27256  * @extends Roo.form.Field
27257  * Embed a grid (or editable grid into a form)
27258  * STATUS ALPHA
27259  * 
27260  * This embeds a grid in a form, the value of the field should be the json encoded array of rows
27261  * it needs 
27262  * xgrid.store = Roo.data.Store
27263  * xgrid.store.proxy = Roo.data.MemoryProxy (data = [] )
27264  * xgrid.store.reader = Roo.data.JsonReader 
27265  * 
27266  * 
27267  * @constructor
27268  * Creates a new GridField
27269  * @param {Object} config Configuration options
27270  */
27271 Roo.form.GridField = function(config){
27272     Roo.form.GridField.superclass.constructor.call(this, config);
27273      
27274 };
27275
27276 Roo.extend(Roo.form.GridField, Roo.form.Field,  {
27277     /**
27278      * @cfg {Number} width  - used to restrict width of grid..
27279      */
27280     width : 100,
27281     /**
27282      * @cfg {Number} height - used to restrict height of grid..
27283      */
27284     height : 50,
27285      /**
27286      * @cfg {Object} xgrid (xtype'd description of grid) { xtype : 'Grid', dataSource: .... }
27287          * 
27288          *}
27289      */
27290     xgrid : false, 
27291     /**
27292      * @cfg {String/Object} autoCreate A DomHelper element spec, or true for a default element spec (defaults to
27293      * {tag: "input", type: "checkbox", autocomplete: "off"})
27294      */
27295    // defaultAutoCreate : { tag: 'div' },
27296     defaultAutoCreate : { tag: 'input', type: 'hidden', autocomplete: 'new-password'},
27297     /**
27298      * @cfg {String} addTitle Text to include for adding a title.
27299      */
27300     addTitle : false,
27301     //
27302     onResize : function(){
27303         Roo.form.Field.superclass.onResize.apply(this, arguments);
27304     },
27305
27306     initEvents : function(){
27307         // Roo.form.Checkbox.superclass.initEvents.call(this);
27308         // has no events...
27309        
27310     },
27311
27312
27313     getResizeEl : function(){
27314         return this.wrap;
27315     },
27316
27317     getPositionEl : function(){
27318         return this.wrap;
27319     },
27320
27321     // private
27322     onRender : function(ct, position){
27323         
27324         this.style = this.style || 'overflow: hidden; border:1px solid #c3daf9;';
27325         var style = this.style;
27326         delete this.style;
27327         
27328         Roo.form.GridField.superclass.onRender.call(this, ct, position);
27329         this.wrap = this.el.wrap({cls: ''}); // not sure why ive done thsi...
27330         this.viewEl = this.wrap.createChild({ tag: 'div' });
27331         if (style) {
27332             this.viewEl.applyStyles(style);
27333         }
27334         if (this.width) {
27335             this.viewEl.setWidth(this.width);
27336         }
27337         if (this.height) {
27338             this.viewEl.setHeight(this.height);
27339         }
27340         //if(this.inputValue !== undefined){
27341         //this.setValue(this.value);
27342         
27343         
27344         this.grid = new Roo.grid[this.xgrid.xtype](this.viewEl, this.xgrid);
27345         
27346         
27347         this.grid.render();
27348         this.grid.getDataSource().on('remove', this.refreshValue, this);
27349         this.grid.getDataSource().on('update', this.refreshValue, this);
27350         this.grid.on('afteredit', this.refreshValue, this);
27351  
27352     },
27353      
27354     
27355     /**
27356      * Sets the value of the item. 
27357      * @param {String} either an object  or a string..
27358      */
27359     setValue : function(v){
27360         //this.value = v;
27361         v = v || []; // empty set..
27362         // this does not seem smart - it really only affects memoryproxy grids..
27363         if (this.grid && this.grid.getDataSource() && typeof(v) != 'undefined') {
27364             var ds = this.grid.getDataSource();
27365             // assumes a json reader..
27366             var data = {}
27367             data[ds.reader.meta.root ] =  typeof(v) == 'string' ? Roo.decode(v) : v;
27368             ds.loadData( data);
27369         }
27370         // clear selection so it does not get stale.
27371         if (this.grid.sm) { 
27372             this.grid.sm.clearSelections();
27373         }
27374         
27375         Roo.form.GridField.superclass.setValue.call(this, v);
27376         this.refreshValue();
27377         // should load data in the grid really....
27378     },
27379     
27380     // private
27381     refreshValue: function() {
27382          var val = [];
27383         this.grid.getDataSource().each(function(r) {
27384             val.push(r.data);
27385         });
27386         this.el.dom.value = Roo.encode(val);
27387     }
27388     
27389      
27390     
27391     
27392 });/*
27393  * Based on:
27394  * Ext JS Library 1.1.1
27395  * Copyright(c) 2006-2007, Ext JS, LLC.
27396  *
27397  * Originally Released Under LGPL - original licence link has changed is not relivant.
27398  *
27399  * Fork - LGPL
27400  * <script type="text/javascript">
27401  */
27402 /**
27403  * @class Roo.form.DisplayField
27404  * @extends Roo.form.Field
27405  * A generic Field to display non-editable data.
27406  * @cfg {Boolean} closable (true|false) default false
27407  * @constructor
27408  * Creates a new Display Field item.
27409  * @param {Object} config Configuration options
27410  */
27411 Roo.form.DisplayField = function(config){
27412     Roo.form.DisplayField.superclass.constructor.call(this, config);
27413     
27414     this.addEvents({
27415         /**
27416          * @event close
27417          * Fires after the click the close btn
27418              * @param {Roo.form.DisplayField} this
27419              */
27420         close : true
27421     });
27422 };
27423
27424 Roo.extend(Roo.form.DisplayField, Roo.form.TextField,  {
27425     inputType:      'hidden',
27426     allowBlank:     true,
27427     readOnly:         true,
27428     
27429  
27430     /**
27431      * @cfg {String} focusClass The CSS class to use when the checkbox receives focus (defaults to undefined)
27432      */
27433     focusClass : undefined,
27434     /**
27435      * @cfg {String} fieldClass The default CSS class for the checkbox (defaults to "x-form-field")
27436      */
27437     fieldClass: 'x-form-field',
27438     
27439      /**
27440      * @cfg {Function} valueRenderer The renderer for the field (so you can reformat output). should return raw HTML
27441      */
27442     valueRenderer: undefined,
27443     
27444     width: 100,
27445     /**
27446      * @cfg {String/Object} autoCreate A DomHelper element spec, or true for a default element spec (defaults to
27447      * {tag: "input", type: "checkbox", autocomplete: "off"})
27448      */
27449      
27450  //   defaultAutoCreate : { tag: 'input', type: 'hidden', autocomplete: 'off'},
27451  
27452     closable : false,
27453     
27454     onResize : function(){
27455         Roo.form.DisplayField.superclass.onResize.apply(this, arguments);
27456         
27457     },
27458
27459     initEvents : function(){
27460         // Roo.form.Checkbox.superclass.initEvents.call(this);
27461         // has no events...
27462         
27463         if(this.closable){
27464             this.closeEl.on('click', this.onClose, this);
27465         }
27466        
27467     },
27468
27469
27470     getResizeEl : function(){
27471         return this.wrap;
27472     },
27473
27474     getPositionEl : function(){
27475         return this.wrap;
27476     },
27477
27478     // private
27479     onRender : function(ct, position){
27480         
27481         Roo.form.DisplayField.superclass.onRender.call(this, ct, position);
27482         //if(this.inputValue !== undefined){
27483         this.wrap = this.el.wrap();
27484         
27485         this.viewEl = this.wrap.createChild({ tag: 'div', cls: 'x-form-displayfield'});
27486         
27487         if(this.closable){
27488             this.closeEl = this.wrap.createChild({ tag: 'div', cls: 'x-dlg-close'});
27489         }
27490         
27491         if (this.bodyStyle) {
27492             this.viewEl.applyStyles(this.bodyStyle);
27493         }
27494         //this.viewEl.setStyle('padding', '2px');
27495         
27496         this.setValue(this.value);
27497         
27498     },
27499 /*
27500     // private
27501     initValue : Roo.emptyFn,
27502
27503   */
27504
27505         // private
27506     onClick : function(){
27507         
27508     },
27509
27510     /**
27511      * Sets the checked state of the checkbox.
27512      * @param {Boolean/String} checked True, 'true', '1', or 'on' to check the checkbox, any other value will uncheck it.
27513      */
27514     setValue : function(v){
27515         this.value = v;
27516         var html = this.valueRenderer ?  this.valueRenderer(v) : String.format('{0}', v);
27517         // this might be called before we have a dom element..
27518         if (!this.viewEl) {
27519             return;
27520         }
27521         this.viewEl.dom.innerHTML = html;
27522         Roo.form.DisplayField.superclass.setValue.call(this, v);
27523
27524     },
27525     
27526     onClose : function(e)
27527     {
27528         e.preventDefault();
27529         
27530         this.fireEvent('close', this);
27531     }
27532 });/*
27533  * 
27534  * Licence- LGPL
27535  * 
27536  */
27537
27538 /**
27539  * @class Roo.form.DayPicker
27540  * @extends Roo.form.Field
27541  * A Day picker show [M] [T] [W] ....
27542  * @constructor
27543  * Creates a new Day Picker
27544  * @param {Object} config Configuration options
27545  */
27546 Roo.form.DayPicker= function(config){
27547     Roo.form.DayPicker.superclass.constructor.call(this, config);
27548      
27549 };
27550
27551 Roo.extend(Roo.form.DayPicker, Roo.form.Field,  {
27552     /**
27553      * @cfg {String} focusClass The CSS class to use when the checkbox receives focus (defaults to undefined)
27554      */
27555     focusClass : undefined,
27556     /**
27557      * @cfg {String} fieldClass The default CSS class for the checkbox (defaults to "x-form-field")
27558      */
27559     fieldClass: "x-form-field",
27560    
27561     /**
27562      * @cfg {String/Object} autoCreate A DomHelper element spec, or true for a default element spec (defaults to
27563      * {tag: "input", type: "checkbox", autocomplete: "off"})
27564      */
27565     defaultAutoCreate : { tag: "input", type: 'hidden', autocomplete: "new-password"},
27566     
27567    
27568     actionMode : 'viewEl', 
27569     //
27570     // private
27571  
27572     inputType : 'hidden',
27573     
27574      
27575     inputElement: false, // real input element?
27576     basedOn: false, // ????
27577     
27578     isFormField: true, // not sure where this is needed!!!!
27579
27580     onResize : function(){
27581         Roo.form.Checkbox.superclass.onResize.apply(this, arguments);
27582         if(!this.boxLabel){
27583             this.el.alignTo(this.wrap, 'c-c');
27584         }
27585     },
27586
27587     initEvents : function(){
27588         Roo.form.Checkbox.superclass.initEvents.call(this);
27589         this.el.on("click", this.onClick,  this);
27590         this.el.on("change", this.onClick,  this);
27591     },
27592
27593
27594     getResizeEl : function(){
27595         return this.wrap;
27596     },
27597
27598     getPositionEl : function(){
27599         return this.wrap;
27600     },
27601
27602     
27603     // private
27604     onRender : function(ct, position){
27605         Roo.form.Checkbox.superclass.onRender.call(this, ct, position);
27606        
27607         this.wrap = this.el.wrap({cls: 'x-form-daypick-item '});
27608         
27609         var r1 = '<table><tr>';
27610         var r2 = '<tr class="x-form-daypick-icons">';
27611         for (var i=0; i < 7; i++) {
27612             r1+= '<td><div>' + Date.dayNames[i].substring(0,3) + '</div></td>';
27613             r2+= '<td><img class="x-menu-item-icon" src="' + Roo.BLANK_IMAGE_URL  +'"></td>';
27614         }
27615         
27616         var viewEl = this.wrap.createChild( r1 + '</tr>' + r2 + '</tr></table>');
27617         viewEl.select('img').on('click', this.onClick, this);
27618         this.viewEl = viewEl;   
27619         
27620         
27621         // this will not work on Chrome!!!
27622         this.el.on('DOMAttrModified', this.setFromHidden,  this); //ff
27623         this.el.on('propertychange', this.setFromHidden,  this);  //ie
27624         
27625         
27626           
27627
27628     },
27629
27630     // private
27631     initValue : Roo.emptyFn,
27632
27633     /**
27634      * Returns the checked state of the checkbox.
27635      * @return {Boolean} True if checked, else false
27636      */
27637     getValue : function(){
27638         return this.el.dom.value;
27639         
27640     },
27641
27642         // private
27643     onClick : function(e){ 
27644         //this.setChecked(!this.checked);
27645         Roo.get(e.target).toggleClass('x-menu-item-checked');
27646         this.refreshValue();
27647         //if(this.el.dom.checked != this.checked){
27648         //    this.setValue(this.el.dom.checked);
27649        // }
27650     },
27651     
27652     // private
27653     refreshValue : function()
27654     {
27655         var val = '';
27656         this.viewEl.select('img',true).each(function(e,i,n)  {
27657             val += e.is(".x-menu-item-checked") ? String(n) : '';
27658         });
27659         this.setValue(val, true);
27660     },
27661
27662     /**
27663      * Sets the checked state of the checkbox.
27664      * On is always based on a string comparison between inputValue and the param.
27665      * @param {Boolean/String} value - the value to set 
27666      * @param {Boolean/String} suppressEvent - whether to suppress the checkchange event.
27667      */
27668     setValue : function(v,suppressEvent){
27669         if (!this.el.dom) {
27670             return;
27671         }
27672         var old = this.el.dom.value ;
27673         this.el.dom.value = v;
27674         if (suppressEvent) {
27675             return ;
27676         }
27677          
27678         // update display..
27679         this.viewEl.select('img',true).each(function(e,i,n)  {
27680             
27681             var on = e.is(".x-menu-item-checked");
27682             var newv = v.indexOf(String(n)) > -1;
27683             if (on != newv) {
27684                 e.toggleClass('x-menu-item-checked');
27685             }
27686             
27687         });
27688         
27689         
27690         this.fireEvent('change', this, v, old);
27691         
27692         
27693     },
27694    
27695     // handle setting of hidden value by some other method!!?!?
27696     setFromHidden: function()
27697     {
27698         if(!this.el){
27699             return;
27700         }
27701         //console.log("SET FROM HIDDEN");
27702         //alert('setFrom hidden');
27703         this.setValue(this.el.dom.value);
27704     },
27705     
27706     onDestroy : function()
27707     {
27708         if(this.viewEl){
27709             Roo.get(this.viewEl).remove();
27710         }
27711          
27712         Roo.form.DayPicker.superclass.onDestroy.call(this);
27713     }
27714
27715 });/*
27716  * RooJS Library 1.1.1
27717  * Copyright(c) 2008-2011  Alan Knowles
27718  *
27719  * License - LGPL
27720  */
27721  
27722
27723 /**
27724  * @class Roo.form.ComboCheck
27725  * @extends Roo.form.ComboBox
27726  * A combobox for multiple select items.
27727  *
27728  * FIXME - could do with a reset button..
27729  * 
27730  * @constructor
27731  * Create a new ComboCheck
27732  * @param {Object} config Configuration options
27733  */
27734 Roo.form.ComboCheck = function(config){
27735     Roo.form.ComboCheck.superclass.constructor.call(this, config);
27736     // should verify some data...
27737     // like
27738     // hiddenName = required..
27739     // displayField = required
27740     // valudField == required
27741     var req= [ 'hiddenName', 'displayField', 'valueField' ];
27742     var _t = this;
27743     Roo.each(req, function(e) {
27744         if ((typeof(_t[e]) == 'undefined' ) || !_t[e].length) {
27745             throw "Roo.form.ComboCheck : missing value for: " + e;
27746         }
27747     });
27748     
27749     
27750 };
27751
27752 Roo.extend(Roo.form.ComboCheck, Roo.form.ComboBox, {
27753      
27754      
27755     editable : false,
27756      
27757     selectedClass: 'x-menu-item-checked', 
27758     
27759     // private
27760     onRender : function(ct, position){
27761         var _t = this;
27762         
27763         
27764         
27765         if(!this.tpl){
27766             var cls = 'x-combo-list';
27767
27768             
27769             this.tpl =  new Roo.Template({
27770                 html :  '<div class="'+cls+'-item x-menu-check-item">' +
27771                    '<img class="x-menu-item-icon" style="margin: 0px;" src="' + Roo.BLANK_IMAGE_URL + '">' + 
27772                    '<span>{' + this.displayField + '}</span>' +
27773                     '</div>' 
27774                 
27775             });
27776         }
27777  
27778         
27779         Roo.form.ComboCheck.superclass.onRender.call(this, ct, position);
27780         this.view.singleSelect = false;
27781         this.view.multiSelect = true;
27782         this.view.toggleSelect = true;
27783         this.pageTb.add(new Roo.Toolbar.Fill(), {
27784             
27785             text: 'Done',
27786             handler: function()
27787             {
27788                 _t.collapse();
27789             }
27790         });
27791     },
27792     
27793     onViewOver : function(e, t){
27794         // do nothing...
27795         return;
27796         
27797     },
27798     
27799     onViewClick : function(doFocus,index){
27800         return;
27801         
27802     },
27803     select: function () {
27804         //Roo.log("SELECT CALLED");
27805     },
27806      
27807     selectByValue : function(xv, scrollIntoView){
27808         var ar = this.getValueArray();
27809         var sels = [];
27810         
27811         Roo.each(ar, function(v) {
27812             if(v === undefined || v === null){
27813                 return;
27814             }
27815             var r = this.findRecord(this.valueField, v);
27816             if(r){
27817                 sels.push(this.store.indexOf(r))
27818                 
27819             }
27820         },this);
27821         this.view.select(sels);
27822         return false;
27823     },
27824     
27825     
27826     
27827     onSelect : function(record, index){
27828        // Roo.log("onselect Called");
27829        // this is only called by the clear button now..
27830         this.view.clearSelections();
27831         this.setValue('[]');
27832         if (this.value != this.valueBefore) {
27833             this.fireEvent('change', this, this.value, this.valueBefore);
27834             this.valueBefore = this.value;
27835         }
27836     },
27837     getValueArray : function()
27838     {
27839         var ar = [] ;
27840         
27841         try {
27842             //Roo.log(this.value);
27843             if (typeof(this.value) == 'undefined') {
27844                 return [];
27845             }
27846             var ar = Roo.decode(this.value);
27847             return  ar instanceof Array ? ar : []; //?? valid?
27848             
27849         } catch(e) {
27850             Roo.log(e + "\nRoo.form.ComboCheck:getValueArray  invalid data:" + this.getValue());
27851             return [];
27852         }
27853          
27854     },
27855     expand : function ()
27856     {
27857         
27858         Roo.form.ComboCheck.superclass.expand.call(this);
27859         this.valueBefore = typeof(this.value) == 'undefined' ? '' : this.value;
27860         //this.valueBefore = typeof(this.valueBefore) == 'undefined' ? '' : this.valueBefore;
27861         
27862
27863     },
27864     
27865     collapse : function(){
27866         Roo.form.ComboCheck.superclass.collapse.call(this);
27867         var sl = this.view.getSelectedIndexes();
27868         var st = this.store;
27869         var nv = [];
27870         var tv = [];
27871         var r;
27872         Roo.each(sl, function(i) {
27873             r = st.getAt(i);
27874             nv.push(r.get(this.valueField));
27875         },this);
27876         this.setValue(Roo.encode(nv));
27877         if (this.value != this.valueBefore) {
27878
27879             this.fireEvent('change', this, this.value, this.valueBefore);
27880             this.valueBefore = this.value;
27881         }
27882         
27883     },
27884     
27885     setValue : function(v){
27886         // Roo.log(v);
27887         this.value = v;
27888         
27889         var vals = this.getValueArray();
27890         var tv = [];
27891         Roo.each(vals, function(k) {
27892             var r = this.findRecord(this.valueField, k);
27893             if(r){
27894                 tv.push(r.data[this.displayField]);
27895             }else if(this.valueNotFoundText !== undefined){
27896                 tv.push( this.valueNotFoundText );
27897             }
27898         },this);
27899        // Roo.log(tv);
27900         
27901         Roo.form.ComboBox.superclass.setValue.call(this, tv.join(', '));
27902         this.hiddenField.value = v;
27903         this.value = v;
27904     }
27905     
27906 });/*
27907  * Based on:
27908  * Ext JS Library 1.1.1
27909  * Copyright(c) 2006-2007, Ext JS, LLC.
27910  *
27911  * Originally Released Under LGPL - original licence link has changed is not relivant.
27912  *
27913  * Fork - LGPL
27914  * <script type="text/javascript">
27915  */
27916  
27917 /**
27918  * @class Roo.form.Signature
27919  * @extends Roo.form.Field
27920  * Signature field.  
27921  * @constructor
27922  * 
27923  * @param {Object} config Configuration options
27924  */
27925
27926 Roo.form.Signature = function(config){
27927     Roo.form.Signature.superclass.constructor.call(this, config);
27928     
27929     this.addEvents({// not in used??
27930          /**
27931          * @event confirm
27932          * Fires when the 'confirm' icon is pressed (add a listener to enable add button)
27933              * @param {Roo.form.Signature} combo This combo box
27934              */
27935         'confirm' : true,
27936         /**
27937          * @event reset
27938          * Fires when the 'edit' icon is pressed (add a listener to enable add button)
27939              * @param {Roo.form.ComboBox} combo This combo box
27940              * @param {Roo.data.Record|false} record The data record returned from the underlying store (or false on nothing selected)
27941              */
27942         'reset' : true
27943     });
27944 };
27945
27946 Roo.extend(Roo.form.Signature, Roo.form.Field,  {
27947     /**
27948      * @cfg {Object} labels Label to use when rendering a form.
27949      * defaults to 
27950      * labels : { 
27951      *      clear : "Clear",
27952      *      confirm : "Confirm"
27953      *  }
27954      */
27955     labels : { 
27956         clear : "Clear",
27957         confirm : "Confirm"
27958     },
27959     /**
27960      * @cfg {Number} width The signature panel width (defaults to 300)
27961      */
27962     width: 300,
27963     /**
27964      * @cfg {Number} height The signature panel height (defaults to 100)
27965      */
27966     height : 100,
27967     /**
27968      * @cfg {Boolean} allowBlank False to validate that the value length > 0 (defaults to false)
27969      */
27970     allowBlank : false,
27971     
27972     //private
27973     // {Object} signPanel The signature SVG panel element (defaults to {})
27974     signPanel : {},
27975     // {Boolean} isMouseDown False to validate that the mouse down event (defaults to false)
27976     isMouseDown : false,
27977     // {Boolean} isConfirmed validate the signature is confirmed or not for submitting form (defaults to false)
27978     isConfirmed : false,
27979     // {String} signatureTmp SVG mapping string (defaults to empty string)
27980     signatureTmp : '',
27981     
27982     
27983     defaultAutoCreate : { // modified by initCompnoent..
27984         tag: "input",
27985         type:"hidden"
27986     },
27987
27988     // private
27989     onRender : function(ct, position){
27990         
27991         Roo.form.Signature.superclass.onRender.call(this, ct, position);
27992         
27993         this.wrap = this.el.wrap({
27994             cls:'x-form-signature-wrap', style : 'width: ' + this.width + 'px', cn:{cls:'x-form-signature'}
27995         });
27996         
27997         this.createToolbar(this);
27998         this.signPanel = this.wrap.createChild({
27999                 tag: 'div',
28000                 style: 'width: ' + this.width + 'px; height: ' + this.height + 'px; border: 0;'
28001             }, this.el
28002         );
28003             
28004         this.svgID = Roo.id();
28005         this.svgEl = this.signPanel.createChild({
28006               xmlns : 'http://www.w3.org/2000/svg',
28007               tag : 'svg',
28008               id : this.svgID + "-svg",
28009               width: this.width,
28010               height: this.height,
28011               viewBox: '0 0 '+this.width+' '+this.height,
28012               cn : [
28013                 {
28014                     tag: "rect",
28015                     id: this.svgID + "-svg-r",
28016                     width: this.width,
28017                     height: this.height,
28018                     fill: "#ffa"
28019                 },
28020                 {
28021                     tag: "line",
28022                     id: this.svgID + "-svg-l",
28023                     x1: "0", // start
28024                     y1: (this.height*0.8), // start set the line in 80% of height
28025                     x2: this.width, // end
28026                     y2: (this.height*0.8), // end set the line in 80% of height
28027                     'stroke': "#666",
28028                     'stroke-width': "1",
28029                     'stroke-dasharray': "3",
28030                     'shape-rendering': "crispEdges",
28031                     'pointer-events': "none"
28032                 },
28033                 {
28034                     tag: "path",
28035                     id: this.svgID + "-svg-p",
28036                     'stroke': "navy",
28037                     'stroke-width': "3",
28038                     'fill': "none",
28039                     'pointer-events': 'none'
28040                 }
28041               ]
28042         });
28043         this.createSVG();
28044         this.svgBox = this.svgEl.dom.getScreenCTM();
28045     },
28046     createSVG : function(){ 
28047         var svg = this.signPanel;
28048         var r = svg.select('#'+ this.svgID + '-svg-r', true).first().dom;
28049         var t = this;
28050
28051         r.addEventListener('mousedown', function(e) { return t.down(e); }, false);
28052         r.addEventListener('mousemove', function(e) { return t.move(e); }, false);
28053         r.addEventListener('mouseup', function(e) { return t.up(e); }, false);
28054         r.addEventListener('mouseout', function(e) { return t.up(e); }, false);
28055         r.addEventListener('touchstart', function(e) { return t.down(e); }, false);
28056         r.addEventListener('touchmove', function(e) { return t.move(e); }, false);
28057         r.addEventListener('touchend', function(e) { return t.up(e); }, false);
28058         
28059     },
28060     isTouchEvent : function(e){
28061         return e.type.match(/^touch/);
28062     },
28063     getCoords : function (e) {
28064         var pt    = this.svgEl.dom.createSVGPoint();
28065         pt.x = e.clientX; 
28066         pt.y = e.clientY;
28067         if (this.isTouchEvent(e)) {
28068             pt.x =  e.targetTouches[0].clientX;
28069             pt.y = e.targetTouches[0].clientY;
28070         }
28071         var a = this.svgEl.dom.getScreenCTM();
28072         var b = a.inverse();
28073         var mx = pt.matrixTransform(b);
28074         return mx.x + ',' + mx.y;
28075     },
28076     //mouse event headler 
28077     down : function (e) {
28078         this.signatureTmp += 'M' + this.getCoords(e) + ' ';
28079         this.signPanel.select('#'+ this.svgID + '-svg-p', true).first().attr('d', this.signatureTmp);
28080         
28081         this.isMouseDown = true;
28082         
28083         e.preventDefault();
28084     },
28085     move : function (e) {
28086         if (this.isMouseDown) {
28087             this.signatureTmp += 'L' + this.getCoords(e) + ' ';
28088             this.signPanel.select('#'+ this.svgID + '-svg-p', true).first().attr( 'd', this.signatureTmp);
28089         }
28090         
28091         e.preventDefault();
28092     },
28093     up : function (e) {
28094         this.isMouseDown = false;
28095         var sp = this.signatureTmp.split(' ');
28096         
28097         if(sp.length > 1){
28098             if(!sp[sp.length-2].match(/^L/)){
28099                 sp.pop();
28100                 sp.pop();
28101                 sp.push("");
28102                 this.signatureTmp = sp.join(" ");
28103             }
28104         }
28105         if(this.getValue() != this.signatureTmp){
28106             this.signPanel.select('#'+ this.svgID + '-svg-r', true).first().attr('fill', '#ffa');
28107             this.isConfirmed = false;
28108         }
28109         e.preventDefault();
28110     },
28111     
28112     /**
28113      * Protected method that will not generally be called directly. It
28114      * is called when the editor creates its toolbar. Override this method if you need to
28115      * add custom toolbar buttons.
28116      * @param {HtmlEditor} editor
28117      */
28118     createToolbar : function(editor){
28119          function btn(id, toggle, handler){
28120             var xid = fid + '-'+ id ;
28121             return {
28122                 id : xid,
28123                 cmd : id,
28124                 cls : 'x-btn-icon x-edit-'+id,
28125                 enableToggle:toggle !== false,
28126                 scope: editor, // was editor...
28127                 handler:handler||editor.relayBtnCmd,
28128                 clickEvent:'mousedown',
28129                 tooltip: etb.buttonTips[id] || undefined, ///tips ???
28130                 tabIndex:-1
28131             };
28132         }
28133         
28134         
28135         var tb = new Roo.Toolbar(editor.wrap.dom.firstChild);
28136         this.tb = tb;
28137         this.tb.add(
28138            {
28139                 cls : ' x-signature-btn x-signature-'+id,
28140                 scope: editor, // was editor...
28141                 handler: this.reset,
28142                 clickEvent:'mousedown',
28143                 text: this.labels.clear
28144             },
28145             {
28146                  xtype : 'Fill',
28147                  xns: Roo.Toolbar
28148             }, 
28149             {
28150                 cls : '  x-signature-btn x-signature-'+id,
28151                 scope: editor, // was editor...
28152                 handler: this.confirmHandler,
28153                 clickEvent:'mousedown',
28154                 text: this.labels.confirm
28155             }
28156         );
28157     
28158     },
28159     //public
28160     /**
28161      * when user is clicked confirm then show this image.....
28162      * 
28163      * @return {String} Image Data URI
28164      */
28165     getImageDataURI : function(){
28166         var svg = this.svgEl.dom.parentNode.innerHTML;
28167         var src = 'data:image/svg+xml;base64,'+window.btoa(svg);
28168         return src; 
28169     },
28170     /**
28171      * 
28172      * @return {Boolean} this.isConfirmed
28173      */
28174     getConfirmed : function(){
28175         return this.isConfirmed;
28176     },
28177     /**
28178      * 
28179      * @return {Number} this.width
28180      */
28181     getWidth : function(){
28182         return this.width;
28183     },
28184     /**
28185      * 
28186      * @return {Number} this.height
28187      */
28188     getHeight : function(){
28189         return this.height;
28190     },
28191     // private
28192     getSignature : function(){
28193         return this.signatureTmp;
28194     },
28195     // private
28196     reset : function(){
28197         this.signatureTmp = '';
28198         this.signPanel.select('#'+ this.svgID + '-svg-r', true).first().attr('fill', '#ffa');
28199         this.signPanel.select('#'+ this.svgID + '-svg-p', true).first().attr( 'd', '');
28200         this.isConfirmed = false;
28201         Roo.form.Signature.superclass.reset.call(this);
28202     },
28203     setSignature : function(s){
28204         this.signatureTmp = s;
28205         this.signPanel.select('#'+ this.svgID + '-svg-r', true).first().attr('fill', '#ffa');
28206         this.signPanel.select('#'+ this.svgID + '-svg-p', true).first().attr( 'd', s);
28207         this.setValue(s);
28208         this.isConfirmed = false;
28209         Roo.form.Signature.superclass.reset.call(this);
28210     }, 
28211     test : function(){
28212 //        Roo.log(this.signPanel.dom.contentWindow.up())
28213     },
28214     //private
28215     setConfirmed : function(){
28216         
28217         
28218         
28219 //        Roo.log(Roo.get(this.signPanel.dom.contentWindow.r).attr('fill', '#cfc'));
28220     },
28221     // private
28222     confirmHandler : function(){
28223         if(!this.getSignature()){
28224             return;
28225         }
28226         
28227         this.signPanel.select('#'+ this.svgID + '-svg-r', true).first().attr('fill', '#cfc');
28228         this.setValue(this.getSignature());
28229         this.isConfirmed = true;
28230         
28231         this.fireEvent('confirm', this);
28232     },
28233     // private
28234     // Subclasses should provide the validation implementation by overriding this
28235     validateValue : function(value){
28236         if(this.allowBlank){
28237             return true;
28238         }
28239         
28240         if(this.isConfirmed){
28241             return true;
28242         }
28243         return false;
28244     }
28245 });/*
28246  * Based on:
28247  * Ext JS Library 1.1.1
28248  * Copyright(c) 2006-2007, Ext JS, LLC.
28249  *
28250  * Originally Released Under LGPL - original licence link has changed is not relivant.
28251  *
28252  * Fork - LGPL
28253  * <script type="text/javascript">
28254  */
28255  
28256
28257 /**
28258  * @class Roo.form.ComboBox
28259  * @extends Roo.form.TriggerField
28260  * A combobox control with support for autocomplete, remote-loading, paging and many other features.
28261  * @constructor
28262  * Create a new ComboBox.
28263  * @param {Object} config Configuration options
28264  */
28265 Roo.form.Select = function(config){
28266     Roo.form.Select.superclass.constructor.call(this, config);
28267      
28268 };
28269
28270 Roo.extend(Roo.form.Select , Roo.form.ComboBox, {
28271     /**
28272      * @cfg {String/HTMLElement/Element} transform The id, DOM node or element of an existing select to convert to a ComboBox
28273      */
28274     /**
28275      * @cfg {Boolean} lazyRender True to prevent the ComboBox from rendering until requested (should always be used when
28276      * rendering into an Roo.Editor, defaults to false)
28277      */
28278     /**
28279      * @cfg {Boolean/Object} autoCreate A DomHelper element spec, or true for a default element spec (defaults to:
28280      * {tag: "input", type: "text", size: "24", autocomplete: "off"})
28281      */
28282     /**
28283      * @cfg {Roo.data.Store} store The data store to which this combo is bound (defaults to undefined)
28284      */
28285     /**
28286      * @cfg {String} title If supplied, a header element is created containing this text and added into the top of
28287      * the dropdown list (defaults to undefined, with no header element)
28288      */
28289
28290      /**
28291      * @cfg {String/Roo.Template} tpl The template to use to render the output
28292      */
28293      
28294     // private
28295     defaultAutoCreate : {tag: "select"  },
28296     /**
28297      * @cfg {Number} listWidth The width in pixels of the dropdown list (defaults to the width of the ComboBox field)
28298      */
28299     listWidth: undefined,
28300     /**
28301      * @cfg {String} displayField The underlying data field name to bind to this CombBox (defaults to undefined if
28302      * mode = 'remote' or 'text' if mode = 'local')
28303      */
28304     displayField: undefined,
28305     /**
28306      * @cfg {String} valueField The underlying data value name to bind to this CombBox (defaults to undefined if
28307      * mode = 'remote' or 'value' if mode = 'local'). 
28308      * Note: use of a valueField requires the user make a selection
28309      * in order for a value to be mapped.
28310      */
28311     valueField: undefined,
28312     
28313     
28314     /**
28315      * @cfg {String} hiddenName If specified, a hidden form field with this name is dynamically generated to store the
28316      * field's data value (defaults to the underlying DOM element's name)
28317      */
28318     hiddenName: undefined,
28319     /**
28320      * @cfg {String} listClass CSS class to apply to the dropdown list element (defaults to '')
28321      */
28322     listClass: '',
28323     /**
28324      * @cfg {String} selectedClass CSS class to apply to the selected item in the dropdown list (defaults to 'x-combo-selected')
28325      */
28326     selectedClass: 'x-combo-selected',
28327     /**
28328      * @cfg {String} triggerClass An additional CSS class used to style the trigger button.  The trigger will always get the
28329      * class 'x-form-trigger' and triggerClass will be <b>appended</b> if specified (defaults to 'x-form-arrow-trigger'
28330      * which displays a downward arrow icon).
28331      */
28332     triggerClass : 'x-form-arrow-trigger',
28333     /**
28334      * @cfg {Boolean/String} shadow True or "sides" for the default effect, "frame" for 4-way shadow, and "drop" for bottom-right
28335      */
28336     shadow:'sides',
28337     /**
28338      * @cfg {String} listAlign A valid anchor position value. See {@link Roo.Element#alignTo} for details on supported
28339      * anchor positions (defaults to 'tl-bl')
28340      */
28341     listAlign: 'tl-bl?',
28342     /**
28343      * @cfg {Number} maxHeight The maximum height in pixels of the dropdown list before scrollbars are shown (defaults to 300)
28344      */
28345     maxHeight: 300,
28346     /**
28347      * @cfg {String} triggerAction The action to execute when the trigger field is activated.  Use 'all' to run the
28348      * query specified by the allQuery config option (defaults to 'query')
28349      */
28350     triggerAction: 'query',
28351     /**
28352      * @cfg {Number} minChars The minimum number of characters the user must type before autocomplete and typeahead activate
28353      * (defaults to 4, does not apply if editable = false)
28354      */
28355     minChars : 4,
28356     /**
28357      * @cfg {Boolean} typeAhead True to populate and autoselect the remainder of the text being typed after a configurable
28358      * delay (typeAheadDelay) if it matches a known value (defaults to false)
28359      */
28360     typeAhead: false,
28361     /**
28362      * @cfg {Number} queryDelay The length of time in milliseconds to delay between the start of typing and sending the
28363      * query to filter the dropdown list (defaults to 500 if mode = 'remote' or 10 if mode = 'local')
28364      */
28365     queryDelay: 500,
28366     /**
28367      * @cfg {Number} pageSize If greater than 0, a paging toolbar is displayed in the footer of the dropdown list and the
28368      * filter queries will execute with page start and limit parameters.  Only applies when mode = 'remote' (defaults to 0)
28369      */
28370     pageSize: 0,
28371     /**
28372      * @cfg {Boolean} selectOnFocus True to select any existing text in the field immediately on focus.  Only applies
28373      * when editable = true (defaults to false)
28374      */
28375     selectOnFocus:false,
28376     /**
28377      * @cfg {String} queryParam Name of the query as it will be passed on the querystring (defaults to 'query')
28378      */
28379     queryParam: 'query',
28380     /**
28381      * @cfg {String} loadingText The text to display in the dropdown list while data is loading.  Only applies
28382      * when mode = 'remote' (defaults to 'Loading...')
28383      */
28384     loadingText: 'Loading...',
28385     /**
28386      * @cfg {Boolean} resizable True to add a resize handle to the bottom of the dropdown list (defaults to false)
28387      */
28388     resizable: false,
28389     /**
28390      * @cfg {Number} handleHeight The height in pixels of the dropdown list resize handle if resizable = true (defaults to 8)
28391      */
28392     handleHeight : 8,
28393     /**
28394      * @cfg {Boolean} editable False to prevent the user from typing text directly into the field, just like a
28395      * traditional select (defaults to true)
28396      */
28397     editable: true,
28398     /**
28399      * @cfg {String} allQuery The text query to send to the server to return all records for the list with no filtering (defaults to '')
28400      */
28401     allQuery: '',
28402     /**
28403      * @cfg {String} mode Set to 'local' if the ComboBox loads local data (defaults to 'remote' which loads from the server)
28404      */
28405     mode: 'remote',
28406     /**
28407      * @cfg {Number} minListWidth The minimum width of the dropdown list in pixels (defaults to 70, will be ignored if
28408      * listWidth has a higher value)
28409      */
28410     minListWidth : 70,
28411     /**
28412      * @cfg {Boolean} forceSelection True to restrict the selected value to one of the values in the list, false to
28413      * allow the user to set arbitrary text into the field (defaults to false)
28414      */
28415     forceSelection:false,
28416     /**
28417      * @cfg {Number} typeAheadDelay The length of time in milliseconds to wait until the typeahead text is displayed
28418      * if typeAhead = true (defaults to 250)
28419      */
28420     typeAheadDelay : 250,
28421     /**
28422      * @cfg {String} valueNotFoundText When using a name/value combo, if the value passed to setValue is not found in
28423      * the store, valueNotFoundText will be displayed as the field text if defined (defaults to undefined)
28424      */
28425     valueNotFoundText : undefined,
28426     
28427     /**
28428      * @cfg {String} defaultValue The value displayed after loading the store.
28429      */
28430     defaultValue: '',
28431     
28432     /**
28433      * @cfg {Boolean} blockFocus Prevents all focus calls, so it can work with things like HTML edtor bar
28434      */
28435     blockFocus : false,
28436     
28437     /**
28438      * @cfg {Boolean} disableClear Disable showing of clear button.
28439      */
28440     disableClear : false,
28441     /**
28442      * @cfg {Boolean} alwaysQuery  Disable caching of results, and always send query
28443      */
28444     alwaysQuery : false,
28445     
28446     //private
28447     addicon : false,
28448     editicon: false,
28449     
28450     // element that contains real text value.. (when hidden is used..)
28451      
28452     // private
28453     onRender : function(ct, position){
28454         Roo.form.Field.prototype.onRender.call(this, ct, position);
28455         
28456         if(this.store){
28457             this.store.on('beforeload', this.onBeforeLoad, this);
28458             this.store.on('load', this.onLoad, this);
28459             this.store.on('loadexception', this.onLoadException, this);
28460             this.store.load({});
28461         }
28462         
28463         
28464         
28465     },
28466
28467     // private
28468     initEvents : function(){
28469         //Roo.form.ComboBox.superclass.initEvents.call(this);
28470  
28471     },
28472
28473     onDestroy : function(){
28474        
28475         if(this.store){
28476             this.store.un('beforeload', this.onBeforeLoad, this);
28477             this.store.un('load', this.onLoad, this);
28478             this.store.un('loadexception', this.onLoadException, this);
28479         }
28480         //Roo.form.ComboBox.superclass.onDestroy.call(this);
28481     },
28482
28483     // private
28484     fireKey : function(e){
28485         if(e.isNavKeyPress() && !this.list.isVisible()){
28486             this.fireEvent("specialkey", this, e);
28487         }
28488     },
28489
28490     // private
28491     onResize: function(w, h){
28492         
28493         return; 
28494     
28495         
28496     },
28497
28498     /**
28499      * Allow or prevent the user from directly editing the field text.  If false is passed,
28500      * the user will only be able to select from the items defined in the dropdown list.  This method
28501      * is the runtime equivalent of setting the 'editable' config option at config time.
28502      * @param {Boolean} value True to allow the user to directly edit the field text
28503      */
28504     setEditable : function(value){
28505          
28506     },
28507
28508     // private
28509     onBeforeLoad : function(){
28510         
28511         Roo.log("Select before load");
28512         return;
28513     
28514         this.innerList.update(this.loadingText ?
28515                '<div class="loading-indicator">'+this.loadingText+'</div>' : '');
28516         //this.restrictHeight();
28517         this.selectedIndex = -1;
28518     },
28519
28520     // private
28521     onLoad : function(){
28522
28523     
28524         var dom = this.el.dom;
28525         dom.innerHTML = '';
28526          var od = dom.ownerDocument;
28527          
28528         if (this.emptyText) {
28529             var op = od.createElement('option');
28530             op.setAttribute('value', '');
28531             op.innerHTML = String.format('{0}', this.emptyText);
28532             dom.appendChild(op);
28533         }
28534         if(this.store.getCount() > 0){
28535            
28536             var vf = this.valueField;
28537             var df = this.displayField;
28538             this.store.data.each(function(r) {
28539                 // which colmsn to use... testing - cdoe / title..
28540                 var op = od.createElement('option');
28541                 op.setAttribute('value', r.data[vf]);
28542                 op.innerHTML = String.format('{0}', r.data[df]);
28543                 dom.appendChild(op);
28544             });
28545             if (typeof(this.defaultValue != 'undefined')) {
28546                 this.setValue(this.defaultValue);
28547             }
28548             
28549              
28550         }else{
28551             //this.onEmptyResults();
28552         }
28553         //this.el.focus();
28554     },
28555     // private
28556     onLoadException : function()
28557     {
28558         dom.innerHTML = '';
28559             
28560         Roo.log("Select on load exception");
28561         return;
28562     
28563         this.collapse();
28564         Roo.log(this.store.reader.jsonData);
28565         if (this.store && typeof(this.store.reader.jsonData.errorMsg) != 'undefined') {
28566             Roo.MessageBox.alert("Error loading",this.store.reader.jsonData.errorMsg);
28567         }
28568         
28569         
28570     },
28571     // private
28572     onTypeAhead : function(){
28573          
28574     },
28575
28576     // private
28577     onSelect : function(record, index){
28578         Roo.log('on select?');
28579         return;
28580         if(this.fireEvent('beforeselect', this, record, index) !== false){
28581             this.setFromData(index > -1 ? record.data : false);
28582             this.collapse();
28583             this.fireEvent('select', this, record, index);
28584         }
28585     },
28586
28587     /**
28588      * Returns the currently selected field value or empty string if no value is set.
28589      * @return {String} value The selected value
28590      */
28591     getValue : function(){
28592         var dom = this.el.dom;
28593         this.value = dom.options[dom.selectedIndex].value;
28594         return this.value;
28595         
28596     },
28597
28598     /**
28599      * Clears any text/value currently set in the field
28600      */
28601     clearValue : function(){
28602         this.value = '';
28603         this.el.dom.selectedIndex = this.emptyText ? 0 : -1;
28604         
28605     },
28606
28607     /**
28608      * Sets the specified value into the field.  If the value finds a match, the corresponding record text
28609      * will be displayed in the field.  If the value does not match the data value of an existing item,
28610      * and the valueNotFoundText config option is defined, it will be displayed as the default field text.
28611      * Otherwise the field will be blank (although the value will still be set).
28612      * @param {String} value The value to match
28613      */
28614     setValue : function(v){
28615         var d = this.el.dom;
28616         for (var i =0; i < d.options.length;i++) {
28617             if (v == d.options[i].value) {
28618                 d.selectedIndex = i;
28619                 this.value = v;
28620                 return;
28621             }
28622         }
28623         this.clearValue();
28624     },
28625     /**
28626      * @property {Object} the last set data for the element
28627      */
28628     
28629     lastData : false,
28630     /**
28631      * Sets the value of the field based on a object which is related to the record format for the store.
28632      * @param {Object} value the value to set as. or false on reset?
28633      */
28634     setFromData : function(o){
28635         Roo.log('setfrom data?');
28636          
28637         
28638         
28639     },
28640     // private
28641     reset : function(){
28642         this.clearValue();
28643     },
28644     // private
28645     findRecord : function(prop, value){
28646         
28647         return false;
28648     
28649         var record;
28650         if(this.store.getCount() > 0){
28651             this.store.each(function(r){
28652                 if(r.data[prop] == value){
28653                     record = r;
28654                     return false;
28655                 }
28656                 return true;
28657             });
28658         }
28659         return record;
28660     },
28661     
28662     getName: function()
28663     {
28664         // returns hidden if it's set..
28665         if (!this.rendered) {return ''};
28666         return !this.hiddenName && this.el.dom.name  ? this.el.dom.name : (this.hiddenName || '');
28667         
28668     },
28669      
28670
28671     
28672
28673     // private
28674     onEmptyResults : function(){
28675         Roo.log('empty results');
28676         //this.collapse();
28677     },
28678
28679     /**
28680      * Returns true if the dropdown list is expanded, else false.
28681      */
28682     isExpanded : function(){
28683         return false;
28684     },
28685
28686     /**
28687      * Select an item in the dropdown list by its data value. This function does NOT cause the select event to fire.
28688      * The store must be loaded and the list expanded for this function to work, otherwise use setValue.
28689      * @param {String} value The data value of the item to select
28690      * @param {Boolean} scrollIntoView False to prevent the dropdown list from autoscrolling to display the
28691      * selected item if it is not currently in view (defaults to true)
28692      * @return {Boolean} True if the value matched an item in the list, else false
28693      */
28694     selectByValue : function(v, scrollIntoView){
28695         Roo.log('select By Value');
28696         return false;
28697     
28698         if(v !== undefined && v !== null){
28699             var r = this.findRecord(this.valueField || this.displayField, v);
28700             if(r){
28701                 this.select(this.store.indexOf(r), scrollIntoView);
28702                 return true;
28703             }
28704         }
28705         return false;
28706     },
28707
28708     /**
28709      * Select an item in the dropdown list by its numeric index in the list. This function does NOT cause the select event to fire.
28710      * The store must be loaded and the list expanded for this function to work, otherwise use setValue.
28711      * @param {Number} index The zero-based index of the list item to select
28712      * @param {Boolean} scrollIntoView False to prevent the dropdown list from autoscrolling to display the
28713      * selected item if it is not currently in view (defaults to true)
28714      */
28715     select : function(index, scrollIntoView){
28716         Roo.log('select ');
28717         return  ;
28718         
28719         this.selectedIndex = index;
28720         this.view.select(index);
28721         if(scrollIntoView !== false){
28722             var el = this.view.getNode(index);
28723             if(el){
28724                 this.innerList.scrollChildIntoView(el, false);
28725             }
28726         }
28727     },
28728
28729       
28730
28731     // private
28732     validateBlur : function(){
28733         
28734         return;
28735         
28736     },
28737
28738     // private
28739     initQuery : function(){
28740         this.doQuery(this.getRawValue());
28741     },
28742
28743     // private
28744     doForce : function(){
28745         if(this.el.dom.value.length > 0){
28746             this.el.dom.value =
28747                 this.lastSelectionText === undefined ? '' : this.lastSelectionText;
28748              
28749         }
28750     },
28751
28752     /**
28753      * Execute a query to filter the dropdown list.  Fires the beforequery event prior to performing the
28754      * query allowing the query action to be canceled if needed.
28755      * @param {String} query The SQL query to execute
28756      * @param {Boolean} forceAll True to force the query to execute even if there are currently fewer characters
28757      * in the field than the minimum specified by the minChars config option.  It also clears any filter previously
28758      * saved in the current store (defaults to false)
28759      */
28760     doQuery : function(q, forceAll){
28761         
28762         Roo.log('doQuery?');
28763         if(q === undefined || q === null){
28764             q = '';
28765         }
28766         var qe = {
28767             query: q,
28768             forceAll: forceAll,
28769             combo: this,
28770             cancel:false
28771         };
28772         if(this.fireEvent('beforequery', qe)===false || qe.cancel){
28773             return false;
28774         }
28775         q = qe.query;
28776         forceAll = qe.forceAll;
28777         if(forceAll === true || (q.length >= this.minChars)){
28778             if(this.lastQuery != q || this.alwaysQuery){
28779                 this.lastQuery = q;
28780                 if(this.mode == 'local'){
28781                     this.selectedIndex = -1;
28782                     if(forceAll){
28783                         this.store.clearFilter();
28784                     }else{
28785                         this.store.filter(this.displayField, q);
28786                     }
28787                     this.onLoad();
28788                 }else{
28789                     this.store.baseParams[this.queryParam] = q;
28790                     this.store.load({
28791                         params: this.getParams(q)
28792                     });
28793                     this.expand();
28794                 }
28795             }else{
28796                 this.selectedIndex = -1;
28797                 this.onLoad();   
28798             }
28799         }
28800     },
28801
28802     // private
28803     getParams : function(q){
28804         var p = {};
28805         //p[this.queryParam] = q;
28806         if(this.pageSize){
28807             p.start = 0;
28808             p.limit = this.pageSize;
28809         }
28810         return p;
28811     },
28812
28813     /**
28814      * Hides the dropdown list if it is currently expanded. Fires the 'collapse' event on completion.
28815      */
28816     collapse : function(){
28817         
28818     },
28819
28820     // private
28821     collapseIf : function(e){
28822         
28823     },
28824
28825     /**
28826      * Expands the dropdown list if it is currently hidden. Fires the 'expand' event on completion.
28827      */
28828     expand : function(){
28829         
28830     } ,
28831
28832     // private
28833      
28834
28835     /** 
28836     * @cfg {Boolean} grow 
28837     * @hide 
28838     */
28839     /** 
28840     * @cfg {Number} growMin 
28841     * @hide 
28842     */
28843     /** 
28844     * @cfg {Number} growMax 
28845     * @hide 
28846     */
28847     /**
28848      * @hide
28849      * @method autoSize
28850      */
28851     
28852     setWidth : function()
28853     {
28854         
28855     },
28856     getResizeEl : function(){
28857         return this.el;
28858     }
28859 });//<script type="text/javasscript">
28860  
28861
28862 /**
28863  * @class Roo.DDView
28864  * A DnD enabled version of Roo.View.
28865  * @param {Element/String} container The Element in which to create the View.
28866  * @param {String} tpl The template string used to create the markup for each element of the View
28867  * @param {Object} config The configuration properties. These include all the config options of
28868  * {@link Roo.View} plus some specific to this class.<br>
28869  * <p>
28870  * Drag/drop is implemented by adding {@link Roo.data.Record}s to the target DDView. If copying is
28871  * not being performed, the original {@link Roo.data.Record} is removed from the source DDView.<br>
28872  * <p>
28873  * The following extra CSS rules are needed to provide insertion point highlighting:<pre><code>
28874 .x-view-drag-insert-above {
28875         border-top:1px dotted #3366cc;
28876 }
28877 .x-view-drag-insert-below {
28878         border-bottom:1px dotted #3366cc;
28879 }
28880 </code></pre>
28881  * 
28882  */
28883  
28884 Roo.DDView = function(container, tpl, config) {
28885     Roo.DDView.superclass.constructor.apply(this, arguments);
28886     this.getEl().setStyle("outline", "0px none");
28887     this.getEl().unselectable();
28888     if (this.dragGroup) {
28889                 this.setDraggable(this.dragGroup.split(","));
28890     }
28891     if (this.dropGroup) {
28892                 this.setDroppable(this.dropGroup.split(","));
28893     }
28894     if (this.deletable) {
28895         this.setDeletable();
28896     }
28897     this.isDirtyFlag = false;
28898         this.addEvents({
28899                 "drop" : true
28900         });
28901 };
28902
28903 Roo.extend(Roo.DDView, Roo.View, {
28904 /**     @cfg {String/Array} dragGroup The ddgroup name(s) for the View's DragZone. */
28905 /**     @cfg {String/Array} dropGroup The ddgroup name(s) for the View's DropZone. */
28906 /**     @cfg {Boolean} copy Causes drag operations to copy nodes rather than move. */
28907 /**     @cfg {Boolean} allowCopy Causes ctrl/drag operations to copy nodes rather than move. */
28908
28909         isFormField: true,
28910
28911         reset: Roo.emptyFn,
28912         
28913         clearInvalid: Roo.form.Field.prototype.clearInvalid,
28914
28915         validate: function() {
28916                 return true;
28917         },
28918         
28919         destroy: function() {
28920                 this.purgeListeners();
28921                 this.getEl.removeAllListeners();
28922                 this.getEl().remove();
28923                 if (this.dragZone) {
28924                         if (this.dragZone.destroy) {
28925                                 this.dragZone.destroy();
28926                         }
28927                 }
28928                 if (this.dropZone) {
28929                         if (this.dropZone.destroy) {
28930                                 this.dropZone.destroy();
28931                         }
28932                 }
28933         },
28934
28935 /**     Allows this class to be an Roo.form.Field so it can be found using {@link Roo.form.BasicForm#findField}. */
28936         getName: function() {
28937                 return this.name;
28938         },
28939
28940 /**     Loads the View from a JSON string representing the Records to put into the Store. */
28941         setValue: function(v) {
28942                 if (!this.store) {
28943                         throw "DDView.setValue(). DDView must be constructed with a valid Store";
28944                 }
28945                 var data = {};
28946                 data[this.store.reader.meta.root] = v ? [].concat(v) : [];
28947                 this.store.proxy = new Roo.data.MemoryProxy(data);
28948                 this.store.load();
28949         },
28950
28951 /**     @return {String} a parenthesised list of the ids of the Records in the View. */
28952         getValue: function() {
28953                 var result = '(';
28954                 this.store.each(function(rec) {
28955                         result += rec.id + ',';
28956                 });
28957                 return result.substr(0, result.length - 1) + ')';
28958         },
28959         
28960         getIds: function() {
28961                 var i = 0, result = new Array(this.store.getCount());
28962                 this.store.each(function(rec) {
28963                         result[i++] = rec.id;
28964                 });
28965                 return result;
28966         },
28967         
28968         isDirty: function() {
28969                 return this.isDirtyFlag;
28970         },
28971
28972 /**
28973  *      Part of the Roo.dd.DropZone interface. If no target node is found, the
28974  *      whole Element becomes the target, and this causes the drop gesture to append.
28975  */
28976     getTargetFromEvent : function(e) {
28977                 var target = e.getTarget();
28978                 while ((target !== null) && (target.parentNode != this.el.dom)) {
28979                 target = target.parentNode;
28980                 }
28981                 if (!target) {
28982                         target = this.el.dom.lastChild || this.el.dom;
28983                 }
28984                 return target;
28985     },
28986
28987 /**
28988  *      Create the drag data which consists of an object which has the property "ddel" as
28989  *      the drag proxy element. 
28990  */
28991     getDragData : function(e) {
28992         var target = this.findItemFromChild(e.getTarget());
28993                 if(target) {
28994                         this.handleSelection(e);
28995                         var selNodes = this.getSelectedNodes();
28996             var dragData = {
28997                 source: this,
28998                 copy: this.copy || (this.allowCopy && e.ctrlKey),
28999                 nodes: selNodes,
29000                 records: []
29001                         };
29002                         var selectedIndices = this.getSelectedIndexes();
29003                         for (var i = 0; i < selectedIndices.length; i++) {
29004                                 dragData.records.push(this.store.getAt(selectedIndices[i]));
29005                         }
29006                         if (selNodes.length == 1) {
29007                                 dragData.ddel = target.cloneNode(true); // the div element
29008                         } else {
29009                                 var div = document.createElement('div'); // create the multi element drag "ghost"
29010                                 div.className = 'multi-proxy';
29011                                 for (var i = 0, len = selNodes.length; i < len; i++) {
29012                                         div.appendChild(selNodes[i].cloneNode(true));
29013                                 }
29014                                 dragData.ddel = div;
29015                         }
29016             //console.log(dragData)
29017             //console.log(dragData.ddel.innerHTML)
29018                         return dragData;
29019                 }
29020         //console.log('nodragData')
29021                 return false;
29022     },
29023     
29024 /**     Specify to which ddGroup items in this DDView may be dragged. */
29025     setDraggable: function(ddGroup) {
29026         if (ddGroup instanceof Array) {
29027                 Roo.each(ddGroup, this.setDraggable, this);
29028                 return;
29029         }
29030         if (this.dragZone) {
29031                 this.dragZone.addToGroup(ddGroup);
29032         } else {
29033                         this.dragZone = new Roo.dd.DragZone(this.getEl(), {
29034                                 containerScroll: true,
29035                                 ddGroup: ddGroup 
29036
29037                         });
29038 //                      Draggability implies selection. DragZone's mousedown selects the element.
29039                         if (!this.multiSelect) { this.singleSelect = true; }
29040
29041 //                      Wire the DragZone's handlers up to methods in *this*
29042                         this.dragZone.getDragData = this.getDragData.createDelegate(this);
29043                 }
29044     },
29045
29046 /**     Specify from which ddGroup this DDView accepts drops. */
29047     setDroppable: function(ddGroup) {
29048         if (ddGroup instanceof Array) {
29049                 Roo.each(ddGroup, this.setDroppable, this);
29050                 return;
29051         }
29052         if (this.dropZone) {
29053                 this.dropZone.addToGroup(ddGroup);
29054         } else {
29055                         this.dropZone = new Roo.dd.DropZone(this.getEl(), {
29056                                 containerScroll: true,
29057                                 ddGroup: ddGroup
29058                         });
29059
29060 //                      Wire the DropZone's handlers up to methods in *this*
29061                         this.dropZone.getTargetFromEvent = this.getTargetFromEvent.createDelegate(this);
29062                         this.dropZone.onNodeEnter = this.onNodeEnter.createDelegate(this);
29063                         this.dropZone.onNodeOver = this.onNodeOver.createDelegate(this);
29064                         this.dropZone.onNodeOut = this.onNodeOut.createDelegate(this);
29065                         this.dropZone.onNodeDrop = this.onNodeDrop.createDelegate(this);
29066                 }
29067     },
29068
29069 /**     Decide whether to drop above or below a View node. */
29070     getDropPoint : function(e, n, dd){
29071         if (n == this.el.dom) { return "above"; }
29072                 var t = Roo.lib.Dom.getY(n), b = t + n.offsetHeight;
29073                 var c = t + (b - t) / 2;
29074                 var y = Roo.lib.Event.getPageY(e);
29075                 if(y <= c) {
29076                         return "above";
29077                 }else{
29078                         return "below";
29079                 }
29080     },
29081
29082     onNodeEnter : function(n, dd, e, data){
29083                 return false;
29084     },
29085     
29086     onNodeOver : function(n, dd, e, data){
29087                 var pt = this.getDropPoint(e, n, dd);
29088                 // set the insert point style on the target node
29089                 var dragElClass = this.dropNotAllowed;
29090                 if (pt) {
29091                         var targetElClass;
29092                         if (pt == "above"){
29093                                 dragElClass = n.previousSibling ? "x-tree-drop-ok-between" : "x-tree-drop-ok-above";
29094                                 targetElClass = "x-view-drag-insert-above";
29095                         } else {
29096                                 dragElClass = n.nextSibling ? "x-tree-drop-ok-between" : "x-tree-drop-ok-below";
29097                                 targetElClass = "x-view-drag-insert-below";
29098                         }
29099                         if (this.lastInsertClass != targetElClass){
29100                                 Roo.fly(n).replaceClass(this.lastInsertClass, targetElClass);
29101                                 this.lastInsertClass = targetElClass;
29102                         }
29103                 }
29104                 return dragElClass;
29105         },
29106
29107     onNodeOut : function(n, dd, e, data){
29108                 this.removeDropIndicators(n);
29109     },
29110
29111     onNodeDrop : function(n, dd, e, data){
29112         if (this.fireEvent("drop", this, n, dd, e, data) === false) {
29113                 return false;
29114         }
29115         var pt = this.getDropPoint(e, n, dd);
29116                 var insertAt = (n == this.el.dom) ? this.nodes.length : n.nodeIndex;
29117                 if (pt == "below") { insertAt++; }
29118                 for (var i = 0; i < data.records.length; i++) {
29119                         var r = data.records[i];
29120                         var dup = this.store.getById(r.id);
29121                         if (dup && (dd != this.dragZone)) {
29122                                 Roo.fly(this.getNode(this.store.indexOf(dup))).frame("red", 1);
29123                         } else {
29124                                 if (data.copy) {
29125                                         this.store.insert(insertAt++, r.copy());
29126                                 } else {
29127                                         data.source.isDirtyFlag = true;
29128                                         r.store.remove(r);
29129                                         this.store.insert(insertAt++, r);
29130                                 }
29131                                 this.isDirtyFlag = true;
29132                         }
29133                 }
29134                 this.dragZone.cachedTarget = null;
29135                 return true;
29136     },
29137
29138     removeDropIndicators : function(n){
29139                 if(n){
29140                         Roo.fly(n).removeClass([
29141                                 "x-view-drag-insert-above",
29142                                 "x-view-drag-insert-below"]);
29143                         this.lastInsertClass = "_noclass";
29144                 }
29145     },
29146
29147 /**
29148  *      Utility method. Add a delete option to the DDView's context menu.
29149  *      @param {String} imageUrl The URL of the "delete" icon image.
29150  */
29151         setDeletable: function(imageUrl) {
29152                 if (!this.singleSelect && !this.multiSelect) {
29153                         this.singleSelect = true;
29154                 }
29155                 var c = this.getContextMenu();
29156                 this.contextMenu.on("itemclick", function(item) {
29157                         switch (item.id) {
29158                                 case "delete":
29159                                         this.remove(this.getSelectedIndexes());
29160                                         break;
29161                         }
29162                 }, this);
29163                 this.contextMenu.add({
29164                         icon: imageUrl,
29165                         id: "delete",
29166                         text: 'Delete'
29167                 });
29168         },
29169         
29170 /**     Return the context menu for this DDView. */
29171         getContextMenu: function() {
29172                 if (!this.contextMenu) {
29173 //                      Create the View's context menu
29174                         this.contextMenu = new Roo.menu.Menu({
29175                                 id: this.id + "-contextmenu"
29176                         });
29177                         this.el.on("contextmenu", this.showContextMenu, this);
29178                 }
29179                 return this.contextMenu;
29180         },
29181         
29182         disableContextMenu: function() {
29183                 if (this.contextMenu) {
29184                         this.el.un("contextmenu", this.showContextMenu, this);
29185                 }
29186         },
29187
29188         showContextMenu: function(e, item) {
29189         item = this.findItemFromChild(e.getTarget());
29190                 if (item) {
29191                         e.stopEvent();
29192                         this.select(this.getNode(item), this.multiSelect && e.ctrlKey, true);
29193                         this.contextMenu.showAt(e.getXY());
29194             }
29195     },
29196
29197 /**
29198  *      Remove {@link Roo.data.Record}s at the specified indices.
29199  *      @param {Array/Number} selectedIndices The index (or Array of indices) of Records to remove.
29200  */
29201     remove: function(selectedIndices) {
29202                 selectedIndices = [].concat(selectedIndices);
29203                 for (var i = 0; i < selectedIndices.length; i++) {
29204                         var rec = this.store.getAt(selectedIndices[i]);
29205                         this.store.remove(rec);
29206                 }
29207     },
29208
29209 /**
29210  *      Double click fires the event, but also, if this is draggable, and there is only one other
29211  *      related DropZone, it transfers the selected node.
29212  */
29213     onDblClick : function(e){
29214         var item = this.findItemFromChild(e.getTarget());
29215         if(item){
29216             if (this.fireEvent("dblclick", this, this.indexOf(item), item, e) === false) {
29217                 return false;
29218             }
29219             if (this.dragGroup) {
29220                     var targets = Roo.dd.DragDropMgr.getRelated(this.dragZone, true);
29221                     while (targets.indexOf(this.dropZone) > -1) {
29222                             targets.remove(this.dropZone);
29223                                 }
29224                     if (targets.length == 1) {
29225                                         this.dragZone.cachedTarget = null;
29226                         var el = Roo.get(targets[0].getEl());
29227                         var box = el.getBox(true);
29228                         targets[0].onNodeDrop(el.dom, {
29229                                 target: el.dom,
29230                                 xy: [box.x, box.y + box.height - 1]
29231                         }, null, this.getDragData(e));
29232                     }
29233                 }
29234         }
29235     },
29236     
29237     handleSelection: function(e) {
29238                 this.dragZone.cachedTarget = null;
29239         var item = this.findItemFromChild(e.getTarget());
29240         if (!item) {
29241                 this.clearSelections(true);
29242                 return;
29243         }
29244                 if (item && (this.multiSelect || this.singleSelect)){
29245                         if(this.multiSelect && e.shiftKey && (!e.ctrlKey) && this.lastSelection){
29246                                 this.select(this.getNodes(this.indexOf(this.lastSelection), item.nodeIndex), false);
29247                         }else if (this.isSelected(this.getNode(item)) && e.ctrlKey){
29248                                 this.unselect(item);
29249                         } else {
29250                                 this.select(item, this.multiSelect && e.ctrlKey);
29251                                 this.lastSelection = item;
29252                         }
29253                 }
29254     },
29255
29256     onItemClick : function(item, index, e){
29257                 if(this.fireEvent("beforeclick", this, index, item, e) === false){
29258                         return false;
29259                 }
29260                 return true;
29261     },
29262
29263     unselect : function(nodeInfo, suppressEvent){
29264                 var node = this.getNode(nodeInfo);
29265                 if(node && this.isSelected(node)){
29266                         if(this.fireEvent("beforeselect", this, node, this.selections) !== false){
29267                                 Roo.fly(node).removeClass(this.selectedClass);
29268                                 this.selections.remove(node);
29269                                 if(!suppressEvent){
29270                                         this.fireEvent("selectionchange", this, this.selections);
29271                                 }
29272                         }
29273                 }
29274     }
29275 });
29276 /*
29277  * Based on:
29278  * Ext JS Library 1.1.1
29279  * Copyright(c) 2006-2007, Ext JS, LLC.
29280  *
29281  * Originally Released Under LGPL - original licence link has changed is not relivant.
29282  *
29283  * Fork - LGPL
29284  * <script type="text/javascript">
29285  */
29286  
29287 /**
29288  * @class Roo.LayoutManager
29289  * @extends Roo.util.Observable
29290  * Base class for layout managers.
29291  */
29292 Roo.LayoutManager = function(container, config){
29293     Roo.LayoutManager.superclass.constructor.call(this);
29294     this.el = Roo.get(container);
29295     // ie scrollbar fix
29296     if(this.el.dom == document.body && Roo.isIE && !config.allowScroll){
29297         document.body.scroll = "no";
29298     }else if(this.el.dom != document.body && this.el.getStyle('position') == 'static'){
29299         this.el.position('relative');
29300     }
29301     this.id = this.el.id;
29302     this.el.addClass("x-layout-container");
29303     /** false to disable window resize monitoring @type Boolean */
29304     this.monitorWindowResize = true;
29305     this.regions = {};
29306     this.addEvents({
29307         /**
29308          * @event layout
29309          * Fires when a layout is performed. 
29310          * @param {Roo.LayoutManager} this
29311          */
29312         "layout" : true,
29313         /**
29314          * @event regionresized
29315          * Fires when the user resizes a region. 
29316          * @param {Roo.LayoutRegion} region The resized region
29317          * @param {Number} newSize The new size (width for east/west, height for north/south)
29318          */
29319         "regionresized" : true,
29320         /**
29321          * @event regioncollapsed
29322          * Fires when a region is collapsed. 
29323          * @param {Roo.LayoutRegion} region The collapsed region
29324          */
29325         "regioncollapsed" : true,
29326         /**
29327          * @event regionexpanded
29328          * Fires when a region is expanded.  
29329          * @param {Roo.LayoutRegion} region The expanded region
29330          */
29331         "regionexpanded" : true
29332     });
29333     this.updating = false;
29334     Roo.EventManager.onWindowResize(this.onWindowResize, this, true);
29335 };
29336
29337 Roo.extend(Roo.LayoutManager, Roo.util.Observable, {
29338     /**
29339      * Returns true if this layout is currently being updated
29340      * @return {Boolean}
29341      */
29342     isUpdating : function(){
29343         return this.updating; 
29344     },
29345     
29346     /**
29347      * Suspend the LayoutManager from doing auto-layouts while
29348      * making multiple add or remove calls
29349      */
29350     beginUpdate : function(){
29351         this.updating = true;    
29352     },
29353     
29354     /**
29355      * Restore auto-layouts and optionally disable the manager from performing a layout
29356      * @param {Boolean} noLayout true to disable a layout update 
29357      */
29358     endUpdate : function(noLayout){
29359         this.updating = false;
29360         if(!noLayout){
29361             this.layout();
29362         }    
29363     },
29364     
29365     layout: function(){
29366         
29367     },
29368     
29369     onRegionResized : function(region, newSize){
29370         this.fireEvent("regionresized", region, newSize);
29371         this.layout();
29372     },
29373     
29374     onRegionCollapsed : function(region){
29375         this.fireEvent("regioncollapsed", region);
29376     },
29377     
29378     onRegionExpanded : function(region){
29379         this.fireEvent("regionexpanded", region);
29380     },
29381         
29382     /**
29383      * Returns the size of the current view. This method normalizes document.body and element embedded layouts and
29384      * performs box-model adjustments.
29385      * @return {Object} The size as an object {width: (the width), height: (the height)}
29386      */
29387     getViewSize : function(){
29388         var size;
29389         if(this.el.dom != document.body){
29390             size = this.el.getSize();
29391         }else{
29392             size = {width: Roo.lib.Dom.getViewWidth(), height: Roo.lib.Dom.getViewHeight()};
29393         }
29394         size.width -= this.el.getBorderWidth("lr")-this.el.getPadding("lr");
29395         size.height -= this.el.getBorderWidth("tb")-this.el.getPadding("tb");
29396         return size;
29397     },
29398     
29399     /**
29400      * Returns the Element this layout is bound to.
29401      * @return {Roo.Element}
29402      */
29403     getEl : function(){
29404         return this.el;
29405     },
29406     
29407     /**
29408      * Returns the specified region.
29409      * @param {String} target The region key ('center', 'north', 'south', 'east' or 'west')
29410      * @return {Roo.LayoutRegion}
29411      */
29412     getRegion : function(target){
29413         return this.regions[target.toLowerCase()];
29414     },
29415     
29416     onWindowResize : function(){
29417         if(this.monitorWindowResize){
29418             this.layout();
29419         }
29420     }
29421 });/*
29422  * Based on:
29423  * Ext JS Library 1.1.1
29424  * Copyright(c) 2006-2007, Ext JS, LLC.
29425  *
29426  * Originally Released Under LGPL - original licence link has changed is not relivant.
29427  *
29428  * Fork - LGPL
29429  * <script type="text/javascript">
29430  */
29431 /**
29432  * @class Roo.BorderLayout
29433  * @extends Roo.LayoutManager
29434  * This class represents a common layout manager used in desktop applications. For screenshots and more details,
29435  * please see: <br><br>
29436  * <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>
29437  * <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>
29438  * Example:
29439  <pre><code>
29440  var layout = new Roo.BorderLayout(document.body, {
29441     north: {
29442         initialSize: 25,
29443         titlebar: false
29444     },
29445     west: {
29446         split:true,
29447         initialSize: 200,
29448         minSize: 175,
29449         maxSize: 400,
29450         titlebar: true,
29451         collapsible: true
29452     },
29453     east: {
29454         split:true,
29455         initialSize: 202,
29456         minSize: 175,
29457         maxSize: 400,
29458         titlebar: true,
29459         collapsible: true
29460     },
29461     south: {
29462         split:true,
29463         initialSize: 100,
29464         minSize: 100,
29465         maxSize: 200,
29466         titlebar: true,
29467         collapsible: true
29468     },
29469     center: {
29470         titlebar: true,
29471         autoScroll:true,
29472         resizeTabs: true,
29473         minTabWidth: 50,
29474         preferredTabWidth: 150
29475     }
29476 });
29477
29478 // shorthand
29479 var CP = Roo.ContentPanel;
29480
29481 layout.beginUpdate();
29482 layout.add("north", new CP("north", "North"));
29483 layout.add("south", new CP("south", {title: "South", closable: true}));
29484 layout.add("west", new CP("west", {title: "West"}));
29485 layout.add("east", new CP("autoTabs", {title: "Auto Tabs", closable: true}));
29486 layout.add("center", new CP("center1", {title: "Close Me", closable: true}));
29487 layout.add("center", new CP("center2", {title: "Center Panel", closable: false}));
29488 layout.getRegion("center").showPanel("center1");
29489 layout.endUpdate();
29490 </code></pre>
29491
29492 <b>The container the layout is rendered into can be either the body element or any other element.
29493 If it is not the body element, the container needs to either be an absolute positioned element,
29494 or you will need to add "position:relative" to the css of the container.  You will also need to specify
29495 the container size if it is not the body element.</b>
29496
29497 * @constructor
29498 * Create a new BorderLayout
29499 * @param {String/HTMLElement/Element} container The container this layout is bound to
29500 * @param {Object} config Configuration options
29501  */
29502 Roo.BorderLayout = function(container, config){
29503     config = config || {};
29504     Roo.BorderLayout.superclass.constructor.call(this, container, config);
29505     this.factory = config.factory || Roo.BorderLayout.RegionFactory;
29506     for(var i = 0, len = this.factory.validRegions.length; i < len; i++) {
29507         var target = this.factory.validRegions[i];
29508         if(config[target]){
29509             this.addRegion(target, config[target]);
29510         }
29511     }
29512 };
29513
29514 Roo.extend(Roo.BorderLayout, Roo.LayoutManager, {
29515     /**
29516      * Creates and adds a new region if it doesn't already exist.
29517      * @param {String} target The target region key (north, south, east, west or center).
29518      * @param {Object} config The regions config object
29519      * @return {BorderLayoutRegion} The new region
29520      */
29521     addRegion : function(target, config){
29522         if(!this.regions[target]){
29523             var r = this.factory.create(target, this, config);
29524             this.bindRegion(target, r);
29525         }
29526         return this.regions[target];
29527     },
29528
29529     // private (kinda)
29530     bindRegion : function(name, r){
29531         this.regions[name] = r;
29532         r.on("visibilitychange", this.layout, this);
29533         r.on("paneladded", this.layout, this);
29534         r.on("panelremoved", this.layout, this);
29535         r.on("invalidated", this.layout, this);
29536         r.on("resized", this.onRegionResized, this);
29537         r.on("collapsed", this.onRegionCollapsed, this);
29538         r.on("expanded", this.onRegionExpanded, this);
29539     },
29540
29541     /**
29542      * Performs a layout update.
29543      */
29544     layout : function(){
29545         if(this.updating) {
29546             return;
29547         }
29548         var size = this.getViewSize();
29549         var w = size.width;
29550         var h = size.height;
29551         var centerW = w;
29552         var centerH = h;
29553         var centerY = 0;
29554         var centerX = 0;
29555         //var x = 0, y = 0;
29556
29557         var rs = this.regions;
29558         var north = rs["north"];
29559         var south = rs["south"]; 
29560         var west = rs["west"];
29561         var east = rs["east"];
29562         var center = rs["center"];
29563         //if(this.hideOnLayout){ // not supported anymore
29564             //c.el.setStyle("display", "none");
29565         //}
29566         if(north && north.isVisible()){
29567             var b = north.getBox();
29568             var m = north.getMargins();
29569             b.width = w - (m.left+m.right);
29570             b.x = m.left;
29571             b.y = m.top;
29572             centerY = b.height + b.y + m.bottom;
29573             centerH -= centerY;
29574             north.updateBox(this.safeBox(b));
29575         }
29576         if(south && south.isVisible()){
29577             var b = south.getBox();
29578             var m = south.getMargins();
29579             b.width = w - (m.left+m.right);
29580             b.x = m.left;
29581             var totalHeight = (b.height + m.top + m.bottom);
29582             b.y = h - totalHeight + m.top;
29583             centerH -= totalHeight;
29584             south.updateBox(this.safeBox(b));
29585         }
29586         if(west && west.isVisible()){
29587             var b = west.getBox();
29588             var m = west.getMargins();
29589             b.height = centerH - (m.top+m.bottom);
29590             b.x = m.left;
29591             b.y = centerY + m.top;
29592             var totalWidth = (b.width + m.left + m.right);
29593             centerX += totalWidth;
29594             centerW -= totalWidth;
29595             west.updateBox(this.safeBox(b));
29596         }
29597         if(east && east.isVisible()){
29598             var b = east.getBox();
29599             var m = east.getMargins();
29600             b.height = centerH - (m.top+m.bottom);
29601             var totalWidth = (b.width + m.left + m.right);
29602             b.x = w - totalWidth + m.left;
29603             b.y = centerY + m.top;
29604             centerW -= totalWidth;
29605             east.updateBox(this.safeBox(b));
29606         }
29607         if(center){
29608             var m = center.getMargins();
29609             var centerBox = {
29610                 x: centerX + m.left,
29611                 y: centerY + m.top,
29612                 width: centerW - (m.left+m.right),
29613                 height: centerH - (m.top+m.bottom)
29614             };
29615             //if(this.hideOnLayout){
29616                 //center.el.setStyle("display", "block");
29617             //}
29618             center.updateBox(this.safeBox(centerBox));
29619         }
29620         this.el.repaint();
29621         this.fireEvent("layout", this);
29622     },
29623
29624     // private
29625     safeBox : function(box){
29626         box.width = Math.max(0, box.width);
29627         box.height = Math.max(0, box.height);
29628         return box;
29629     },
29630
29631     /**
29632      * Adds a ContentPanel (or subclass) to this layout.
29633      * @param {String} target The target region key (north, south, east, west or center).
29634      * @param {Roo.ContentPanel} panel The panel to add
29635      * @return {Roo.ContentPanel} The added panel
29636      */
29637     add : function(target, panel){
29638          
29639         target = target.toLowerCase();
29640         return this.regions[target].add(panel);
29641     },
29642
29643     /**
29644      * Remove a ContentPanel (or subclass) to this layout.
29645      * @param {String} target The target region key (north, south, east, west or center).
29646      * @param {Number/String/Roo.ContentPanel} panel The index, id or panel to remove
29647      * @return {Roo.ContentPanel} The removed panel
29648      */
29649     remove : function(target, panel){
29650         target = target.toLowerCase();
29651         return this.regions[target].remove(panel);
29652     },
29653
29654     /**
29655      * Searches all regions for a panel with the specified id
29656      * @param {String} panelId
29657      * @return {Roo.ContentPanel} The panel or null if it wasn't found
29658      */
29659     findPanel : function(panelId){
29660         var rs = this.regions;
29661         for(var target in rs){
29662             if(typeof rs[target] != "function"){
29663                 var p = rs[target].getPanel(panelId);
29664                 if(p){
29665                     return p;
29666                 }
29667             }
29668         }
29669         return null;
29670     },
29671
29672     /**
29673      * Searches all regions for a panel with the specified id and activates (shows) it.
29674      * @param {String/ContentPanel} panelId The panels id or the panel itself
29675      * @return {Roo.ContentPanel} The shown panel or null
29676      */
29677     showPanel : function(panelId) {
29678       var rs = this.regions;
29679       for(var target in rs){
29680          var r = rs[target];
29681          if(typeof r != "function"){
29682             if(r.hasPanel(panelId)){
29683                return r.showPanel(panelId);
29684             }
29685          }
29686       }
29687       return null;
29688    },
29689
29690    /**
29691      * Restores this layout's state using Roo.state.Manager or the state provided by the passed provider.
29692      * @param {Roo.state.Provider} provider (optional) An alternate state provider
29693      */
29694     restoreState : function(provider){
29695         if(!provider){
29696             provider = Roo.state.Manager;
29697         }
29698         var sm = new Roo.LayoutStateManager();
29699         sm.init(this, provider);
29700     },
29701
29702     /**
29703      * Adds a batch of multiple ContentPanels dynamically by passing a special regions config object.  This config
29704      * object should contain properties for each region to add ContentPanels to, and each property's value should be
29705      * a valid ContentPanel config object.  Example:
29706      * <pre><code>
29707 // Create the main layout
29708 var layout = new Roo.BorderLayout('main-ct', {
29709     west: {
29710         split:true,
29711         minSize: 175,
29712         titlebar: true
29713     },
29714     center: {
29715         title:'Components'
29716     }
29717 }, 'main-ct');
29718
29719 // Create and add multiple ContentPanels at once via configs
29720 layout.batchAdd({
29721    west: {
29722        id: 'source-files',
29723        autoCreate:true,
29724        title:'Ext Source Files',
29725        autoScroll:true,
29726        fitToFrame:true
29727    },
29728    center : {
29729        el: cview,
29730        autoScroll:true,
29731        fitToFrame:true,
29732        toolbar: tb,
29733        resizeEl:'cbody'
29734    }
29735 });
29736 </code></pre>
29737      * @param {Object} regions An object containing ContentPanel configs by region name
29738      */
29739     batchAdd : function(regions){
29740         this.beginUpdate();
29741         for(var rname in regions){
29742             var lr = this.regions[rname];
29743             if(lr){
29744                 this.addTypedPanels(lr, regions[rname]);
29745             }
29746         }
29747         this.endUpdate();
29748     },
29749
29750     // private
29751     addTypedPanels : function(lr, ps){
29752         if(typeof ps == 'string'){
29753             lr.add(new Roo.ContentPanel(ps));
29754         }
29755         else if(ps instanceof Array){
29756             for(var i =0, len = ps.length; i < len; i++){
29757                 this.addTypedPanels(lr, ps[i]);
29758             }
29759         }
29760         else if(!ps.events){ // raw config?
29761             var el = ps.el;
29762             delete ps.el; // prevent conflict
29763             lr.add(new Roo.ContentPanel(el || Roo.id(), ps));
29764         }
29765         else {  // panel object assumed!
29766             lr.add(ps);
29767         }
29768     },
29769     /**
29770      * Adds a xtype elements to the layout.
29771      * <pre><code>
29772
29773 layout.addxtype({
29774        xtype : 'ContentPanel',
29775        region: 'west',
29776        items: [ .... ]
29777    }
29778 );
29779
29780 layout.addxtype({
29781         xtype : 'NestedLayoutPanel',
29782         region: 'west',
29783         layout: {
29784            center: { },
29785            west: { }   
29786         },
29787         items : [ ... list of content panels or nested layout panels.. ]
29788    }
29789 );
29790 </code></pre>
29791      * @param {Object} cfg Xtype definition of item to add.
29792      */
29793     addxtype : function(cfg)
29794     {
29795         // basically accepts a pannel...
29796         // can accept a layout region..!?!?
29797         //Roo.log('Roo.BorderLayout add ' + cfg.xtype)
29798         
29799         if (!cfg.xtype.match(/Panel$/)) {
29800             return false;
29801         }
29802         var ret = false;
29803         
29804         if (typeof(cfg.region) == 'undefined') {
29805             Roo.log("Failed to add Panel, region was not set");
29806             Roo.log(cfg);
29807             return false;
29808         }
29809         var region = cfg.region;
29810         delete cfg.region;
29811         
29812           
29813         var xitems = [];
29814         if (cfg.items) {
29815             xitems = cfg.items;
29816             delete cfg.items;
29817         }
29818         var nb = false;
29819         
29820         switch(cfg.xtype) 
29821         {
29822             case 'ContentPanel':  // ContentPanel (el, cfg)
29823             case 'ScrollPanel':  // ContentPanel (el, cfg)
29824             case 'ViewPanel': 
29825                 if(cfg.autoCreate) {
29826                     ret = new Roo[cfg.xtype](cfg); // new panel!!!!!
29827                 } else {
29828                     var el = this.el.createChild();
29829                     ret = new Roo[cfg.xtype](el, cfg); // new panel!!!!!
29830                 }
29831                 
29832                 this.add(region, ret);
29833                 break;
29834             
29835             
29836             case 'TreePanel': // our new panel!
29837                 cfg.el = this.el.createChild();
29838                 ret = new Roo[cfg.xtype](cfg); // new panel!!!!!
29839                 this.add(region, ret);
29840                 break;
29841             
29842             case 'NestedLayoutPanel': 
29843                 // create a new Layout (which is  a Border Layout...
29844                 var el = this.el.createChild();
29845                 var clayout = cfg.layout;
29846                 delete cfg.layout;
29847                 clayout.items   = clayout.items  || [];
29848                 // replace this exitems with the clayout ones..
29849                 xitems = clayout.items;
29850                  
29851                 
29852                 if (region == 'center' && this.active && this.getRegion('center').panels.length < 1) {
29853                     cfg.background = false;
29854                 }
29855                 var layout = new Roo.BorderLayout(el, clayout);
29856                 
29857                 ret = new Roo[cfg.xtype](layout, cfg); // new panel!!!!!
29858                 //console.log('adding nested layout panel '  + cfg.toSource());
29859                 this.add(region, ret);
29860                 nb = {}; /// find first...
29861                 break;
29862                 
29863             case 'GridPanel': 
29864             
29865                 // needs grid and region
29866                 
29867                 //var el = this.getRegion(region).el.createChild();
29868                 var el = this.el.createChild();
29869                 // create the grid first...
29870                 
29871                 var grid = new Roo.grid[cfg.grid.xtype](el, cfg.grid);
29872                 delete cfg.grid;
29873                 if (region == 'center' && this.active ) {
29874                     cfg.background = false;
29875                 }
29876                 ret = new Roo[cfg.xtype](grid, cfg); // new panel!!!!!
29877                 
29878                 this.add(region, ret);
29879                 if (cfg.background) {
29880                     ret.on('activate', function(gp) {
29881                         if (!gp.grid.rendered) {
29882                             gp.grid.render();
29883                         }
29884                     });
29885                 } else {
29886                     grid.render();
29887                 }
29888                 break;
29889            
29890            
29891            
29892                 
29893                 
29894                 
29895             default:
29896                 if (typeof(Roo[cfg.xtype]) != 'undefined') {
29897                     
29898                     ret = new Roo[cfg.xtype](cfg); // new panel!!!!!
29899                     this.add(region, ret);
29900                 } else {
29901                 
29902                     alert("Can not add '" + cfg.xtype + "' to BorderLayout");
29903                     return null;
29904                 }
29905                 
29906              // GridPanel (grid, cfg)
29907             
29908         }
29909         this.beginUpdate();
29910         // add children..
29911         var region = '';
29912         var abn = {};
29913         Roo.each(xitems, function(i)  {
29914             region = nb && i.region ? i.region : false;
29915             
29916             var add = ret.addxtype(i);
29917            
29918             if (region) {
29919                 nb[region] = nb[region] == undefined ? 0 : nb[region]+1;
29920                 if (!i.background) {
29921                     abn[region] = nb[region] ;
29922                 }
29923             }
29924             
29925         });
29926         this.endUpdate();
29927
29928         // make the last non-background panel active..
29929         //if (nb) { Roo.log(abn); }
29930         if (nb) {
29931             
29932             for(var r in abn) {
29933                 region = this.getRegion(r);
29934                 if (region) {
29935                     // tried using nb[r], but it does not work..
29936                      
29937                     region.showPanel(abn[r]);
29938                    
29939                 }
29940             }
29941         }
29942         return ret;
29943         
29944     }
29945 });
29946
29947 /**
29948  * Shortcut for creating a new BorderLayout object and adding one or more ContentPanels to it in a single step, handling
29949  * the beginUpdate and endUpdate calls internally.  The key to this method is the <b>panels</b> property that can be
29950  * provided with each region config, which allows you to add ContentPanel configs in addition to the region configs
29951  * during creation.  The following code is equivalent to the constructor-based example at the beginning of this class:
29952  * <pre><code>
29953 // shorthand
29954 var CP = Roo.ContentPanel;
29955
29956 var layout = Roo.BorderLayout.create({
29957     north: {
29958         initialSize: 25,
29959         titlebar: false,
29960         panels: [new CP("north", "North")]
29961     },
29962     west: {
29963         split:true,
29964         initialSize: 200,
29965         minSize: 175,
29966         maxSize: 400,
29967         titlebar: true,
29968         collapsible: true,
29969         panels: [new CP("west", {title: "West"})]
29970     },
29971     east: {
29972         split:true,
29973         initialSize: 202,
29974         minSize: 175,
29975         maxSize: 400,
29976         titlebar: true,
29977         collapsible: true,
29978         panels: [new CP("autoTabs", {title: "Auto Tabs", closable: true})]
29979     },
29980     south: {
29981         split:true,
29982         initialSize: 100,
29983         minSize: 100,
29984         maxSize: 200,
29985         titlebar: true,
29986         collapsible: true,
29987         panels: [new CP("south", {title: "South", closable: true})]
29988     },
29989     center: {
29990         titlebar: true,
29991         autoScroll:true,
29992         resizeTabs: true,
29993         minTabWidth: 50,
29994         preferredTabWidth: 150,
29995         panels: [
29996             new CP("center1", {title: "Close Me", closable: true}),
29997             new CP("center2", {title: "Center Panel", closable: false})
29998         ]
29999     }
30000 }, document.body);
30001
30002 layout.getRegion("center").showPanel("center1");
30003 </code></pre>
30004  * @param config
30005  * @param targetEl
30006  */
30007 Roo.BorderLayout.create = function(config, targetEl){
30008     var layout = new Roo.BorderLayout(targetEl || document.body, config);
30009     layout.beginUpdate();
30010     var regions = Roo.BorderLayout.RegionFactory.validRegions;
30011     for(var j = 0, jlen = regions.length; j < jlen; j++){
30012         var lr = regions[j];
30013         if(layout.regions[lr] && config[lr].panels){
30014             var r = layout.regions[lr];
30015             var ps = config[lr].panels;
30016             layout.addTypedPanels(r, ps);
30017         }
30018     }
30019     layout.endUpdate();
30020     return layout;
30021 };
30022
30023 // private
30024 Roo.BorderLayout.RegionFactory = {
30025     // private
30026     validRegions : ["north","south","east","west","center"],
30027
30028     // private
30029     create : function(target, mgr, config){
30030         target = target.toLowerCase();
30031         if(config.lightweight || config.basic){
30032             return new Roo.BasicLayoutRegion(mgr, config, target);
30033         }
30034         switch(target){
30035             case "north":
30036                 return new Roo.NorthLayoutRegion(mgr, config);
30037             case "south":
30038                 return new Roo.SouthLayoutRegion(mgr, config);
30039             case "east":
30040                 return new Roo.EastLayoutRegion(mgr, config);
30041             case "west":
30042                 return new Roo.WestLayoutRegion(mgr, config);
30043             case "center":
30044                 return new Roo.CenterLayoutRegion(mgr, config);
30045         }
30046         throw 'Layout region "'+target+'" not supported.';
30047     }
30048 };/*
30049  * Based on:
30050  * Ext JS Library 1.1.1
30051  * Copyright(c) 2006-2007, Ext JS, LLC.
30052  *
30053  * Originally Released Under LGPL - original licence link has changed is not relivant.
30054  *
30055  * Fork - LGPL
30056  * <script type="text/javascript">
30057  */
30058  
30059 /**
30060  * @class Roo.BasicLayoutRegion
30061  * @extends Roo.util.Observable
30062  * This class represents a lightweight region in a layout manager. This region does not move dom nodes
30063  * and does not have a titlebar, tabs or any other features. All it does is size and position 
30064  * panels. To create a BasicLayoutRegion, add lightweight:true or basic:true to your regions config.
30065  */
30066 Roo.BasicLayoutRegion = function(mgr, config, pos, skipConfig){
30067     this.mgr = mgr;
30068     this.position  = pos;
30069     this.events = {
30070         /**
30071          * @scope Roo.BasicLayoutRegion
30072          */
30073         
30074         /**
30075          * @event beforeremove
30076          * Fires before a panel is removed (or closed). To cancel the removal set "e.cancel = true" on the event argument.
30077          * @param {Roo.LayoutRegion} this
30078          * @param {Roo.ContentPanel} panel The panel
30079          * @param {Object} e The cancel event object
30080          */
30081         "beforeremove" : true,
30082         /**
30083          * @event invalidated
30084          * Fires when the layout for this region is changed.
30085          * @param {Roo.LayoutRegion} this
30086          */
30087         "invalidated" : true,
30088         /**
30089          * @event visibilitychange
30090          * Fires when this region is shown or hidden 
30091          * @param {Roo.LayoutRegion} this
30092          * @param {Boolean} visibility true or false
30093          */
30094         "visibilitychange" : true,
30095         /**
30096          * @event paneladded
30097          * Fires when a panel is added. 
30098          * @param {Roo.LayoutRegion} this
30099          * @param {Roo.ContentPanel} panel The panel
30100          */
30101         "paneladded" : true,
30102         /**
30103          * @event panelremoved
30104          * Fires when a panel is removed. 
30105          * @param {Roo.LayoutRegion} this
30106          * @param {Roo.ContentPanel} panel The panel
30107          */
30108         "panelremoved" : true,
30109         /**
30110          * @event beforecollapse
30111          * Fires when this region before collapse.
30112          * @param {Roo.LayoutRegion} this
30113          */
30114         "beforecollapse" : true,
30115         /**
30116          * @event collapsed
30117          * Fires when this region is collapsed.
30118          * @param {Roo.LayoutRegion} this
30119          */
30120         "collapsed" : true,
30121         /**
30122          * @event expanded
30123          * Fires when this region is expanded.
30124          * @param {Roo.LayoutRegion} this
30125          */
30126         "expanded" : true,
30127         /**
30128          * @event slideshow
30129          * Fires when this region is slid into view.
30130          * @param {Roo.LayoutRegion} this
30131          */
30132         "slideshow" : true,
30133         /**
30134          * @event slidehide
30135          * Fires when this region slides out of view. 
30136          * @param {Roo.LayoutRegion} this
30137          */
30138         "slidehide" : true,
30139         /**
30140          * @event panelactivated
30141          * Fires when a panel is activated. 
30142          * @param {Roo.LayoutRegion} this
30143          * @param {Roo.ContentPanel} panel The activated panel
30144          */
30145         "panelactivated" : true,
30146         /**
30147          * @event resized
30148          * Fires when the user resizes this region. 
30149          * @param {Roo.LayoutRegion} this
30150          * @param {Number} newSize The new size (width for east/west, height for north/south)
30151          */
30152         "resized" : true
30153     };
30154     /** A collection of panels in this region. @type Roo.util.MixedCollection */
30155     this.panels = new Roo.util.MixedCollection();
30156     this.panels.getKey = this.getPanelId.createDelegate(this);
30157     this.box = null;
30158     this.activePanel = null;
30159     // ensure listeners are added...
30160     
30161     if (config.listeners || config.events) {
30162         Roo.BasicLayoutRegion.superclass.constructor.call(this, {
30163             listeners : config.listeners || {},
30164             events : config.events || {}
30165         });
30166     }
30167     
30168     if(skipConfig !== true){
30169         this.applyConfig(config);
30170     }
30171 };
30172
30173 Roo.extend(Roo.BasicLayoutRegion, Roo.util.Observable, {
30174     getPanelId : function(p){
30175         return p.getId();
30176     },
30177     
30178     applyConfig : function(config){
30179         this.margins = config.margins || this.margins || {top: 0, left: 0, right:0, bottom: 0};
30180         this.config = config;
30181         
30182     },
30183     
30184     /**
30185      * Resizes the region to the specified size. For vertical regions (west, east) this adjusts 
30186      * the width, for horizontal (north, south) the height.
30187      * @param {Number} newSize The new width or height
30188      */
30189     resizeTo : function(newSize){
30190         var el = this.el ? this.el :
30191                  (this.activePanel ? this.activePanel.getEl() : null);
30192         if(el){
30193             switch(this.position){
30194                 case "east":
30195                 case "west":
30196                     el.setWidth(newSize);
30197                     this.fireEvent("resized", this, newSize);
30198                 break;
30199                 case "north":
30200                 case "south":
30201                     el.setHeight(newSize);
30202                     this.fireEvent("resized", this, newSize);
30203                 break;                
30204             }
30205         }
30206     },
30207     
30208     getBox : function(){
30209         return this.activePanel ? this.activePanel.getEl().getBox(false, true) : null;
30210     },
30211     
30212     getMargins : function(){
30213         return this.margins;
30214     },
30215     
30216     updateBox : function(box){
30217         this.box = box;
30218         var el = this.activePanel.getEl();
30219         el.dom.style.left = box.x + "px";
30220         el.dom.style.top = box.y + "px";
30221         this.activePanel.setSize(box.width, box.height);
30222     },
30223     
30224     /**
30225      * Returns the container element for this region.
30226      * @return {Roo.Element}
30227      */
30228     getEl : function(){
30229         return this.activePanel;
30230     },
30231     
30232     /**
30233      * Returns true if this region is currently visible.
30234      * @return {Boolean}
30235      */
30236     isVisible : function(){
30237         return this.activePanel ? true : false;
30238     },
30239     
30240     setActivePanel : function(panel){
30241         panel = this.getPanel(panel);
30242         if(this.activePanel && this.activePanel != panel){
30243             this.activePanel.setActiveState(false);
30244             this.activePanel.getEl().setLeftTop(-10000,-10000);
30245         }
30246         this.activePanel = panel;
30247         panel.setActiveState(true);
30248         if(this.box){
30249             panel.setSize(this.box.width, this.box.height);
30250         }
30251         this.fireEvent("panelactivated", this, panel);
30252         this.fireEvent("invalidated");
30253     },
30254     
30255     /**
30256      * Show the specified panel.
30257      * @param {Number/String/ContentPanel} panelId The panels index, id or the panel itself
30258      * @return {Roo.ContentPanel} The shown panel or null
30259      */
30260     showPanel : function(panel){
30261         if(panel = this.getPanel(panel)){
30262             this.setActivePanel(panel);
30263         }
30264         return panel;
30265     },
30266     
30267     /**
30268      * Get the active panel for this region.
30269      * @return {Roo.ContentPanel} The active panel or null
30270      */
30271     getActivePanel : function(){
30272         return this.activePanel;
30273     },
30274     
30275     /**
30276      * Add the passed ContentPanel(s)
30277      * @param {ContentPanel...} panel The ContentPanel(s) to add (you can pass more than one)
30278      * @return {Roo.ContentPanel} The panel added (if only one was added)
30279      */
30280     add : function(panel){
30281         if(arguments.length > 1){
30282             for(var i = 0, len = arguments.length; i < len; i++) {
30283                 this.add(arguments[i]);
30284             }
30285             return null;
30286         }
30287         if(this.hasPanel(panel)){
30288             this.showPanel(panel);
30289             return panel;
30290         }
30291         var el = panel.getEl();
30292         if(el.dom.parentNode != this.mgr.el.dom){
30293             this.mgr.el.dom.appendChild(el.dom);
30294         }
30295         if(panel.setRegion){
30296             panel.setRegion(this);
30297         }
30298         this.panels.add(panel);
30299         el.setStyle("position", "absolute");
30300         if(!panel.background){
30301             this.setActivePanel(panel);
30302             if(this.config.initialSize && this.panels.getCount()==1){
30303                 this.resizeTo(this.config.initialSize);
30304             }
30305         }
30306         this.fireEvent("paneladded", this, panel);
30307         return panel;
30308     },
30309     
30310     /**
30311      * Returns true if the panel is in this region.
30312      * @param {Number/String/ContentPanel} panel The panels index, id or the panel itself
30313      * @return {Boolean}
30314      */
30315     hasPanel : function(panel){
30316         if(typeof panel == "object"){ // must be panel obj
30317             panel = panel.getId();
30318         }
30319         return this.getPanel(panel) ? true : false;
30320     },
30321     
30322     /**
30323      * Removes the specified panel. If preservePanel is not true (either here or in the config), the panel is destroyed.
30324      * @param {Number/String/ContentPanel} panel The panels index, id or the panel itself
30325      * @param {Boolean} preservePanel Overrides the config preservePanel option
30326      * @return {Roo.ContentPanel} The panel that was removed
30327      */
30328     remove : function(panel, preservePanel){
30329         panel = this.getPanel(panel);
30330         if(!panel){
30331             return null;
30332         }
30333         var e = {};
30334         this.fireEvent("beforeremove", this, panel, e);
30335         if(e.cancel === true){
30336             return null;
30337         }
30338         var panelId = panel.getId();
30339         this.panels.removeKey(panelId);
30340         return panel;
30341     },
30342     
30343     /**
30344      * Returns the panel specified or null if it's not in this region.
30345      * @param {Number/String/ContentPanel} panel The panels index, id or the panel itself
30346      * @return {Roo.ContentPanel}
30347      */
30348     getPanel : function(id){
30349         if(typeof id == "object"){ // must be panel obj
30350             return id;
30351         }
30352         return this.panels.get(id);
30353     },
30354     
30355     /**
30356      * Returns this regions position (north/south/east/west/center).
30357      * @return {String} 
30358      */
30359     getPosition: function(){
30360         return this.position;    
30361     }
30362 });/*
30363  * Based on:
30364  * Ext JS Library 1.1.1
30365  * Copyright(c) 2006-2007, Ext JS, LLC.
30366  *
30367  * Originally Released Under LGPL - original licence link has changed is not relivant.
30368  *
30369  * Fork - LGPL
30370  * <script type="text/javascript">
30371  */
30372  
30373 /**
30374  * @class Roo.LayoutRegion
30375  * @extends Roo.BasicLayoutRegion
30376  * This class represents a region in a layout manager.
30377  * @cfg {Boolean}   collapsible     False to disable collapsing (defaults to true)
30378  * @cfg {Boolean}   collapsed       True to set the initial display to collapsed (defaults to false)
30379  * @cfg {Boolean}   floatable       False to disable floating (defaults to true)
30380  * @cfg {Object}    margins         Margins for the element (defaults to {top: 0, left: 0, right:0, bottom: 0})
30381  * @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})
30382  * @cfg {String}    tabPosition     (top|bottom) "top" or "bottom" (defaults to "bottom")
30383  * @cfg {String}    collapsedTitle  Optional string message to display in the collapsed block of a north or south region
30384  * @cfg {Boolean}   alwaysShowTabs  True to always display tabs even when there is only 1 panel (defaults to false)
30385  * @cfg {Boolean}   autoScroll      True to enable overflow scrolling (defaults to false)
30386  * @cfg {Boolean}   titlebar        True to display a title bar (defaults to true)
30387  * @cfg {String}    title           The title for the region (overrides panel titles)
30388  * @cfg {Boolean}   animate         True to animate expand/collapse (defaults to false)
30389  * @cfg {Boolean}   autoHide        False to disable auto hiding when the mouse leaves the "floated" region (defaults to true)
30390  * @cfg {Boolean}   preservePanels  True to preserve removed panels so they can be readded later (defaults to false)
30391  * @cfg {Boolean}   closeOnTab      True to place the close icon on the tabs instead of the region titlebar (defaults to false)
30392  * @cfg {Boolean}   hideTabs        True to hide the tab strip (defaults to false)
30393  * @cfg {Boolean}   resizeTabs      True to enable automatic tab resizing. This will resize the tabs so they are all the same size and fit within
30394  *                      the space available, similar to FireFox 1.5 tabs (defaults to false)
30395  * @cfg {Number}    minTabWidth     The minimum tab width (defaults to 40)
30396  * @cfg {Number}    preferredTabWidth The preferred tab width (defaults to 150)
30397  * @cfg {Boolean}   showPin         True to show a pin button
30398  * @cfg {Boolean}   hidden          True to start the region hidden (defaults to false)
30399  * @cfg {Boolean}   hideWhenEmpty   True to hide the region when it has no panels
30400  * @cfg {Boolean}   disableTabTips  True to disable tab tooltips
30401  * @cfg {Number}    width           For East/West panels
30402  * @cfg {Number}    height          For North/South panels
30403  * @cfg {Boolean}   split           To show the splitter
30404  * @cfg {Boolean}   toolbar         xtype configuration for a toolbar - shows on right of tabbar
30405  */
30406 Roo.LayoutRegion = function(mgr, config, pos){
30407     Roo.LayoutRegion.superclass.constructor.call(this, mgr, config, pos, true);
30408     var dh = Roo.DomHelper;
30409     /** This region's container element 
30410     * @type Roo.Element */
30411     this.el = dh.append(mgr.el.dom, {tag: "div", cls: "x-layout-panel x-layout-panel-" + this.position}, true);
30412     /** This region's title element 
30413     * @type Roo.Element */
30414
30415     this.titleEl = dh.append(this.el.dom, {tag: "div", unselectable: "on", cls: "x-unselectable x-layout-panel-hd x-layout-title-"+this.position, children:[
30416         {tag: "span", cls: "x-unselectable x-layout-panel-hd-text", unselectable: "on", html: "&#160;"},
30417         {tag: "div", cls: "x-unselectable x-layout-panel-hd-tools", unselectable: "on"}
30418     ]}, true);
30419     this.titleEl.enableDisplayMode();
30420     /** This region's title text element 
30421     * @type HTMLElement */
30422     this.titleTextEl = this.titleEl.dom.firstChild;
30423     this.tools = Roo.get(this.titleEl.dom.childNodes[1], true);
30424     this.closeBtn = this.createTool(this.tools.dom, "x-layout-close");
30425     this.closeBtn.enableDisplayMode();
30426     this.closeBtn.on("click", this.closeClicked, this);
30427     this.closeBtn.hide();
30428
30429     this.createBody(config);
30430     this.visible = true;
30431     this.collapsed = false;
30432
30433     if(config.hideWhenEmpty){
30434         this.hide();
30435         this.on("paneladded", this.validateVisibility, this);
30436         this.on("panelremoved", this.validateVisibility, this);
30437     }
30438     this.applyConfig(config);
30439 };
30440
30441 Roo.extend(Roo.LayoutRegion, Roo.BasicLayoutRegion, {
30442
30443     createBody : function(){
30444         /** This region's body element 
30445         * @type Roo.Element */
30446         this.bodyEl = this.el.createChild({tag: "div", cls: "x-layout-panel-body"});
30447     },
30448
30449     applyConfig : function(c){
30450         if(c.collapsible && this.position != "center" && !this.collapsedEl){
30451             var dh = Roo.DomHelper;
30452             if(c.titlebar !== false){
30453                 this.collapseBtn = this.createTool(this.tools.dom, "x-layout-collapse-"+this.position);
30454                 this.collapseBtn.on("click", this.collapse, this);
30455                 this.collapseBtn.enableDisplayMode();
30456
30457                 if(c.showPin === true || this.showPin){
30458                     this.stickBtn = this.createTool(this.tools.dom, "x-layout-stick");
30459                     this.stickBtn.enableDisplayMode();
30460                     this.stickBtn.on("click", this.expand, this);
30461                     this.stickBtn.hide();
30462                 }
30463             }
30464             /** This region's collapsed element
30465             * @type Roo.Element */
30466             this.collapsedEl = dh.append(this.mgr.el.dom, {cls: "x-layout-collapsed x-layout-collapsed-"+this.position, children:[
30467                 {cls: "x-layout-collapsed-tools", children:[{cls: "x-layout-ctools-inner"}]}
30468             ]}, true);
30469             if(c.floatable !== false){
30470                this.collapsedEl.addClassOnOver("x-layout-collapsed-over");
30471                this.collapsedEl.on("click", this.collapseClick, this);
30472             }
30473
30474             if(c.collapsedTitle && (this.position == "north" || this.position== "south")) {
30475                 this.collapsedTitleTextEl = dh.append(this.collapsedEl.dom, {tag: "div", cls: "x-unselectable x-layout-panel-hd-text",
30476                    id: "message", unselectable: "on", style:{"float":"left"}});
30477                this.collapsedTitleTextEl.innerHTML = c.collapsedTitle;
30478              }
30479             this.expandBtn = this.createTool(this.collapsedEl.dom.firstChild.firstChild, "x-layout-expand-"+this.position);
30480             this.expandBtn.on("click", this.expand, this);
30481         }
30482         if(this.collapseBtn){
30483             this.collapseBtn.setVisible(c.collapsible == true);
30484         }
30485         this.cmargins = c.cmargins || this.cmargins ||
30486                          (this.position == "west" || this.position == "east" ?
30487                              {top: 0, left: 2, right:2, bottom: 0} :
30488                              {top: 2, left: 0, right:0, bottom: 2});
30489         this.margins = c.margins || this.margins || {top: 0, left: 0, right:0, bottom: 0};
30490         this.bottomTabs = c.tabPosition != "top";
30491         this.autoScroll = c.autoScroll || false;
30492         if(this.autoScroll){
30493             this.bodyEl.setStyle("overflow", "auto");
30494         }else{
30495             this.bodyEl.setStyle("overflow", "hidden");
30496         }
30497         //if(c.titlebar !== false){
30498             if((!c.titlebar && !c.title) || c.titlebar === false){
30499                 this.titleEl.hide();
30500             }else{
30501                 this.titleEl.show();
30502                 if(c.title){
30503                     this.titleTextEl.innerHTML = c.title;
30504                 }
30505             }
30506         //}
30507         this.duration = c.duration || .30;
30508         this.slideDuration = c.slideDuration || .45;
30509         this.config = c;
30510         if(c.collapsed){
30511             this.collapse(true);
30512         }
30513         if(c.hidden){
30514             this.hide();
30515         }
30516     },
30517     /**
30518      * Returns true if this region is currently visible.
30519      * @return {Boolean}
30520      */
30521     isVisible : function(){
30522         return this.visible;
30523     },
30524
30525     /**
30526      * Updates the title for collapsed north/south regions (used with {@link #collapsedTitle} config option)
30527      * @param {String} title (optional) The title text (accepts HTML markup, defaults to the numeric character reference for a non-breaking space, "&amp;#160;")
30528      */
30529     setCollapsedTitle : function(title){
30530         title = title || "&#160;";
30531         if(this.collapsedTitleTextEl){
30532             this.collapsedTitleTextEl.innerHTML = title;
30533         }
30534     },
30535
30536     getBox : function(){
30537         var b;
30538         if(!this.collapsed){
30539             b = this.el.getBox(false, true);
30540         }else{
30541             b = this.collapsedEl.getBox(false, true);
30542         }
30543         return b;
30544     },
30545
30546     getMargins : function(){
30547         return this.collapsed ? this.cmargins : this.margins;
30548     },
30549
30550     highlight : function(){
30551         this.el.addClass("x-layout-panel-dragover");
30552     },
30553
30554     unhighlight : function(){
30555         this.el.removeClass("x-layout-panel-dragover");
30556     },
30557
30558     updateBox : function(box){
30559         this.box = box;
30560         if(!this.collapsed){
30561             this.el.dom.style.left = box.x + "px";
30562             this.el.dom.style.top = box.y + "px";
30563             this.updateBody(box.width, box.height);
30564         }else{
30565             this.collapsedEl.dom.style.left = box.x + "px";
30566             this.collapsedEl.dom.style.top = box.y + "px";
30567             this.collapsedEl.setSize(box.width, box.height);
30568         }
30569         if(this.tabs){
30570             this.tabs.autoSizeTabs();
30571         }
30572     },
30573
30574     updateBody : function(w, h){
30575         if(w !== null){
30576             this.el.setWidth(w);
30577             w -= this.el.getBorderWidth("rl");
30578             if(this.config.adjustments){
30579                 w += this.config.adjustments[0];
30580             }
30581         }
30582         if(h !== null){
30583             this.el.setHeight(h);
30584             h = this.titleEl && this.titleEl.isDisplayed() ? h - (this.titleEl.getHeight()||0) : h;
30585             h -= this.el.getBorderWidth("tb");
30586             if(this.config.adjustments){
30587                 h += this.config.adjustments[1];
30588             }
30589             this.bodyEl.setHeight(h);
30590             if(this.tabs){
30591                 h = this.tabs.syncHeight(h);
30592             }
30593         }
30594         if(this.panelSize){
30595             w = w !== null ? w : this.panelSize.width;
30596             h = h !== null ? h : this.panelSize.height;
30597         }
30598         if(this.activePanel){
30599             var el = this.activePanel.getEl();
30600             w = w !== null ? w : el.getWidth();
30601             h = h !== null ? h : el.getHeight();
30602             this.panelSize = {width: w, height: h};
30603             this.activePanel.setSize(w, h);
30604         }
30605         if(Roo.isIE && this.tabs){
30606             this.tabs.el.repaint();
30607         }
30608     },
30609
30610     /**
30611      * Returns the container element for this region.
30612      * @return {Roo.Element}
30613      */
30614     getEl : function(){
30615         return this.el;
30616     },
30617
30618     /**
30619      * Hides this region.
30620      */
30621     hide : function(){
30622         if(!this.collapsed){
30623             this.el.dom.style.left = "-2000px";
30624             this.el.hide();
30625         }else{
30626             this.collapsedEl.dom.style.left = "-2000px";
30627             this.collapsedEl.hide();
30628         }
30629         this.visible = false;
30630         this.fireEvent("visibilitychange", this, false);
30631     },
30632
30633     /**
30634      * Shows this region if it was previously hidden.
30635      */
30636     show : function(){
30637         if(!this.collapsed){
30638             this.el.show();
30639         }else{
30640             this.collapsedEl.show();
30641         }
30642         this.visible = true;
30643         this.fireEvent("visibilitychange", this, true);
30644     },
30645
30646     closeClicked : function(){
30647         if(this.activePanel){
30648             this.remove(this.activePanel);
30649         }
30650     },
30651
30652     collapseClick : function(e){
30653         if(this.isSlid){
30654            e.stopPropagation();
30655            this.slideIn();
30656         }else{
30657            e.stopPropagation();
30658            this.slideOut();
30659         }
30660     },
30661
30662     /**
30663      * Collapses this region.
30664      * @param {Boolean} skipAnim (optional) true to collapse the element without animation (if animate is true)
30665      */
30666     collapse : function(skipAnim, skipCheck){
30667         if(this.collapsed) {
30668             return;
30669         }
30670         
30671         if(skipCheck || this.fireEvent("beforecollapse", this) != false){
30672             
30673             this.collapsed = true;
30674             if(this.split){
30675                 this.split.el.hide();
30676             }
30677             if(this.config.animate && skipAnim !== true){
30678                 this.fireEvent("invalidated", this);
30679                 this.animateCollapse();
30680             }else{
30681                 this.el.setLocation(-20000,-20000);
30682                 this.el.hide();
30683                 this.collapsedEl.show();
30684                 this.fireEvent("collapsed", this);
30685                 this.fireEvent("invalidated", this);
30686             }
30687         }
30688         
30689     },
30690
30691     animateCollapse : function(){
30692         // overridden
30693     },
30694
30695     /**
30696      * Expands this region if it was previously collapsed.
30697      * @param {Roo.EventObject} e The event that triggered the expand (or null if calling manually)
30698      * @param {Boolean} skipAnim (optional) true to expand the element without animation (if animate is true)
30699      */
30700     expand : function(e, skipAnim){
30701         if(e) {
30702             e.stopPropagation();
30703         }
30704         if(!this.collapsed || this.el.hasActiveFx()) {
30705             return;
30706         }
30707         if(this.isSlid){
30708             this.afterSlideIn();
30709             skipAnim = true;
30710         }
30711         this.collapsed = false;
30712         if(this.config.animate && skipAnim !== true){
30713             this.animateExpand();
30714         }else{
30715             this.el.show();
30716             if(this.split){
30717                 this.split.el.show();
30718             }
30719             this.collapsedEl.setLocation(-2000,-2000);
30720             this.collapsedEl.hide();
30721             this.fireEvent("invalidated", this);
30722             this.fireEvent("expanded", this);
30723         }
30724     },
30725
30726     animateExpand : function(){
30727         // overridden
30728     },
30729
30730     initTabs : function()
30731     {
30732         this.bodyEl.setStyle("overflow", "hidden");
30733         var ts = new Roo.TabPanel(
30734                 this.bodyEl.dom,
30735                 {
30736                     tabPosition: this.bottomTabs ? 'bottom' : 'top',
30737                     disableTooltips: this.config.disableTabTips,
30738                     toolbar : this.config.toolbar
30739                 }
30740         );
30741         if(this.config.hideTabs){
30742             ts.stripWrap.setDisplayed(false);
30743         }
30744         this.tabs = ts;
30745         ts.resizeTabs = this.config.resizeTabs === true;
30746         ts.minTabWidth = this.config.minTabWidth || 40;
30747         ts.maxTabWidth = this.config.maxTabWidth || 250;
30748         ts.preferredTabWidth = this.config.preferredTabWidth || 150;
30749         ts.monitorResize = false;
30750         ts.bodyEl.setStyle("overflow", this.config.autoScroll ? "auto" : "hidden");
30751         ts.bodyEl.addClass('x-layout-tabs-body');
30752         this.panels.each(this.initPanelAsTab, this);
30753     },
30754
30755     initPanelAsTab : function(panel){
30756         var ti = this.tabs.addTab(panel.getEl().id, panel.getTitle(), null,
30757                     this.config.closeOnTab && panel.isClosable());
30758         if(panel.tabTip !== undefined){
30759             ti.setTooltip(panel.tabTip);
30760         }
30761         ti.on("activate", function(){
30762               this.setActivePanel(panel);
30763         }, this);
30764         if(this.config.closeOnTab){
30765             ti.on("beforeclose", function(t, e){
30766                 e.cancel = true;
30767                 this.remove(panel);
30768             }, this);
30769         }
30770         return ti;
30771     },
30772
30773     updatePanelTitle : function(panel, title){
30774         if(this.activePanel == panel){
30775             this.updateTitle(title);
30776         }
30777         if(this.tabs){
30778             var ti = this.tabs.getTab(panel.getEl().id);
30779             ti.setText(title);
30780             if(panel.tabTip !== undefined){
30781                 ti.setTooltip(panel.tabTip);
30782             }
30783         }
30784     },
30785
30786     updateTitle : function(title){
30787         if(this.titleTextEl && !this.config.title){
30788             this.titleTextEl.innerHTML = (typeof title != "undefined" && title.length > 0 ? title : "&#160;");
30789         }
30790     },
30791
30792     setActivePanel : function(panel){
30793         panel = this.getPanel(panel);
30794         if(this.activePanel && this.activePanel != panel){
30795             this.activePanel.setActiveState(false);
30796         }
30797         this.activePanel = panel;
30798         panel.setActiveState(true);
30799         if(this.panelSize){
30800             panel.setSize(this.panelSize.width, this.panelSize.height);
30801         }
30802         if(this.closeBtn){
30803             this.closeBtn.setVisible(!this.config.closeOnTab && !this.isSlid && panel.isClosable());
30804         }
30805         this.updateTitle(panel.getTitle());
30806         if(this.tabs){
30807             this.fireEvent("invalidated", this);
30808         }
30809         this.fireEvent("panelactivated", this, panel);
30810     },
30811
30812     /**
30813      * Shows the specified panel.
30814      * @param {Number/String/ContentPanel} panelId The panel's index, id or the panel itself
30815      * @return {Roo.ContentPanel} The shown panel, or null if a panel could not be found from panelId
30816      */
30817     showPanel : function(panel)
30818     {
30819         panel = this.getPanel(panel);
30820         if(panel){
30821             if(this.tabs){
30822                 var tab = this.tabs.getTab(panel.getEl().id);
30823                 if(tab.isHidden()){
30824                     this.tabs.unhideTab(tab.id);
30825                 }
30826                 tab.activate();
30827             }else{
30828                 this.setActivePanel(panel);
30829             }
30830         }
30831         return panel;
30832     },
30833
30834     /**
30835      * Get the active panel for this region.
30836      * @return {Roo.ContentPanel} The active panel or null
30837      */
30838     getActivePanel : function(){
30839         return this.activePanel;
30840     },
30841
30842     validateVisibility : function(){
30843         if(this.panels.getCount() < 1){
30844             this.updateTitle("&#160;");
30845             this.closeBtn.hide();
30846             this.hide();
30847         }else{
30848             if(!this.isVisible()){
30849                 this.show();
30850             }
30851         }
30852     },
30853
30854     /**
30855      * Adds the passed ContentPanel(s) to this region.
30856      * @param {ContentPanel...} panel The ContentPanel(s) to add (you can pass more than one)
30857      * @return {Roo.ContentPanel} The panel added (if only one was added; null otherwise)
30858      */
30859     add : function(panel){
30860         if(arguments.length > 1){
30861             for(var i = 0, len = arguments.length; i < len; i++) {
30862                 this.add(arguments[i]);
30863             }
30864             return null;
30865         }
30866         if(this.hasPanel(panel)){
30867             this.showPanel(panel);
30868             return panel;
30869         }
30870         panel.setRegion(this);
30871         this.panels.add(panel);
30872         if(this.panels.getCount() == 1 && !this.config.alwaysShowTabs){
30873             this.bodyEl.dom.appendChild(panel.getEl().dom);
30874             if(panel.background !== true){
30875                 this.setActivePanel(panel);
30876             }
30877             this.fireEvent("paneladded", this, panel);
30878             return panel;
30879         }
30880         if(!this.tabs){
30881             this.initTabs();
30882         }else{
30883             this.initPanelAsTab(panel);
30884         }
30885         if(panel.background !== true){
30886             this.tabs.activate(panel.getEl().id);
30887         }
30888         this.fireEvent("paneladded", this, panel);
30889         return panel;
30890     },
30891
30892     /**
30893      * Hides the tab for the specified panel.
30894      * @param {Number/String/ContentPanel} panel The panel's index, id or the panel itself
30895      */
30896     hidePanel : function(panel){
30897         if(this.tabs && (panel = this.getPanel(panel))){
30898             this.tabs.hideTab(panel.getEl().id);
30899         }
30900     },
30901
30902     /**
30903      * Unhides the tab for a previously hidden panel.
30904      * @param {Number/String/ContentPanel} panel The panel's index, id or the panel itself
30905      */
30906     unhidePanel : function(panel){
30907         if(this.tabs && (panel = this.getPanel(panel))){
30908             this.tabs.unhideTab(panel.getEl().id);
30909         }
30910     },
30911
30912     clearPanels : function(){
30913         while(this.panels.getCount() > 0){
30914              this.remove(this.panels.first());
30915         }
30916     },
30917
30918     /**
30919      * Removes the specified panel. If preservePanel is not true (either here or in the config), the panel is destroyed.
30920      * @param {Number/String/ContentPanel} panel The panel's index, id or the panel itself
30921      * @param {Boolean} preservePanel Overrides the config preservePanel option
30922      * @return {Roo.ContentPanel} The panel that was removed
30923      */
30924     remove : function(panel, preservePanel){
30925         panel = this.getPanel(panel);
30926         if(!panel){
30927             return null;
30928         }
30929         var e = {};
30930         this.fireEvent("beforeremove", this, panel, e);
30931         if(e.cancel === true){
30932             return null;
30933         }
30934         preservePanel = (typeof preservePanel != "undefined" ? preservePanel : (this.config.preservePanels === true || panel.preserve === true));
30935         var panelId = panel.getId();
30936         this.panels.removeKey(panelId);
30937         if(preservePanel){
30938             document.body.appendChild(panel.getEl().dom);
30939         }
30940         if(this.tabs){
30941             this.tabs.removeTab(panel.getEl().id);
30942         }else if (!preservePanel){
30943             this.bodyEl.dom.removeChild(panel.getEl().dom);
30944         }
30945         if(this.panels.getCount() == 1 && this.tabs && !this.config.alwaysShowTabs){
30946             var p = this.panels.first();
30947             var tempEl = document.createElement("div"); // temp holder to keep IE from deleting the node
30948             tempEl.appendChild(p.getEl().dom);
30949             this.bodyEl.update("");
30950             this.bodyEl.dom.appendChild(p.getEl().dom);
30951             tempEl = null;
30952             this.updateTitle(p.getTitle());
30953             this.tabs = null;
30954             this.bodyEl.setStyle("overflow", this.config.autoScroll ? "auto" : "hidden");
30955             this.setActivePanel(p);
30956         }
30957         panel.setRegion(null);
30958         if(this.activePanel == panel){
30959             this.activePanel = null;
30960         }
30961         if(this.config.autoDestroy !== false && preservePanel !== true){
30962             try{panel.destroy();}catch(e){}
30963         }
30964         this.fireEvent("panelremoved", this, panel);
30965         return panel;
30966     },
30967
30968     /**
30969      * Returns the TabPanel component used by this region
30970      * @return {Roo.TabPanel}
30971      */
30972     getTabs : function(){
30973         return this.tabs;
30974     },
30975
30976     createTool : function(parentEl, className){
30977         var btn = Roo.DomHelper.append(parentEl, {tag: "div", cls: "x-layout-tools-button",
30978             children: [{tag: "div", cls: "x-layout-tools-button-inner " + className, html: "&#160;"}]}, true);
30979         btn.addClassOnOver("x-layout-tools-button-over");
30980         return btn;
30981     }
30982 });/*
30983  * Based on:
30984  * Ext JS Library 1.1.1
30985  * Copyright(c) 2006-2007, Ext JS, LLC.
30986  *
30987  * Originally Released Under LGPL - original licence link has changed is not relivant.
30988  *
30989  * Fork - LGPL
30990  * <script type="text/javascript">
30991  */
30992  
30993
30994
30995 /**
30996  * @class Roo.SplitLayoutRegion
30997  * @extends Roo.LayoutRegion
30998  * Adds a splitbar and other (private) useful functionality to a {@link Roo.LayoutRegion}.
30999  */
31000 Roo.SplitLayoutRegion = function(mgr, config, pos, cursor){
31001     this.cursor = cursor;
31002     Roo.SplitLayoutRegion.superclass.constructor.call(this, mgr, config, pos);
31003 };
31004
31005 Roo.extend(Roo.SplitLayoutRegion, Roo.LayoutRegion, {
31006     splitTip : "Drag to resize.",
31007     collapsibleSplitTip : "Drag to resize. Double click to hide.",
31008     useSplitTips : false,
31009
31010     applyConfig : function(config){
31011         Roo.SplitLayoutRegion.superclass.applyConfig.call(this, config);
31012         if(config.split){
31013             if(!this.split){
31014                 var splitEl = Roo.DomHelper.append(this.mgr.el.dom, 
31015                         {tag: "div", id: this.el.id + "-split", cls: "x-layout-split x-layout-split-"+this.position, html: "&#160;"});
31016                 /** The SplitBar for this region 
31017                 * @type Roo.SplitBar */
31018                 this.split = new Roo.SplitBar(splitEl, this.el, this.orientation);
31019                 this.split.on("moved", this.onSplitMove, this);
31020                 this.split.useShim = config.useShim === true;
31021                 this.split.getMaximumSize = this[this.position == 'north' || this.position == 'south' ? 'getVMaxSize' : 'getHMaxSize'].createDelegate(this);
31022                 if(this.useSplitTips){
31023                     this.split.el.dom.title = config.collapsible ? this.collapsibleSplitTip : this.splitTip;
31024                 }
31025                 if(config.collapsible){
31026                     this.split.el.on("dblclick", this.collapse,  this);
31027                 }
31028             }
31029             if(typeof config.minSize != "undefined"){
31030                 this.split.minSize = config.minSize;
31031             }
31032             if(typeof config.maxSize != "undefined"){
31033                 this.split.maxSize = config.maxSize;
31034             }
31035             if(config.hideWhenEmpty || config.hidden || config.collapsed){
31036                 this.hideSplitter();
31037             }
31038         }
31039     },
31040
31041     getHMaxSize : function(){
31042          var cmax = this.config.maxSize || 10000;
31043          var center = this.mgr.getRegion("center");
31044          return Math.min(cmax, (this.el.getWidth()+center.getEl().getWidth())-center.getMinWidth());
31045     },
31046
31047     getVMaxSize : function(){
31048          var cmax = this.config.maxSize || 10000;
31049          var center = this.mgr.getRegion("center");
31050          return Math.min(cmax, (this.el.getHeight()+center.getEl().getHeight())-center.getMinHeight());
31051     },
31052
31053     onSplitMove : function(split, newSize){
31054         this.fireEvent("resized", this, newSize);
31055     },
31056     
31057     /** 
31058      * Returns the {@link Roo.SplitBar} for this region.
31059      * @return {Roo.SplitBar}
31060      */
31061     getSplitBar : function(){
31062         return this.split;
31063     },
31064     
31065     hide : function(){
31066         this.hideSplitter();
31067         Roo.SplitLayoutRegion.superclass.hide.call(this);
31068     },
31069
31070     hideSplitter : function(){
31071         if(this.split){
31072             this.split.el.setLocation(-2000,-2000);
31073             this.split.el.hide();
31074         }
31075     },
31076
31077     show : function(){
31078         if(this.split){
31079             this.split.el.show();
31080         }
31081         Roo.SplitLayoutRegion.superclass.show.call(this);
31082     },
31083     
31084     beforeSlide: function(){
31085         if(Roo.isGecko){// firefox overflow auto bug workaround
31086             this.bodyEl.clip();
31087             if(this.tabs) {
31088                 this.tabs.bodyEl.clip();
31089             }
31090             if(this.activePanel){
31091                 this.activePanel.getEl().clip();
31092                 
31093                 if(this.activePanel.beforeSlide){
31094                     this.activePanel.beforeSlide();
31095                 }
31096             }
31097         }
31098     },
31099     
31100     afterSlide : function(){
31101         if(Roo.isGecko){// firefox overflow auto bug workaround
31102             this.bodyEl.unclip();
31103             if(this.tabs) {
31104                 this.tabs.bodyEl.unclip();
31105             }
31106             if(this.activePanel){
31107                 this.activePanel.getEl().unclip();
31108                 if(this.activePanel.afterSlide){
31109                     this.activePanel.afterSlide();
31110                 }
31111             }
31112         }
31113     },
31114
31115     initAutoHide : function(){
31116         if(this.autoHide !== false){
31117             if(!this.autoHideHd){
31118                 var st = new Roo.util.DelayedTask(this.slideIn, this);
31119                 this.autoHideHd = {
31120                     "mouseout": function(e){
31121                         if(!e.within(this.el, true)){
31122                             st.delay(500);
31123                         }
31124                     },
31125                     "mouseover" : function(e){
31126                         st.cancel();
31127                     },
31128                     scope : this
31129                 };
31130             }
31131             this.el.on(this.autoHideHd);
31132         }
31133     },
31134
31135     clearAutoHide : function(){
31136         if(this.autoHide !== false){
31137             this.el.un("mouseout", this.autoHideHd.mouseout);
31138             this.el.un("mouseover", this.autoHideHd.mouseover);
31139         }
31140     },
31141
31142     clearMonitor : function(){
31143         Roo.get(document).un("click", this.slideInIf, this);
31144     },
31145
31146     // these names are backwards but not changed for compat
31147     slideOut : function(){
31148         if(this.isSlid || this.el.hasActiveFx()){
31149             return;
31150         }
31151         this.isSlid = true;
31152         if(this.collapseBtn){
31153             this.collapseBtn.hide();
31154         }
31155         this.closeBtnState = this.closeBtn.getStyle('display');
31156         this.closeBtn.hide();
31157         if(this.stickBtn){
31158             this.stickBtn.show();
31159         }
31160         this.el.show();
31161         this.el.alignTo(this.collapsedEl, this.getCollapseAnchor());
31162         this.beforeSlide();
31163         this.el.setStyle("z-index", 10001);
31164         this.el.slideIn(this.getSlideAnchor(), {
31165             callback: function(){
31166                 this.afterSlide();
31167                 this.initAutoHide();
31168                 Roo.get(document).on("click", this.slideInIf, this);
31169                 this.fireEvent("slideshow", this);
31170             },
31171             scope: this,
31172             block: true
31173         });
31174     },
31175
31176     afterSlideIn : function(){
31177         this.clearAutoHide();
31178         this.isSlid = false;
31179         this.clearMonitor();
31180         this.el.setStyle("z-index", "");
31181         if(this.collapseBtn){
31182             this.collapseBtn.show();
31183         }
31184         this.closeBtn.setStyle('display', this.closeBtnState);
31185         if(this.stickBtn){
31186             this.stickBtn.hide();
31187         }
31188         this.fireEvent("slidehide", this);
31189     },
31190
31191     slideIn : function(cb){
31192         if(!this.isSlid || this.el.hasActiveFx()){
31193             Roo.callback(cb);
31194             return;
31195         }
31196         this.isSlid = false;
31197         this.beforeSlide();
31198         this.el.slideOut(this.getSlideAnchor(), {
31199             callback: function(){
31200                 this.el.setLeftTop(-10000, -10000);
31201                 this.afterSlide();
31202                 this.afterSlideIn();
31203                 Roo.callback(cb);
31204             },
31205             scope: this,
31206             block: true
31207         });
31208     },
31209     
31210     slideInIf : function(e){
31211         if(!e.within(this.el)){
31212             this.slideIn();
31213         }
31214     },
31215
31216     animateCollapse : function(){
31217         this.beforeSlide();
31218         this.el.setStyle("z-index", 20000);
31219         var anchor = this.getSlideAnchor();
31220         this.el.slideOut(anchor, {
31221             callback : function(){
31222                 this.el.setStyle("z-index", "");
31223                 this.collapsedEl.slideIn(anchor, {duration:.3});
31224                 this.afterSlide();
31225                 this.el.setLocation(-10000,-10000);
31226                 this.el.hide();
31227                 this.fireEvent("collapsed", this);
31228             },
31229             scope: this,
31230             block: true
31231         });
31232     },
31233
31234     animateExpand : function(){
31235         this.beforeSlide();
31236         this.el.alignTo(this.collapsedEl, this.getCollapseAnchor(), this.getExpandAdj());
31237         this.el.setStyle("z-index", 20000);
31238         this.collapsedEl.hide({
31239             duration:.1
31240         });
31241         this.el.slideIn(this.getSlideAnchor(), {
31242             callback : function(){
31243                 this.el.setStyle("z-index", "");
31244                 this.afterSlide();
31245                 if(this.split){
31246                     this.split.el.show();
31247                 }
31248                 this.fireEvent("invalidated", this);
31249                 this.fireEvent("expanded", this);
31250             },
31251             scope: this,
31252             block: true
31253         });
31254     },
31255
31256     anchors : {
31257         "west" : "left",
31258         "east" : "right",
31259         "north" : "top",
31260         "south" : "bottom"
31261     },
31262
31263     sanchors : {
31264         "west" : "l",
31265         "east" : "r",
31266         "north" : "t",
31267         "south" : "b"
31268     },
31269
31270     canchors : {
31271         "west" : "tl-tr",
31272         "east" : "tr-tl",
31273         "north" : "tl-bl",
31274         "south" : "bl-tl"
31275     },
31276
31277     getAnchor : function(){
31278         return this.anchors[this.position];
31279     },
31280
31281     getCollapseAnchor : function(){
31282         return this.canchors[this.position];
31283     },
31284
31285     getSlideAnchor : function(){
31286         return this.sanchors[this.position];
31287     },
31288
31289     getAlignAdj : function(){
31290         var cm = this.cmargins;
31291         switch(this.position){
31292             case "west":
31293                 return [0, 0];
31294             break;
31295             case "east":
31296                 return [0, 0];
31297             break;
31298             case "north":
31299                 return [0, 0];
31300             break;
31301             case "south":
31302                 return [0, 0];
31303             break;
31304         }
31305     },
31306
31307     getExpandAdj : function(){
31308         var c = this.collapsedEl, cm = this.cmargins;
31309         switch(this.position){
31310             case "west":
31311                 return [-(cm.right+c.getWidth()+cm.left), 0];
31312             break;
31313             case "east":
31314                 return [cm.right+c.getWidth()+cm.left, 0];
31315             break;
31316             case "north":
31317                 return [0, -(cm.top+cm.bottom+c.getHeight())];
31318             break;
31319             case "south":
31320                 return [0, cm.top+cm.bottom+c.getHeight()];
31321             break;
31322         }
31323     }
31324 });/*
31325  * Based on:
31326  * Ext JS Library 1.1.1
31327  * Copyright(c) 2006-2007, Ext JS, LLC.
31328  *
31329  * Originally Released Under LGPL - original licence link has changed is not relivant.
31330  *
31331  * Fork - LGPL
31332  * <script type="text/javascript">
31333  */
31334 /*
31335  * These classes are private internal classes
31336  */
31337 Roo.CenterLayoutRegion = function(mgr, config){
31338     Roo.LayoutRegion.call(this, mgr, config, "center");
31339     this.visible = true;
31340     this.minWidth = config.minWidth || 20;
31341     this.minHeight = config.minHeight || 20;
31342 };
31343
31344 Roo.extend(Roo.CenterLayoutRegion, Roo.LayoutRegion, {
31345     hide : function(){
31346         // center panel can't be hidden
31347     },
31348     
31349     show : function(){
31350         // center panel can't be hidden
31351     },
31352     
31353     getMinWidth: function(){
31354         return this.minWidth;
31355     },
31356     
31357     getMinHeight: function(){
31358         return this.minHeight;
31359     }
31360 });
31361
31362
31363 Roo.NorthLayoutRegion = function(mgr, config){
31364     Roo.LayoutRegion.call(this, mgr, config, "north", "n-resize");
31365     if(this.split){
31366         this.split.placement = Roo.SplitBar.TOP;
31367         this.split.orientation = Roo.SplitBar.VERTICAL;
31368         this.split.el.addClass("x-layout-split-v");
31369     }
31370     var size = config.initialSize || config.height;
31371     if(typeof size != "undefined"){
31372         this.el.setHeight(size);
31373     }
31374 };
31375 Roo.extend(Roo.NorthLayoutRegion, Roo.SplitLayoutRegion, {
31376     orientation: Roo.SplitBar.VERTICAL,
31377     getBox : function(){
31378         if(this.collapsed){
31379             return this.collapsedEl.getBox();
31380         }
31381         var box = this.el.getBox();
31382         if(this.split){
31383             box.height += this.split.el.getHeight();
31384         }
31385         return box;
31386     },
31387     
31388     updateBox : function(box){
31389         if(this.split && !this.collapsed){
31390             box.height -= this.split.el.getHeight();
31391             this.split.el.setLeft(box.x);
31392             this.split.el.setTop(box.y+box.height);
31393             this.split.el.setWidth(box.width);
31394         }
31395         if(this.collapsed){
31396             this.updateBody(box.width, null);
31397         }
31398         Roo.LayoutRegion.prototype.updateBox.call(this, box);
31399     }
31400 });
31401
31402 Roo.SouthLayoutRegion = function(mgr, config){
31403     Roo.SplitLayoutRegion.call(this, mgr, config, "south", "s-resize");
31404     if(this.split){
31405         this.split.placement = Roo.SplitBar.BOTTOM;
31406         this.split.orientation = Roo.SplitBar.VERTICAL;
31407         this.split.el.addClass("x-layout-split-v");
31408     }
31409     var size = config.initialSize || config.height;
31410     if(typeof size != "undefined"){
31411         this.el.setHeight(size);
31412     }
31413 };
31414 Roo.extend(Roo.SouthLayoutRegion, Roo.SplitLayoutRegion, {
31415     orientation: Roo.SplitBar.VERTICAL,
31416     getBox : function(){
31417         if(this.collapsed){
31418             return this.collapsedEl.getBox();
31419         }
31420         var box = this.el.getBox();
31421         if(this.split){
31422             var sh = this.split.el.getHeight();
31423             box.height += sh;
31424             box.y -= sh;
31425         }
31426         return box;
31427     },
31428     
31429     updateBox : function(box){
31430         if(this.split && !this.collapsed){
31431             var sh = this.split.el.getHeight();
31432             box.height -= sh;
31433             box.y += sh;
31434             this.split.el.setLeft(box.x);
31435             this.split.el.setTop(box.y-sh);
31436             this.split.el.setWidth(box.width);
31437         }
31438         if(this.collapsed){
31439             this.updateBody(box.width, null);
31440         }
31441         Roo.LayoutRegion.prototype.updateBox.call(this, box);
31442     }
31443 });
31444
31445 Roo.EastLayoutRegion = function(mgr, config){
31446     Roo.SplitLayoutRegion.call(this, mgr, config, "east", "e-resize");
31447     if(this.split){
31448         this.split.placement = Roo.SplitBar.RIGHT;
31449         this.split.orientation = Roo.SplitBar.HORIZONTAL;
31450         this.split.el.addClass("x-layout-split-h");
31451     }
31452     var size = config.initialSize || config.width;
31453     if(typeof size != "undefined"){
31454         this.el.setWidth(size);
31455     }
31456 };
31457 Roo.extend(Roo.EastLayoutRegion, Roo.SplitLayoutRegion, {
31458     orientation: Roo.SplitBar.HORIZONTAL,
31459     getBox : function(){
31460         if(this.collapsed){
31461             return this.collapsedEl.getBox();
31462         }
31463         var box = this.el.getBox();
31464         if(this.split){
31465             var sw = this.split.el.getWidth();
31466             box.width += sw;
31467             box.x -= sw;
31468         }
31469         return box;
31470     },
31471
31472     updateBox : function(box){
31473         if(this.split && !this.collapsed){
31474             var sw = this.split.el.getWidth();
31475             box.width -= sw;
31476             this.split.el.setLeft(box.x);
31477             this.split.el.setTop(box.y);
31478             this.split.el.setHeight(box.height);
31479             box.x += sw;
31480         }
31481         if(this.collapsed){
31482             this.updateBody(null, box.height);
31483         }
31484         Roo.LayoutRegion.prototype.updateBox.call(this, box);
31485     }
31486 });
31487
31488 Roo.WestLayoutRegion = function(mgr, config){
31489     Roo.SplitLayoutRegion.call(this, mgr, config, "west", "w-resize");
31490     if(this.split){
31491         this.split.placement = Roo.SplitBar.LEFT;
31492         this.split.orientation = Roo.SplitBar.HORIZONTAL;
31493         this.split.el.addClass("x-layout-split-h");
31494     }
31495     var size = config.initialSize || config.width;
31496     if(typeof size != "undefined"){
31497         this.el.setWidth(size);
31498     }
31499 };
31500 Roo.extend(Roo.WestLayoutRegion, Roo.SplitLayoutRegion, {
31501     orientation: Roo.SplitBar.HORIZONTAL,
31502     getBox : function(){
31503         if(this.collapsed){
31504             return this.collapsedEl.getBox();
31505         }
31506         var box = this.el.getBox();
31507         if(this.split){
31508             box.width += this.split.el.getWidth();
31509         }
31510         return box;
31511     },
31512     
31513     updateBox : function(box){
31514         if(this.split && !this.collapsed){
31515             var sw = this.split.el.getWidth();
31516             box.width -= sw;
31517             this.split.el.setLeft(box.x+box.width);
31518             this.split.el.setTop(box.y);
31519             this.split.el.setHeight(box.height);
31520         }
31521         if(this.collapsed){
31522             this.updateBody(null, box.height);
31523         }
31524         Roo.LayoutRegion.prototype.updateBox.call(this, box);
31525     }
31526 });
31527 /*
31528  * Based on:
31529  * Ext JS Library 1.1.1
31530  * Copyright(c) 2006-2007, Ext JS, LLC.
31531  *
31532  * Originally Released Under LGPL - original licence link has changed is not relivant.
31533  *
31534  * Fork - LGPL
31535  * <script type="text/javascript">
31536  */
31537  
31538  
31539 /*
31540  * Private internal class for reading and applying state
31541  */
31542 Roo.LayoutStateManager = function(layout){
31543      // default empty state
31544      this.state = {
31545         north: {},
31546         south: {},
31547         east: {},
31548         west: {}       
31549     };
31550 };
31551
31552 Roo.LayoutStateManager.prototype = {
31553     init : function(layout, provider){
31554         this.provider = provider;
31555         var state = provider.get(layout.id+"-layout-state");
31556         if(state){
31557             var wasUpdating = layout.isUpdating();
31558             if(!wasUpdating){
31559                 layout.beginUpdate();
31560             }
31561             for(var key in state){
31562                 if(typeof state[key] != "function"){
31563                     var rstate = state[key];
31564                     var r = layout.getRegion(key);
31565                     if(r && rstate){
31566                         if(rstate.size){
31567                             r.resizeTo(rstate.size);
31568                         }
31569                         if(rstate.collapsed == true){
31570                             r.collapse(true);
31571                         }else{
31572                             r.expand(null, true);
31573                         }
31574                     }
31575                 }
31576             }
31577             if(!wasUpdating){
31578                 layout.endUpdate();
31579             }
31580             this.state = state; 
31581         }
31582         this.layout = layout;
31583         layout.on("regionresized", this.onRegionResized, this);
31584         layout.on("regioncollapsed", this.onRegionCollapsed, this);
31585         layout.on("regionexpanded", this.onRegionExpanded, this);
31586     },
31587     
31588     storeState : function(){
31589         this.provider.set(this.layout.id+"-layout-state", this.state);
31590     },
31591     
31592     onRegionResized : function(region, newSize){
31593         this.state[region.getPosition()].size = newSize;
31594         this.storeState();
31595     },
31596     
31597     onRegionCollapsed : function(region){
31598         this.state[region.getPosition()].collapsed = true;
31599         this.storeState();
31600     },
31601     
31602     onRegionExpanded : function(region){
31603         this.state[region.getPosition()].collapsed = false;
31604         this.storeState();
31605     }
31606 };/*
31607  * Based on:
31608  * Ext JS Library 1.1.1
31609  * Copyright(c) 2006-2007, Ext JS, LLC.
31610  *
31611  * Originally Released Under LGPL - original licence link has changed is not relivant.
31612  *
31613  * Fork - LGPL
31614  * <script type="text/javascript">
31615  */
31616 /**
31617  * @class Roo.ContentPanel
31618  * @extends Roo.util.Observable
31619  * A basic ContentPanel element.
31620  * @cfg {Boolean}   fitToFrame    True for this panel to adjust its size to fit when the region resizes  (defaults to false)
31621  * @cfg {Boolean}   fitContainer   When using {@link #fitToFrame} and {@link #resizeEl}, you can also fit the parent container  (defaults to false)
31622  * @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
31623  * @cfg {Boolean}   closable      True if the panel can be closed/removed
31624  * @cfg {Boolean}   background    True if the panel should not be activated when it is added (defaults to false)
31625  * @cfg {String/HTMLElement/Element} resizeEl An element to resize if {@link #fitToFrame} is true (instead of this panel's element)
31626  * @cfg {Toolbar}   toolbar       A toolbar for this panel
31627  * @cfg {Boolean} autoScroll    True to scroll overflow in this panel (use with {@link #fitToFrame})
31628  * @cfg {String} title          The title for this panel
31629  * @cfg {Array} adjustments     Values to <b>add</b> to the width/height when doing a {@link #fitToFrame} (default is [0, 0])
31630  * @cfg {String} url            Calls {@link #setUrl} with this value
31631  * @cfg {String} region         (center|north|south|east|west) which region to put this panel on (when used with xtype constructors)
31632  * @cfg {String/Object} params  When used with {@link #url}, calls {@link #setUrl} with this value
31633  * @cfg {Boolean} loadOnce      When used with {@link #url}, calls {@link #setUrl} with this value
31634  * @cfg {String}    content        Raw content to fill content panel with (uses setContent on construction.)
31635
31636  * @constructor
31637  * Create a new ContentPanel.
31638  * @param {String/HTMLElement/Roo.Element} el The container element for this panel
31639  * @param {String/Object} config A string to set only the title or a config object
31640  * @param {String} content (optional) Set the HTML content for this panel
31641  * @param {String} region (optional) Used by xtype constructors to add to regions. (values center,east,west,south,north)
31642  */
31643 Roo.ContentPanel = function(el, config, content){
31644     
31645      
31646     /*
31647     if(el.autoCreate || el.xtype){ // xtype is available if this is called from factory
31648         config = el;
31649         el = Roo.id();
31650     }
31651     if (config && config.parentLayout) { 
31652         el = config.parentLayout.el.createChild(); 
31653     }
31654     */
31655     if(el.autoCreate){ // xtype is available if this is called from factory
31656         config = el;
31657         el = Roo.id();
31658     }
31659     this.el = Roo.get(el);
31660     if(!this.el && config && config.autoCreate){
31661         if(typeof config.autoCreate == "object"){
31662             if(!config.autoCreate.id){
31663                 config.autoCreate.id = config.id||el;
31664             }
31665             this.el = Roo.DomHelper.append(document.body,
31666                         config.autoCreate, true);
31667         }else{
31668             this.el = Roo.DomHelper.append(document.body,
31669                         {tag: "div", cls: "x-layout-inactive-content", id: config.id||el}, true);
31670         }
31671     }
31672     this.closable = false;
31673     this.loaded = false;
31674     this.active = false;
31675     if(typeof config == "string"){
31676         this.title = config;
31677     }else{
31678         Roo.apply(this, config);
31679     }
31680     
31681     if (this.toolbar && !this.toolbar.el && this.toolbar.xtype) {
31682         this.wrapEl = this.el.wrap();
31683         this.toolbar.container = this.el.insertSibling(false, 'before');
31684         this.toolbar = new Roo.Toolbar(this.toolbar);
31685     }
31686     
31687     // xtype created footer. - not sure if will work as we normally have to render first..
31688     if (this.footer && !this.footer.el && this.footer.xtype) {
31689         if (!this.wrapEl) {
31690             this.wrapEl = this.el.wrap();
31691         }
31692     
31693         this.footer.container = this.wrapEl.createChild();
31694          
31695         this.footer = Roo.factory(this.footer, Roo);
31696         
31697     }
31698     
31699     if(this.resizeEl){
31700         this.resizeEl = Roo.get(this.resizeEl, true);
31701     }else{
31702         this.resizeEl = this.el;
31703     }
31704     // handle view.xtype
31705     
31706  
31707     
31708     
31709     this.addEvents({
31710         /**
31711          * @event activate
31712          * Fires when this panel is activated. 
31713          * @param {Roo.ContentPanel} this
31714          */
31715         "activate" : true,
31716         /**
31717          * @event deactivate
31718          * Fires when this panel is activated. 
31719          * @param {Roo.ContentPanel} this
31720          */
31721         "deactivate" : true,
31722
31723         /**
31724          * @event resize
31725          * Fires when this panel is resized if fitToFrame is true.
31726          * @param {Roo.ContentPanel} this
31727          * @param {Number} width The width after any component adjustments
31728          * @param {Number} height The height after any component adjustments
31729          */
31730         "resize" : true,
31731         
31732          /**
31733          * @event render
31734          * Fires when this tab is created
31735          * @param {Roo.ContentPanel} this
31736          */
31737         "render" : true
31738          
31739         
31740     });
31741     
31742
31743     
31744     
31745     if(this.autoScroll){
31746         this.resizeEl.setStyle("overflow", "auto");
31747     } else {
31748         // fix randome scrolling
31749         this.el.on('scroll', function() {
31750             Roo.log('fix random scolling');
31751             this.scrollTo('top',0); 
31752         });
31753     }
31754     content = content || this.content;
31755     if(content){
31756         this.setContent(content);
31757     }
31758     if(config && config.url){
31759         this.setUrl(this.url, this.params, this.loadOnce);
31760     }
31761     
31762     
31763     
31764     Roo.ContentPanel.superclass.constructor.call(this);
31765     
31766     if (this.view && typeof(this.view.xtype) != 'undefined') {
31767         this.view.el = this.el.appendChild(document.createElement("div"));
31768         this.view = Roo.factory(this.view); 
31769         this.view.render  &&  this.view.render(false, '');  
31770     }
31771     
31772     
31773     this.fireEvent('render', this);
31774 };
31775
31776 Roo.extend(Roo.ContentPanel, Roo.util.Observable, {
31777     tabTip:'',
31778     setRegion : function(region){
31779         this.region = region;
31780         if(region){
31781            this.el.replaceClass("x-layout-inactive-content", "x-layout-active-content");
31782         }else{
31783            this.el.replaceClass("x-layout-active-content", "x-layout-inactive-content");
31784         } 
31785     },
31786     
31787     /**
31788      * Returns the toolbar for this Panel if one was configured. 
31789      * @return {Roo.Toolbar} 
31790      */
31791     getToolbar : function(){
31792         return this.toolbar;
31793     },
31794     
31795     setActiveState : function(active){
31796         this.active = active;
31797         if(!active){
31798             this.fireEvent("deactivate", this);
31799         }else{
31800             this.fireEvent("activate", this);
31801         }
31802     },
31803     /**
31804      * Updates this panel's element
31805      * @param {String} content The new content
31806      * @param {Boolean} loadScripts (optional) true to look for and process scripts
31807     */
31808     setContent : function(content, loadScripts){
31809         this.el.update(content, loadScripts);
31810     },
31811
31812     ignoreResize : function(w, h){
31813         if(this.lastSize && this.lastSize.width == w && this.lastSize.height == h){
31814             return true;
31815         }else{
31816             this.lastSize = {width: w, height: h};
31817             return false;
31818         }
31819     },
31820     /**
31821      * Get the {@link Roo.UpdateManager} for this panel. Enables you to perform Ajax updates.
31822      * @return {Roo.UpdateManager} The UpdateManager
31823      */
31824     getUpdateManager : function(){
31825         return this.el.getUpdateManager();
31826     },
31827      /**
31828      * Loads this content panel immediately with content from XHR. Note: to delay loading until the panel is activated, use {@link #setUrl}.
31829      * @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:
31830 <pre><code>
31831 panel.load({
31832     url: "your-url.php",
31833     params: {param1: "foo", param2: "bar"}, // or a URL encoded string
31834     callback: yourFunction,
31835     scope: yourObject, //(optional scope)
31836     discardUrl: false,
31837     nocache: false,
31838     text: "Loading...",
31839     timeout: 30,
31840     scripts: false
31841 });
31842 </code></pre>
31843      * The only required property is <i>url</i>. The optional properties <i>nocache</i>, <i>text</i> and <i>scripts</i>
31844      * 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.
31845      * @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}
31846      * @param {Function} callback (optional) Callback when transaction is complete -- called with signature (oElement, bSuccess, oResponse)
31847      * @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.
31848      * @return {Roo.ContentPanel} this
31849      */
31850     load : function(){
31851         var um = this.el.getUpdateManager();
31852         um.update.apply(um, arguments);
31853         return this;
31854     },
31855
31856
31857     /**
31858      * 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.
31859      * @param {String/Function} url The URL to load the content from or a function to call to get the URL
31860      * @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)
31861      * @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)
31862      * @return {Roo.UpdateManager} The UpdateManager
31863      */
31864     setUrl : function(url, params, loadOnce){
31865         if(this.refreshDelegate){
31866             this.removeListener("activate", this.refreshDelegate);
31867         }
31868         this.refreshDelegate = this._handleRefresh.createDelegate(this, [url, params, loadOnce]);
31869         this.on("activate", this.refreshDelegate);
31870         return this.el.getUpdateManager();
31871     },
31872     
31873     _handleRefresh : function(url, params, loadOnce){
31874         if(!loadOnce || !this.loaded){
31875             var updater = this.el.getUpdateManager();
31876             updater.update(url, params, this._setLoaded.createDelegate(this));
31877         }
31878     },
31879     
31880     _setLoaded : function(){
31881         this.loaded = true;
31882     }, 
31883     
31884     /**
31885      * Returns this panel's id
31886      * @return {String} 
31887      */
31888     getId : function(){
31889         return this.el.id;
31890     },
31891     
31892     /** 
31893      * Returns this panel's element - used by regiosn to add.
31894      * @return {Roo.Element} 
31895      */
31896     getEl : function(){
31897         return this.wrapEl || this.el;
31898     },
31899     
31900     adjustForComponents : function(width, height)
31901     {
31902         //Roo.log('adjustForComponents ');
31903         if(this.resizeEl != this.el){
31904             width -= this.el.getFrameWidth('lr');
31905             height -= this.el.getFrameWidth('tb');
31906         }
31907         if(this.toolbar){
31908             var te = this.toolbar.getEl();
31909             height -= te.getHeight();
31910             te.setWidth(width);
31911         }
31912         if(this.footer){
31913             var te = this.footer.getEl();
31914             //Roo.log("footer:" + te.getHeight());
31915             
31916             height -= te.getHeight();
31917             te.setWidth(width);
31918         }
31919         
31920         
31921         if(this.adjustments){
31922             width += this.adjustments[0];
31923             height += this.adjustments[1];
31924         }
31925         return {"width": width, "height": height};
31926     },
31927     
31928     setSize : function(width, height){
31929         if(this.fitToFrame && !this.ignoreResize(width, height)){
31930             if(this.fitContainer && this.resizeEl != this.el){
31931                 this.el.setSize(width, height);
31932             }
31933             var size = this.adjustForComponents(width, height);
31934             this.resizeEl.setSize(this.autoWidth ? "auto" : size.width, this.autoHeight ? "auto" : size.height);
31935             this.fireEvent('resize', this, size.width, size.height);
31936         }
31937     },
31938     
31939     /**
31940      * Returns this panel's title
31941      * @return {String} 
31942      */
31943     getTitle : function(){
31944         return this.title;
31945     },
31946     
31947     /**
31948      * Set this panel's title
31949      * @param {String} title
31950      */
31951     setTitle : function(title){
31952         this.title = title;
31953         if(this.region){
31954             this.region.updatePanelTitle(this, title);
31955         }
31956     },
31957     
31958     /**
31959      * Returns true is this panel was configured to be closable
31960      * @return {Boolean} 
31961      */
31962     isClosable : function(){
31963         return this.closable;
31964     },
31965     
31966     beforeSlide : function(){
31967         this.el.clip();
31968         this.resizeEl.clip();
31969     },
31970     
31971     afterSlide : function(){
31972         this.el.unclip();
31973         this.resizeEl.unclip();
31974     },
31975     
31976     /**
31977      *   Force a content refresh from the URL specified in the {@link #setUrl} method.
31978      *   Will fail silently if the {@link #setUrl} method has not been called.
31979      *   This does not activate the panel, just updates its content.
31980      */
31981     refresh : function(){
31982         if(this.refreshDelegate){
31983            this.loaded = false;
31984            this.refreshDelegate();
31985         }
31986     },
31987     
31988     /**
31989      * Destroys this panel
31990      */
31991     destroy : function(){
31992         this.el.removeAllListeners();
31993         var tempEl = document.createElement("span");
31994         tempEl.appendChild(this.el.dom);
31995         tempEl.innerHTML = "";
31996         this.el.remove();
31997         this.el = null;
31998     },
31999     
32000     /**
32001      * form - if the content panel contains a form - this is a reference to it.
32002      * @type {Roo.form.Form}
32003      */
32004     form : false,
32005     /**
32006      * view - if the content panel contains a view (Roo.DatePicker / Roo.View / Roo.JsonView)
32007      *    This contains a reference to it.
32008      * @type {Roo.View}
32009      */
32010     view : false,
32011     
32012       /**
32013      * Adds a xtype elements to the panel - currently only supports Forms, View, JsonView.
32014      * <pre><code>
32015
32016 layout.addxtype({
32017        xtype : 'Form',
32018        items: [ .... ]
32019    }
32020 );
32021
32022 </code></pre>
32023      * @param {Object} cfg Xtype definition of item to add.
32024      */
32025     
32026     addxtype : function(cfg) {
32027         // add form..
32028         if (cfg.xtype.match(/^Form$/)) {
32029             
32030             var el;
32031             //if (this.footer) {
32032             //    el = this.footer.container.insertSibling(false, 'before');
32033             //} else {
32034                 el = this.el.createChild();
32035             //}
32036
32037             this.form = new  Roo.form.Form(cfg);
32038             
32039             
32040             if ( this.form.allItems.length) {
32041                 this.form.render(el.dom);
32042             }
32043             return this.form;
32044         }
32045         // should only have one of theses..
32046         if ([ 'View', 'JsonView', 'DatePicker'].indexOf(cfg.xtype) > -1) {
32047             // views.. should not be just added - used named prop 'view''
32048             
32049             cfg.el = this.el.appendChild(document.createElement("div"));
32050             // factory?
32051             
32052             var ret = new Roo.factory(cfg);
32053              
32054              ret.render && ret.render(false, ''); // render blank..
32055             this.view = ret;
32056             return ret;
32057         }
32058         return false;
32059     }
32060 });
32061
32062 /**
32063  * @class Roo.GridPanel
32064  * @extends Roo.ContentPanel
32065  * @constructor
32066  * Create a new GridPanel.
32067  * @param {Roo.grid.Grid} grid The grid for this panel
32068  * @param {String/Object} config A string to set only the panel's title, or a config object
32069  */
32070 Roo.GridPanel = function(grid, config){
32071     
32072   
32073     this.wrapper = Roo.DomHelper.append(document.body, // wrapper for IE7 strict & safari scroll issue
32074         {tag: "div", cls: "x-layout-grid-wrapper x-layout-inactive-content"}, true);
32075         
32076     this.wrapper.dom.appendChild(grid.getGridEl().dom);
32077     
32078     Roo.GridPanel.superclass.constructor.call(this, this.wrapper, config);
32079     
32080     if(this.toolbar){
32081         this.toolbar.el.insertBefore(this.wrapper.dom.firstChild);
32082     }
32083     // xtype created footer. - not sure if will work as we normally have to render first..
32084     if (this.footer && !this.footer.el && this.footer.xtype) {
32085         
32086         this.footer.container = this.grid.getView().getFooterPanel(true);
32087         this.footer.dataSource = this.grid.dataSource;
32088         this.footer = Roo.factory(this.footer, Roo);
32089         
32090     }
32091     
32092     grid.monitorWindowResize = false; // turn off autosizing
32093     grid.autoHeight = false;
32094     grid.autoWidth = false;
32095     this.grid = grid;
32096     this.grid.getGridEl().replaceClass("x-layout-inactive-content", "x-layout-component-panel");
32097 };
32098
32099 Roo.extend(Roo.GridPanel, Roo.ContentPanel, {
32100     getId : function(){
32101         return this.grid.id;
32102     },
32103     
32104     /**
32105      * Returns the grid for this panel
32106      * @return {Roo.grid.Grid} 
32107      */
32108     getGrid : function(){
32109         return this.grid;    
32110     },
32111     
32112     setSize : function(width, height){
32113         if(!this.ignoreResize(width, height)){
32114             var grid = this.grid;
32115             var size = this.adjustForComponents(width, height);
32116             grid.getGridEl().setSize(size.width, size.height);
32117             grid.autoSize();
32118         }
32119     },
32120     
32121     beforeSlide : function(){
32122         this.grid.getView().scroller.clip();
32123     },
32124     
32125     afterSlide : function(){
32126         this.grid.getView().scroller.unclip();
32127     },
32128     
32129     destroy : function(){
32130         this.grid.destroy();
32131         delete this.grid;
32132         Roo.GridPanel.superclass.destroy.call(this); 
32133     }
32134 });
32135
32136
32137 /**
32138  * @class Roo.NestedLayoutPanel
32139  * @extends Roo.ContentPanel
32140  * @constructor
32141  * Create a new NestedLayoutPanel.
32142  * 
32143  * 
32144  * @param {Roo.BorderLayout} layout The layout for this panel
32145  * @param {String/Object} config A string to set only the title or a config object
32146  */
32147 Roo.NestedLayoutPanel = function(layout, config)
32148 {
32149     // construct with only one argument..
32150     /* FIXME - implement nicer consturctors
32151     if (layout.layout) {
32152         config = layout;
32153         layout = config.layout;
32154         delete config.layout;
32155     }
32156     if (layout.xtype && !layout.getEl) {
32157         // then layout needs constructing..
32158         layout = Roo.factory(layout, Roo);
32159     }
32160     */
32161     
32162     
32163     Roo.NestedLayoutPanel.superclass.constructor.call(this, layout.getEl(), config);
32164     
32165     layout.monitorWindowResize = false; // turn off autosizing
32166     this.layout = layout;
32167     this.layout.getEl().addClass("x-layout-nested-layout");
32168     
32169     
32170     
32171     
32172 };
32173
32174 Roo.extend(Roo.NestedLayoutPanel, Roo.ContentPanel, {
32175
32176     setSize : function(width, height){
32177         if(!this.ignoreResize(width, height)){
32178             var size = this.adjustForComponents(width, height);
32179             var el = this.layout.getEl();
32180             el.setSize(size.width, size.height);
32181             var touch = el.dom.offsetWidth;
32182             this.layout.layout();
32183             // ie requires a double layout on the first pass
32184             if(Roo.isIE && !this.initialized){
32185                 this.initialized = true;
32186                 this.layout.layout();
32187             }
32188         }
32189     },
32190     
32191     // activate all subpanels if not currently active..
32192     
32193     setActiveState : function(active){
32194         this.active = active;
32195         if(!active){
32196             this.fireEvent("deactivate", this);
32197             return;
32198         }
32199         
32200         this.fireEvent("activate", this);
32201         // not sure if this should happen before or after..
32202         if (!this.layout) {
32203             return; // should not happen..
32204         }
32205         var reg = false;
32206         for (var r in this.layout.regions) {
32207             reg = this.layout.getRegion(r);
32208             if (reg.getActivePanel()) {
32209                 //reg.showPanel(reg.getActivePanel()); // force it to activate.. 
32210                 reg.setActivePanel(reg.getActivePanel());
32211                 continue;
32212             }
32213             if (!reg.panels.length) {
32214                 continue;
32215             }
32216             reg.showPanel(reg.getPanel(0));
32217         }
32218         
32219         
32220         
32221         
32222     },
32223     
32224     /**
32225      * Returns the nested BorderLayout for this panel
32226      * @return {Roo.BorderLayout} 
32227      */
32228     getLayout : function(){
32229         return this.layout;
32230     },
32231     
32232      /**
32233      * Adds a xtype elements to the layout of the nested panel
32234      * <pre><code>
32235
32236 panel.addxtype({
32237        xtype : 'ContentPanel',
32238        region: 'west',
32239        items: [ .... ]
32240    }
32241 );
32242
32243 panel.addxtype({
32244         xtype : 'NestedLayoutPanel',
32245         region: 'west',
32246         layout: {
32247            center: { },
32248            west: { }   
32249         },
32250         items : [ ... list of content panels or nested layout panels.. ]
32251    }
32252 );
32253 </code></pre>
32254      * @param {Object} cfg Xtype definition of item to add.
32255      */
32256     addxtype : function(cfg) {
32257         return this.layout.addxtype(cfg);
32258     
32259     }
32260 });
32261
32262 Roo.ScrollPanel = function(el, config, content){
32263     config = config || {};
32264     config.fitToFrame = true;
32265     Roo.ScrollPanel.superclass.constructor.call(this, el, config, content);
32266     
32267     this.el.dom.style.overflow = "hidden";
32268     var wrap = this.el.wrap({cls: "x-scroller x-layout-inactive-content"});
32269     this.el.removeClass("x-layout-inactive-content");
32270     this.el.on("mousewheel", this.onWheel, this);
32271
32272     var up = wrap.createChild({cls: "x-scroller-up", html: "&#160;"}, this.el.dom);
32273     var down = wrap.createChild({cls: "x-scroller-down", html: "&#160;"});
32274     up.unselectable(); down.unselectable();
32275     up.on("click", this.scrollUp, this);
32276     down.on("click", this.scrollDown, this);
32277     up.addClassOnOver("x-scroller-btn-over");
32278     down.addClassOnOver("x-scroller-btn-over");
32279     up.addClassOnClick("x-scroller-btn-click");
32280     down.addClassOnClick("x-scroller-btn-click");
32281     this.adjustments = [0, -(up.getHeight() + down.getHeight())];
32282
32283     this.resizeEl = this.el;
32284     this.el = wrap; this.up = up; this.down = down;
32285 };
32286
32287 Roo.extend(Roo.ScrollPanel, Roo.ContentPanel, {
32288     increment : 100,
32289     wheelIncrement : 5,
32290     scrollUp : function(){
32291         this.resizeEl.scroll("up", this.increment, {callback: this.afterScroll, scope: this});
32292     },
32293
32294     scrollDown : function(){
32295         this.resizeEl.scroll("down", this.increment, {callback: this.afterScroll, scope: this});
32296     },
32297
32298     afterScroll : function(){
32299         var el = this.resizeEl;
32300         var t = el.dom.scrollTop, h = el.dom.scrollHeight, ch = el.dom.clientHeight;
32301         this.up[t == 0 ? "addClass" : "removeClass"]("x-scroller-btn-disabled");
32302         this.down[h - t <= ch ? "addClass" : "removeClass"]("x-scroller-btn-disabled");
32303     },
32304
32305     setSize : function(){
32306         Roo.ScrollPanel.superclass.setSize.apply(this, arguments);
32307         this.afterScroll();
32308     },
32309
32310     onWheel : function(e){
32311         var d = e.getWheelDelta();
32312         this.resizeEl.dom.scrollTop -= (d*this.wheelIncrement);
32313         this.afterScroll();
32314         e.stopEvent();
32315     },
32316
32317     setContent : function(content, loadScripts){
32318         this.resizeEl.update(content, loadScripts);
32319     }
32320
32321 });
32322
32323
32324
32325
32326
32327
32328
32329
32330
32331 /**
32332  * @class Roo.TreePanel
32333  * @extends Roo.ContentPanel
32334  * @constructor
32335  * Create a new TreePanel. - defaults to fit/scoll contents.
32336  * @param {String/Object} config A string to set only the panel's title, or a config object
32337  * @cfg {Roo.tree.TreePanel} tree The tree TreePanel, with config etc.
32338  */
32339 Roo.TreePanel = function(config){
32340     var el = config.el;
32341     var tree = config.tree;
32342     delete config.tree; 
32343     delete config.el; // hopefull!
32344     
32345     // wrapper for IE7 strict & safari scroll issue
32346     
32347     var treeEl = el.createChild();
32348     config.resizeEl = treeEl;
32349     
32350     
32351     
32352     Roo.TreePanel.superclass.constructor.call(this, el, config);
32353  
32354  
32355     this.tree = new Roo.tree.TreePanel(treeEl , tree);
32356     //console.log(tree);
32357     this.on('activate', function()
32358     {
32359         if (this.tree.rendered) {
32360             return;
32361         }
32362         //console.log('render tree');
32363         this.tree.render();
32364     });
32365     // this should not be needed.. - it's actually the 'el' that resizes?
32366     // actuall it breaks the containerScroll - dragging nodes auto scroll at top
32367     
32368     //this.on('resize',  function (cp, w, h) {
32369     //        this.tree.innerCt.setWidth(w);
32370     //        this.tree.innerCt.setHeight(h);
32371     //        //this.tree.innerCt.setStyle('overflow-y', 'auto');
32372     //});
32373
32374         
32375     
32376 };
32377
32378 Roo.extend(Roo.TreePanel, Roo.ContentPanel, {   
32379     fitToFrame : true,
32380     autoScroll : true
32381 });
32382
32383
32384
32385
32386
32387
32388
32389
32390
32391
32392
32393 /*
32394  * Based on:
32395  * Ext JS Library 1.1.1
32396  * Copyright(c) 2006-2007, Ext JS, LLC.
32397  *
32398  * Originally Released Under LGPL - original licence link has changed is not relivant.
32399  *
32400  * Fork - LGPL
32401  * <script type="text/javascript">
32402  */
32403  
32404
32405 /**
32406  * @class Roo.ReaderLayout
32407  * @extends Roo.BorderLayout
32408  * This is a pre-built layout that represents a classic, 5-pane application.  It consists of a header, a primary
32409  * center region containing two nested regions (a top one for a list view and one for item preview below),
32410  * and regions on either side that can be used for navigation, application commands, informational displays, etc.
32411  * The setup and configuration work exactly the same as it does for a {@link Roo.BorderLayout} - this class simply
32412  * expedites the setup of the overall layout and regions for this common application style.
32413  * Example:
32414  <pre><code>
32415 var reader = new Roo.ReaderLayout();
32416 var CP = Roo.ContentPanel;  // shortcut for adding
32417
32418 reader.beginUpdate();
32419 reader.add("north", new CP("north", "North"));
32420 reader.add("west", new CP("west", {title: "West"}));
32421 reader.add("east", new CP("east", {title: "East"}));
32422
32423 reader.regions.listView.add(new CP("listView", "List"));
32424 reader.regions.preview.add(new CP("preview", "Preview"));
32425 reader.endUpdate();
32426 </code></pre>
32427 * @constructor
32428 * Create a new ReaderLayout
32429 * @param {Object} config Configuration options
32430 * @param {String/HTMLElement/Element} container (optional) The container this layout is bound to (defaults to
32431 * document.body if omitted)
32432 */
32433 Roo.ReaderLayout = function(config, renderTo){
32434     var c = config || {size:{}};
32435     Roo.ReaderLayout.superclass.constructor.call(this, renderTo || document.body, {
32436         north: c.north !== false ? Roo.apply({
32437             split:false,
32438             initialSize: 32,
32439             titlebar: false
32440         }, c.north) : false,
32441         west: c.west !== false ? Roo.apply({
32442             split:true,
32443             initialSize: 200,
32444             minSize: 175,
32445             maxSize: 400,
32446             titlebar: true,
32447             collapsible: true,
32448             animate: true,
32449             margins:{left:5,right:0,bottom:5,top:5},
32450             cmargins:{left:5,right:5,bottom:5,top:5}
32451         }, c.west) : false,
32452         east: c.east !== false ? Roo.apply({
32453             split:true,
32454             initialSize: 200,
32455             minSize: 175,
32456             maxSize: 400,
32457             titlebar: true,
32458             collapsible: true,
32459             animate: true,
32460             margins:{left:0,right:5,bottom:5,top:5},
32461             cmargins:{left:5,right:5,bottom:5,top:5}
32462         }, c.east) : false,
32463         center: Roo.apply({
32464             tabPosition: 'top',
32465             autoScroll:false,
32466             closeOnTab: true,
32467             titlebar:false,
32468             margins:{left:c.west!==false ? 0 : 5,right:c.east!==false ? 0 : 5,bottom:5,top:2}
32469         }, c.center)
32470     });
32471
32472     this.el.addClass('x-reader');
32473
32474     this.beginUpdate();
32475
32476     var inner = new Roo.BorderLayout(Roo.get(document.body).createChild(), {
32477         south: c.preview !== false ? Roo.apply({
32478             split:true,
32479             initialSize: 200,
32480             minSize: 100,
32481             autoScroll:true,
32482             collapsible:true,
32483             titlebar: true,
32484             cmargins:{top:5,left:0, right:0, bottom:0}
32485         }, c.preview) : false,
32486         center: Roo.apply({
32487             autoScroll:false,
32488             titlebar:false,
32489             minHeight:200
32490         }, c.listView)
32491     });
32492     this.add('center', new Roo.NestedLayoutPanel(inner,
32493             Roo.apply({title: c.mainTitle || '',tabTip:''},c.innerPanelCfg)));
32494
32495     this.endUpdate();
32496
32497     this.regions.preview = inner.getRegion('south');
32498     this.regions.listView = inner.getRegion('center');
32499 };
32500
32501 Roo.extend(Roo.ReaderLayout, Roo.BorderLayout);/*
32502  * Based on:
32503  * Ext JS Library 1.1.1
32504  * Copyright(c) 2006-2007, Ext JS, LLC.
32505  *
32506  * Originally Released Under LGPL - original licence link has changed is not relivant.
32507  *
32508  * Fork - LGPL
32509  * <script type="text/javascript">
32510  */
32511  
32512 /**
32513  * @class Roo.grid.Grid
32514  * @extends Roo.util.Observable
32515  * This class represents the primary interface of a component based grid control.
32516  * <br><br>Usage:<pre><code>
32517  var grid = new Roo.grid.Grid("my-container-id", {
32518      ds: myDataStore,
32519      cm: myColModel,
32520      selModel: mySelectionModel,
32521      autoSizeColumns: true,
32522      monitorWindowResize: false,
32523      trackMouseOver: true
32524  });
32525  // set any options
32526  grid.render();
32527  * </code></pre>
32528  * <b>Common Problems:</b><br/>
32529  * - Grid does not resize properly when going smaller: Setting overflow hidden on the container
32530  * element will correct this<br/>
32531  * - If you get el.style[camel]= NaNpx or -2px or something related, be certain you have given your container element
32532  * dimensions. The grid adapts to your container's size, if your container has no size defined then the results
32533  * are unpredictable.<br/>
32534  * - Do not render the grid into an element with display:none. Try using visibility:hidden. Otherwise there is no way for the
32535  * grid to calculate dimensions/offsets.<br/>
32536   * @constructor
32537  * @param {String/HTMLElement/Roo.Element} container The element into which this grid will be rendered -
32538  * The container MUST have some type of size defined for the grid to fill. The container will be
32539  * automatically set to position relative if it isn't already.
32540  * @param {Object} config A config object that sets properties on this grid.
32541  */
32542 Roo.grid.Grid = function(container, config){
32543         // initialize the container
32544         this.container = Roo.get(container);
32545         this.container.update("");
32546         this.container.setStyle("overflow", "hidden");
32547     this.container.addClass('x-grid-container');
32548
32549     this.id = this.container.id;
32550
32551     Roo.apply(this, config);
32552     // check and correct shorthanded configs
32553     if(this.ds){
32554         this.dataSource = this.ds;
32555         delete this.ds;
32556     }
32557     if(this.cm){
32558         this.colModel = this.cm;
32559         delete this.cm;
32560     }
32561     if(this.sm){
32562         this.selModel = this.sm;
32563         delete this.sm;
32564     }
32565
32566     if (this.selModel) {
32567         this.selModel = Roo.factory(this.selModel, Roo.grid);
32568         this.sm = this.selModel;
32569         this.sm.xmodule = this.xmodule || false;
32570     }
32571     if (typeof(this.colModel.config) == 'undefined') {
32572         this.colModel = new Roo.grid.ColumnModel(this.colModel);
32573         this.cm = this.colModel;
32574         this.cm.xmodule = this.xmodule || false;
32575     }
32576     if (this.dataSource) {
32577         this.dataSource= Roo.factory(this.dataSource, Roo.data);
32578         this.ds = this.dataSource;
32579         this.ds.xmodule = this.xmodule || false;
32580          
32581     }
32582     
32583     
32584     
32585     if(this.width){
32586         this.container.setWidth(this.width);
32587     }
32588
32589     if(this.height){
32590         this.container.setHeight(this.height);
32591     }
32592     /** @private */
32593         this.addEvents({
32594         // raw events
32595         /**
32596          * @event click
32597          * The raw click event for the entire grid.
32598          * @param {Roo.EventObject} e
32599          */
32600         "click" : true,
32601         /**
32602          * @event dblclick
32603          * The raw dblclick event for the entire grid.
32604          * @param {Roo.EventObject} e
32605          */
32606         "dblclick" : true,
32607         /**
32608          * @event contextmenu
32609          * The raw contextmenu event for the entire grid.
32610          * @param {Roo.EventObject} e
32611          */
32612         "contextmenu" : true,
32613         /**
32614          * @event mousedown
32615          * The raw mousedown event for the entire grid.
32616          * @param {Roo.EventObject} e
32617          */
32618         "mousedown" : true,
32619         /**
32620          * @event mouseup
32621          * The raw mouseup event for the entire grid.
32622          * @param {Roo.EventObject} e
32623          */
32624         "mouseup" : true,
32625         /**
32626          * @event mouseover
32627          * The raw mouseover event for the entire grid.
32628          * @param {Roo.EventObject} e
32629          */
32630         "mouseover" : true,
32631         /**
32632          * @event mouseout
32633          * The raw mouseout event for the entire grid.
32634          * @param {Roo.EventObject} e
32635          */
32636         "mouseout" : true,
32637         /**
32638          * @event keypress
32639          * The raw keypress event for the entire grid.
32640          * @param {Roo.EventObject} e
32641          */
32642         "keypress" : true,
32643         /**
32644          * @event keydown
32645          * The raw keydown event for the entire grid.
32646          * @param {Roo.EventObject} e
32647          */
32648         "keydown" : true,
32649
32650         // custom events
32651
32652         /**
32653          * @event cellclick
32654          * Fires when a cell is clicked
32655          * @param {Grid} this
32656          * @param {Number} rowIndex
32657          * @param {Number} columnIndex
32658          * @param {Roo.EventObject} e
32659          */
32660         "cellclick" : true,
32661         /**
32662          * @event celldblclick
32663          * Fires when a cell is double clicked
32664          * @param {Grid} this
32665          * @param {Number} rowIndex
32666          * @param {Number} columnIndex
32667          * @param {Roo.EventObject} e
32668          */
32669         "celldblclick" : true,
32670         /**
32671          * @event rowclick
32672          * Fires when a row is clicked
32673          * @param {Grid} this
32674          * @param {Number} rowIndex
32675          * @param {Roo.EventObject} e
32676          */
32677         "rowclick" : true,
32678         /**
32679          * @event rowdblclick
32680          * Fires when a row is double clicked
32681          * @param {Grid} this
32682          * @param {Number} rowIndex
32683          * @param {Roo.EventObject} e
32684          */
32685         "rowdblclick" : true,
32686         /**
32687          * @event headerclick
32688          * Fires when a header is clicked
32689          * @param {Grid} this
32690          * @param {Number} columnIndex
32691          * @param {Roo.EventObject} e
32692          */
32693         "headerclick" : true,
32694         /**
32695          * @event headerdblclick
32696          * Fires when a header cell is double clicked
32697          * @param {Grid} this
32698          * @param {Number} columnIndex
32699          * @param {Roo.EventObject} e
32700          */
32701         "headerdblclick" : true,
32702         /**
32703          * @event rowcontextmenu
32704          * Fires when a row is right clicked
32705          * @param {Grid} this
32706          * @param {Number} rowIndex
32707          * @param {Roo.EventObject} e
32708          */
32709         "rowcontextmenu" : true,
32710         /**
32711          * @event cellcontextmenu
32712          * Fires when a cell is right clicked
32713          * @param {Grid} this
32714          * @param {Number} rowIndex
32715          * @param {Number} cellIndex
32716          * @param {Roo.EventObject} e
32717          */
32718          "cellcontextmenu" : true,
32719         /**
32720          * @event headercontextmenu
32721          * Fires when a header is right clicked
32722          * @param {Grid} this
32723          * @param {Number} columnIndex
32724          * @param {Roo.EventObject} e
32725          */
32726         "headercontextmenu" : true,
32727         /**
32728          * @event bodyscroll
32729          * Fires when the body element is scrolled
32730          * @param {Number} scrollLeft
32731          * @param {Number} scrollTop
32732          */
32733         "bodyscroll" : true,
32734         /**
32735          * @event columnresize
32736          * Fires when the user resizes a column
32737          * @param {Number} columnIndex
32738          * @param {Number} newSize
32739          */
32740         "columnresize" : true,
32741         /**
32742          * @event columnmove
32743          * Fires when the user moves a column
32744          * @param {Number} oldIndex
32745          * @param {Number} newIndex
32746          */
32747         "columnmove" : true,
32748         /**
32749          * @event startdrag
32750          * Fires when row(s) start being dragged
32751          * @param {Grid} this
32752          * @param {Roo.GridDD} dd The drag drop object
32753          * @param {event} e The raw browser event
32754          */
32755         "startdrag" : true,
32756         /**
32757          * @event enddrag
32758          * Fires when a drag operation is complete
32759          * @param {Grid} this
32760          * @param {Roo.GridDD} dd The drag drop object
32761          * @param {event} e The raw browser event
32762          */
32763         "enddrag" : true,
32764         /**
32765          * @event dragdrop
32766          * Fires when dragged row(s) are dropped on a valid DD target
32767          * @param {Grid} this
32768          * @param {Roo.GridDD} dd The drag drop object
32769          * @param {String} targetId The target drag drop object
32770          * @param {event} e The raw browser event
32771          */
32772         "dragdrop" : true,
32773         /**
32774          * @event dragover
32775          * Fires while row(s) are being dragged. "targetId" is the id of the Yahoo.util.DD object the selected rows are being dragged over.
32776          * @param {Grid} this
32777          * @param {Roo.GridDD} dd The drag drop object
32778          * @param {String} targetId The target drag drop object
32779          * @param {event} e The raw browser event
32780          */
32781         "dragover" : true,
32782         /**
32783          * @event dragenter
32784          *  Fires when the dragged row(s) first cross another DD target while being dragged
32785          * @param {Grid} this
32786          * @param {Roo.GridDD} dd The drag drop object
32787          * @param {String} targetId The target drag drop object
32788          * @param {event} e The raw browser event
32789          */
32790         "dragenter" : true,
32791         /**
32792          * @event dragout
32793          * Fires when the dragged row(s) leave another DD target while being dragged
32794          * @param {Grid} this
32795          * @param {Roo.GridDD} dd The drag drop object
32796          * @param {String} targetId The target drag drop object
32797          * @param {event} e The raw browser event
32798          */
32799         "dragout" : true,
32800         /**
32801          * @event rowclass
32802          * Fires when a row is rendered, so you can change add a style to it.
32803          * @param {GridView} gridview   The grid view
32804          * @param {Object} rowcfg   contains record  rowIndex and rowClass - set rowClass to add a style.
32805          */
32806         'rowclass' : true,
32807
32808         /**
32809          * @event render
32810          * Fires when the grid is rendered
32811          * @param {Grid} grid
32812          */
32813         'render' : true
32814     });
32815
32816     Roo.grid.Grid.superclass.constructor.call(this);
32817 };
32818 Roo.extend(Roo.grid.Grid, Roo.util.Observable, {
32819     
32820     /**
32821      * @cfg {String} ddGroup - drag drop group.
32822      */
32823
32824     /**
32825      * @cfg {Number} minColumnWidth The minimum width a column can be resized to. Default is 25.
32826      */
32827     minColumnWidth : 25,
32828
32829     /**
32830      * @cfg {Boolean} autoSizeColumns True to automatically resize the columns to fit their content
32831      * <b>on initial render.</b> It is more efficient to explicitly size the columns
32832      * through the ColumnModel's {@link Roo.grid.ColumnModel#width} config option.  Default is false.
32833      */
32834     autoSizeColumns : false,
32835
32836     /**
32837      * @cfg {Boolean} autoSizeHeaders True to measure headers with column data when auto sizing columns. Default is true.
32838      */
32839     autoSizeHeaders : true,
32840
32841     /**
32842      * @cfg {Boolean} monitorWindowResize True to autoSize the grid when the window resizes. Default is true.
32843      */
32844     monitorWindowResize : true,
32845
32846     /**
32847      * @cfg {Boolean} maxRowsToMeasure If autoSizeColumns is on, maxRowsToMeasure can be used to limit the number of
32848      * rows measured to get a columns size. Default is 0 (all rows).
32849      */
32850     maxRowsToMeasure : 0,
32851
32852     /**
32853      * @cfg {Boolean} trackMouseOver True to highlight rows when the mouse is over. Default is true.
32854      */
32855     trackMouseOver : true,
32856
32857     /**
32858     * @cfg {Boolean} enableDrag  True to enable drag of rows. Default is false. (double check if this is needed?)
32859     */
32860     
32861     /**
32862     * @cfg {Boolean} enableDragDrop True to enable drag and drop of rows. Default is false.
32863     */
32864     enableDragDrop : false,
32865     
32866     /**
32867     * @cfg {Boolean} enableColumnMove True to enable drag and drop reorder of columns. Default is true.
32868     */
32869     enableColumnMove : true,
32870     
32871     /**
32872     * @cfg {Boolean} enableColumnHide True to enable hiding of columns with the header context menu. Default is true.
32873     */
32874     enableColumnHide : true,
32875     
32876     /**
32877     * @cfg {Boolean} enableRowHeightSync True to manually sync row heights across locked and not locked rows. Default is false.
32878     */
32879     enableRowHeightSync : false,
32880     
32881     /**
32882     * @cfg {Boolean} stripeRows True to stripe the rows.  Default is true.
32883     */
32884     stripeRows : true,
32885     
32886     /**
32887     * @cfg {Boolean} autoHeight True to fit the height of the grid container to the height of the data. Default is false.
32888     */
32889     autoHeight : false,
32890
32891     /**
32892      * @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.
32893      */
32894     autoExpandColumn : false,
32895
32896     /**
32897     * @cfg {Number} autoExpandMin The minimum width the autoExpandColumn can have (if enabled).
32898     * Default is 50.
32899     */
32900     autoExpandMin : 50,
32901
32902     /**
32903     * @cfg {Number} autoExpandMax The maximum width the autoExpandColumn can have (if enabled). Default is 1000.
32904     */
32905     autoExpandMax : 1000,
32906
32907     /**
32908     * @cfg {Object} view The {@link Roo.grid.GridView} used by the grid. This can be set before a call to render().
32909     */
32910     view : null,
32911
32912     /**
32913     * @cfg {Object} loadMask An {@link Roo.LoadMask} config or true to mask the grid while loading. Default is false.
32914     */
32915     loadMask : false,
32916     /**
32917     * @cfg {Roo.dd.DropTarget} dropTarget An {@link Roo.dd.DropTarget} config
32918     */
32919     dropTarget: false,
32920     
32921    
32922     
32923     // private
32924     rendered : false,
32925
32926     /**
32927     * @cfg {Boolean} autoWidth True to set the grid's width to the default total width of the grid's columns instead
32928     * of a fixed width. Default is false.
32929     */
32930     /**
32931     * @cfg {Number} maxHeight Sets the maximum height of the grid - ignored if autoHeight is not on.
32932     */
32933     /**
32934      * Called once after all setup has been completed and the grid is ready to be rendered.
32935      * @return {Roo.grid.Grid} this
32936      */
32937     render : function()
32938     {
32939         var c = this.container;
32940         // try to detect autoHeight/width mode
32941         if((!c.dom.offsetHeight || c.dom.offsetHeight < 20) || c.getStyle("height") == "auto"){
32942             this.autoHeight = true;
32943         }
32944         var view = this.getView();
32945         view.init(this);
32946
32947         c.on("click", this.onClick, this);
32948         c.on("dblclick", this.onDblClick, this);
32949         c.on("contextmenu", this.onContextMenu, this);
32950         c.on("keydown", this.onKeyDown, this);
32951         if (Roo.isTouch) {
32952             c.on("touchstart", this.onTouchStart, this);
32953         }
32954
32955         this.relayEvents(c, ["mousedown","mouseup","mouseover","mouseout","keypress"]);
32956
32957         this.getSelectionModel().init(this);
32958
32959         view.render();
32960
32961         if(this.loadMask){
32962             this.loadMask = new Roo.LoadMask(this.container,
32963                     Roo.apply({store:this.dataSource}, this.loadMask));
32964         }
32965         
32966         
32967         if (this.toolbar && this.toolbar.xtype) {
32968             this.toolbar.container = this.getView().getHeaderPanel(true);
32969             this.toolbar = new Roo.Toolbar(this.toolbar);
32970         }
32971         if (this.footer && this.footer.xtype) {
32972             this.footer.dataSource = this.getDataSource();
32973             this.footer.container = this.getView().getFooterPanel(true);
32974             this.footer = Roo.factory(this.footer, Roo);
32975         }
32976         if (this.dropTarget && this.dropTarget.xtype) {
32977             delete this.dropTarget.xtype;
32978             this.dropTarget =  new Roo.dd.DropTarget(this.getView().mainBody, this.dropTarget);
32979         }
32980         
32981         
32982         this.rendered = true;
32983         this.fireEvent('render', this);
32984         return this;
32985     },
32986
32987     /**
32988      * Reconfigures the grid to use a different Store and Column Model.
32989      * The View will be bound to the new objects and refreshed.
32990      * @param {Roo.data.Store} dataSource The new {@link Roo.data.Store} object
32991      * @param {Roo.grid.ColumnModel} The new {@link Roo.grid.ColumnModel} object
32992      */
32993     reconfigure : function(dataSource, colModel){
32994         if(this.loadMask){
32995             this.loadMask.destroy();
32996             this.loadMask = new Roo.LoadMask(this.container,
32997                     Roo.apply({store:dataSource}, this.loadMask));
32998         }
32999         this.view.bind(dataSource, colModel);
33000         this.dataSource = dataSource;
33001         this.colModel = colModel;
33002         this.view.refresh(true);
33003     },
33004     /**
33005      * addColumns
33006      * Add's a column, default at the end..
33007      
33008      * @param {int} position to add (default end)
33009      * @param {Array} of objects of column configuration see {@link Roo.grid.ColumnModel} 
33010      */
33011     addColumns : function(pos, ar)
33012     {
33013         
33014         for (var i =0;i< ar.length;i++) {
33015             var cfg = ar[i];
33016             cfg.id = typeof(cfg.id) == 'undefined' ? Roo.id() : cfg.id; // don't normally use this..
33017             this.cm.lookup[cfg.id] = cfg;
33018         }
33019         
33020         
33021         if (typeof(pos) == 'undefined' || pos >= this.cm.config.length) {
33022             pos = this.cm.config.length; //this.cm.config.push(cfg);
33023         } 
33024         pos = Math.max(0,pos);
33025         ar.unshift(0);
33026         ar.unshift(pos);
33027         this.cm.config.splice.apply(this.cm.config, ar);
33028         
33029         
33030         
33031         this.view.generateRules(this.cm);
33032         this.view.refresh(true);
33033         
33034     },
33035     
33036     
33037     
33038     
33039     // private
33040     onKeyDown : function(e){
33041         this.fireEvent("keydown", e);
33042     },
33043
33044     /**
33045      * Destroy this grid.
33046      * @param {Boolean} removeEl True to remove the element
33047      */
33048     destroy : function(removeEl, keepListeners){
33049         if(this.loadMask){
33050             this.loadMask.destroy();
33051         }
33052         var c = this.container;
33053         c.removeAllListeners();
33054         this.view.destroy();
33055         this.colModel.purgeListeners();
33056         if(!keepListeners){
33057             this.purgeListeners();
33058         }
33059         c.update("");
33060         if(removeEl === true){
33061             c.remove();
33062         }
33063     },
33064
33065     // private
33066     processEvent : function(name, e){
33067         // does this fire select???
33068         //Roo.log('grid:processEvent '  + name);
33069         
33070         if (name != 'touchstart' ) {
33071             this.fireEvent(name, e);    
33072         }
33073         
33074         var t = e.getTarget();
33075         var v = this.view;
33076         var header = v.findHeaderIndex(t);
33077         if(header !== false){
33078             var ename = name == 'touchstart' ? 'click' : name;
33079              
33080             this.fireEvent("header" + ename, this, header, e);
33081         }else{
33082             var row = v.findRowIndex(t);
33083             var cell = v.findCellIndex(t);
33084             if (name == 'touchstart') {
33085                 // first touch is always a click.
33086                 // hopefull this happens after selection is updated.?
33087                 name = false;
33088                 
33089                 if (typeof(this.selModel.getSelectedCell) != 'undefined') {
33090                     var cs = this.selModel.getSelectedCell();
33091                     if (row == cs[0] && cell == cs[1]){
33092                         name = 'dblclick';
33093                     }
33094                 }
33095                 if (typeof(this.selModel.getSelections) != 'undefined') {
33096                     var cs = this.selModel.getSelections();
33097                     var ds = this.dataSource;
33098                     if (cs.length == 1 && ds.getAt(row) == cs[0]){
33099                         name = 'dblclick';
33100                     }
33101                 }
33102                 if (!name) {
33103                     return;
33104                 }
33105             }
33106             
33107             
33108             if(row !== false){
33109                 this.fireEvent("row" + name, this, row, e);
33110                 if(cell !== false){
33111                     this.fireEvent("cell" + name, this, row, cell, e);
33112                 }
33113             }
33114         }
33115     },
33116
33117     // private
33118     onClick : function(e){
33119         this.processEvent("click", e);
33120     },
33121    // private
33122     onTouchStart : function(e){
33123         this.processEvent("touchstart", e);
33124     },
33125
33126     // private
33127     onContextMenu : function(e, t){
33128         this.processEvent("contextmenu", e);
33129     },
33130
33131     // private
33132     onDblClick : function(e){
33133         this.processEvent("dblclick", e);
33134     },
33135
33136     // private
33137     walkCells : function(row, col, step, fn, scope){
33138         var cm = this.colModel, clen = cm.getColumnCount();
33139         var ds = this.dataSource, rlen = ds.getCount(), first = true;
33140         if(step < 0){
33141             if(col < 0){
33142                 row--;
33143                 first = false;
33144             }
33145             while(row >= 0){
33146                 if(!first){
33147                     col = clen-1;
33148                 }
33149                 first = false;
33150                 while(col >= 0){
33151                     if(fn.call(scope || this, row, col, cm) === true){
33152                         return [row, col];
33153                     }
33154                     col--;
33155                 }
33156                 row--;
33157             }
33158         } else {
33159             if(col >= clen){
33160                 row++;
33161                 first = false;
33162             }
33163             while(row < rlen){
33164                 if(!first){
33165                     col = 0;
33166                 }
33167                 first = false;
33168                 while(col < clen){
33169                     if(fn.call(scope || this, row, col, cm) === true){
33170                         return [row, col];
33171                     }
33172                     col++;
33173                 }
33174                 row++;
33175             }
33176         }
33177         return null;
33178     },
33179
33180     // private
33181     getSelections : function(){
33182         return this.selModel.getSelections();
33183     },
33184
33185     /**
33186      * Causes the grid to manually recalculate its dimensions. Generally this is done automatically,
33187      * but if manual update is required this method will initiate it.
33188      */
33189     autoSize : function(){
33190         if(this.rendered){
33191             this.view.layout();
33192             if(this.view.adjustForScroll){
33193                 this.view.adjustForScroll();
33194             }
33195         }
33196     },
33197
33198     /**
33199      * Returns the grid's underlying element.
33200      * @return {Element} The element
33201      */
33202     getGridEl : function(){
33203         return this.container;
33204     },
33205
33206     // private for compatibility, overridden by editor grid
33207     stopEditing : function(){},
33208
33209     /**
33210      * Returns the grid's SelectionModel.
33211      * @return {SelectionModel}
33212      */
33213     getSelectionModel : function(){
33214         if(!this.selModel){
33215             this.selModel = new Roo.grid.RowSelectionModel();
33216         }
33217         return this.selModel;
33218     },
33219
33220     /**
33221      * Returns the grid's DataSource.
33222      * @return {DataSource}
33223      */
33224     getDataSource : function(){
33225         return this.dataSource;
33226     },
33227
33228     /**
33229      * Returns the grid's ColumnModel.
33230      * @return {ColumnModel}
33231      */
33232     getColumnModel : function(){
33233         return this.colModel;
33234     },
33235
33236     /**
33237      * Returns the grid's GridView object.
33238      * @return {GridView}
33239      */
33240     getView : function(){
33241         if(!this.view){
33242             this.view = new Roo.grid.GridView(this.viewConfig);
33243         }
33244         return this.view;
33245     },
33246     /**
33247      * Called to get grid's drag proxy text, by default returns this.ddText.
33248      * @return {String}
33249      */
33250     getDragDropText : function(){
33251         var count = this.selModel.getCount();
33252         return String.format(this.ddText, count, count == 1 ? '' : 's');
33253     }
33254 });
33255 /**
33256  * Configures the text is the drag proxy (defaults to "%0 selected row(s)").
33257  * %0 is replaced with the number of selected rows.
33258  * @type String
33259  */
33260 Roo.grid.Grid.prototype.ddText = "{0} selected row{1}";/*
33261  * Based on:
33262  * Ext JS Library 1.1.1
33263  * Copyright(c) 2006-2007, Ext JS, LLC.
33264  *
33265  * Originally Released Under LGPL - original licence link has changed is not relivant.
33266  *
33267  * Fork - LGPL
33268  * <script type="text/javascript">
33269  */
33270  
33271 Roo.grid.AbstractGridView = function(){
33272         this.grid = null;
33273         
33274         this.events = {
33275             "beforerowremoved" : true,
33276             "beforerowsinserted" : true,
33277             "beforerefresh" : true,
33278             "rowremoved" : true,
33279             "rowsinserted" : true,
33280             "rowupdated" : true,
33281             "refresh" : true
33282         };
33283     Roo.grid.AbstractGridView.superclass.constructor.call(this);
33284 };
33285
33286 Roo.extend(Roo.grid.AbstractGridView, Roo.util.Observable, {
33287     rowClass : "x-grid-row",
33288     cellClass : "x-grid-cell",
33289     tdClass : "x-grid-td",
33290     hdClass : "x-grid-hd",
33291     splitClass : "x-grid-hd-split",
33292     
33293     init: function(grid){
33294         this.grid = grid;
33295                 var cid = this.grid.getGridEl().id;
33296         this.colSelector = "#" + cid + " ." + this.cellClass + "-";
33297         this.tdSelector = "#" + cid + " ." + this.tdClass + "-";
33298         this.hdSelector = "#" + cid + " ." + this.hdClass + "-";
33299         this.splitSelector = "#" + cid + " ." + this.splitClass + "-";
33300         },
33301         
33302     getColumnRenderers : function(){
33303         var renderers = [];
33304         var cm = this.grid.colModel;
33305         var colCount = cm.getColumnCount();
33306         for(var i = 0; i < colCount; i++){
33307             renderers[i] = cm.getRenderer(i);
33308         }
33309         return renderers;
33310     },
33311     
33312     getColumnIds : function(){
33313         var ids = [];
33314         var cm = this.grid.colModel;
33315         var colCount = cm.getColumnCount();
33316         for(var i = 0; i < colCount; i++){
33317             ids[i] = cm.getColumnId(i);
33318         }
33319         return ids;
33320     },
33321     
33322     getDataIndexes : function(){
33323         if(!this.indexMap){
33324             this.indexMap = this.buildIndexMap();
33325         }
33326         return this.indexMap.colToData;
33327     },
33328     
33329     getColumnIndexByDataIndex : function(dataIndex){
33330         if(!this.indexMap){
33331             this.indexMap = this.buildIndexMap();
33332         }
33333         return this.indexMap.dataToCol[dataIndex];
33334     },
33335     
33336     /**
33337      * Set a css style for a column dynamically. 
33338      * @param {Number} colIndex The index of the column
33339      * @param {String} name The css property name
33340      * @param {String} value The css value
33341      */
33342     setCSSStyle : function(colIndex, name, value){
33343         var selector = "#" + this.grid.id + " .x-grid-col-" + colIndex;
33344         Roo.util.CSS.updateRule(selector, name, value);
33345     },
33346     
33347     generateRules : function(cm){
33348         var ruleBuf = [], rulesId = this.grid.id + '-cssrules';
33349         Roo.util.CSS.removeStyleSheet(rulesId);
33350         for(var i = 0, len = cm.getColumnCount(); i < len; i++){
33351             var cid = cm.getColumnId(i);
33352             ruleBuf.push(this.colSelector, cid, " {\n", cm.config[i].css, "}\n",
33353                          this.tdSelector, cid, " {\n}\n",
33354                          this.hdSelector, cid, " {\n}\n",
33355                          this.splitSelector, cid, " {\n}\n");
33356         }
33357         return Roo.util.CSS.createStyleSheet(ruleBuf.join(""), rulesId);
33358     }
33359 });/*
33360  * Based on:
33361  * Ext JS Library 1.1.1
33362  * Copyright(c) 2006-2007, Ext JS, LLC.
33363  *
33364  * Originally Released Under LGPL - original licence link has changed is not relivant.
33365  *
33366  * Fork - LGPL
33367  * <script type="text/javascript">
33368  */
33369
33370 // private
33371 // This is a support class used internally by the Grid components
33372 Roo.grid.HeaderDragZone = function(grid, hd, hd2){
33373     this.grid = grid;
33374     this.view = grid.getView();
33375     this.ddGroup = "gridHeader" + this.grid.getGridEl().id;
33376     Roo.grid.HeaderDragZone.superclass.constructor.call(this, hd);
33377     if(hd2){
33378         this.setHandleElId(Roo.id(hd));
33379         this.setOuterHandleElId(Roo.id(hd2));
33380     }
33381     this.scroll = false;
33382 };
33383 Roo.extend(Roo.grid.HeaderDragZone, Roo.dd.DragZone, {
33384     maxDragWidth: 120,
33385     getDragData : function(e){
33386         var t = Roo.lib.Event.getTarget(e);
33387         var h = this.view.findHeaderCell(t);
33388         if(h){
33389             return {ddel: h.firstChild, header:h};
33390         }
33391         return false;
33392     },
33393
33394     onInitDrag : function(e){
33395         this.view.headersDisabled = true;
33396         var clone = this.dragData.ddel.cloneNode(true);
33397         clone.id = Roo.id();
33398         clone.style.width = Math.min(this.dragData.header.offsetWidth,this.maxDragWidth) + "px";
33399         this.proxy.update(clone);
33400         return true;
33401     },
33402
33403     afterValidDrop : function(){
33404         var v = this.view;
33405         setTimeout(function(){
33406             v.headersDisabled = false;
33407         }, 50);
33408     },
33409
33410     afterInvalidDrop : function(){
33411         var v = this.view;
33412         setTimeout(function(){
33413             v.headersDisabled = false;
33414         }, 50);
33415     }
33416 });
33417 /*
33418  * Based on:
33419  * Ext JS Library 1.1.1
33420  * Copyright(c) 2006-2007, Ext JS, LLC.
33421  *
33422  * Originally Released Under LGPL - original licence link has changed is not relivant.
33423  *
33424  * Fork - LGPL
33425  * <script type="text/javascript">
33426  */
33427 // private
33428 // This is a support class used internally by the Grid components
33429 Roo.grid.HeaderDropZone = function(grid, hd, hd2){
33430     this.grid = grid;
33431     this.view = grid.getView();
33432     // split the proxies so they don't interfere with mouse events
33433     this.proxyTop = Roo.DomHelper.append(document.body, {
33434         cls:"col-move-top", html:"&#160;"
33435     }, true);
33436     this.proxyBottom = Roo.DomHelper.append(document.body, {
33437         cls:"col-move-bottom", html:"&#160;"
33438     }, true);
33439     this.proxyTop.hide = this.proxyBottom.hide = function(){
33440         this.setLeftTop(-100,-100);
33441         this.setStyle("visibility", "hidden");
33442     };
33443     this.ddGroup = "gridHeader" + this.grid.getGridEl().id;
33444     // temporarily disabled
33445     //Roo.dd.ScrollManager.register(this.view.scroller.dom);
33446     Roo.grid.HeaderDropZone.superclass.constructor.call(this, grid.getGridEl().dom);
33447 };
33448 Roo.extend(Roo.grid.HeaderDropZone, Roo.dd.DropZone, {
33449     proxyOffsets : [-4, -9],
33450     fly: Roo.Element.fly,
33451
33452     getTargetFromEvent : function(e){
33453         var t = Roo.lib.Event.getTarget(e);
33454         var cindex = this.view.findCellIndex(t);
33455         if(cindex !== false){
33456             return this.view.getHeaderCell(cindex);
33457         }
33458         return null;
33459     },
33460
33461     nextVisible : function(h){
33462         var v = this.view, cm = this.grid.colModel;
33463         h = h.nextSibling;
33464         while(h){
33465             if(!cm.isHidden(v.getCellIndex(h))){
33466                 return h;
33467             }
33468             h = h.nextSibling;
33469         }
33470         return null;
33471     },
33472
33473     prevVisible : function(h){
33474         var v = this.view, cm = this.grid.colModel;
33475         h = h.prevSibling;
33476         while(h){
33477             if(!cm.isHidden(v.getCellIndex(h))){
33478                 return h;
33479             }
33480             h = h.prevSibling;
33481         }
33482         return null;
33483     },
33484
33485     positionIndicator : function(h, n, e){
33486         var x = Roo.lib.Event.getPageX(e);
33487         var r = Roo.lib.Dom.getRegion(n.firstChild);
33488         var px, pt, py = r.top + this.proxyOffsets[1];
33489         if((r.right - x) <= (r.right-r.left)/2){
33490             px = r.right+this.view.borderWidth;
33491             pt = "after";
33492         }else{
33493             px = r.left;
33494             pt = "before";
33495         }
33496         var oldIndex = this.view.getCellIndex(h);
33497         var newIndex = this.view.getCellIndex(n);
33498
33499         if(this.grid.colModel.isFixed(newIndex)){
33500             return false;
33501         }
33502
33503         var locked = this.grid.colModel.isLocked(newIndex);
33504
33505         if(pt == "after"){
33506             newIndex++;
33507         }
33508         if(oldIndex < newIndex){
33509             newIndex--;
33510         }
33511         if(oldIndex == newIndex && (locked == this.grid.colModel.isLocked(oldIndex))){
33512             return false;
33513         }
33514         px +=  this.proxyOffsets[0];
33515         this.proxyTop.setLeftTop(px, py);
33516         this.proxyTop.show();
33517         if(!this.bottomOffset){
33518             this.bottomOffset = this.view.mainHd.getHeight();
33519         }
33520         this.proxyBottom.setLeftTop(px, py+this.proxyTop.dom.offsetHeight+this.bottomOffset);
33521         this.proxyBottom.show();
33522         return pt;
33523     },
33524
33525     onNodeEnter : function(n, dd, e, data){
33526         if(data.header != n){
33527             this.positionIndicator(data.header, n, e);
33528         }
33529     },
33530
33531     onNodeOver : function(n, dd, e, data){
33532         var result = false;
33533         if(data.header != n){
33534             result = this.positionIndicator(data.header, n, e);
33535         }
33536         if(!result){
33537             this.proxyTop.hide();
33538             this.proxyBottom.hide();
33539         }
33540         return result ? this.dropAllowed : this.dropNotAllowed;
33541     },
33542
33543     onNodeOut : function(n, dd, e, data){
33544         this.proxyTop.hide();
33545         this.proxyBottom.hide();
33546     },
33547
33548     onNodeDrop : function(n, dd, e, data){
33549         var h = data.header;
33550         if(h != n){
33551             var cm = this.grid.colModel;
33552             var x = Roo.lib.Event.getPageX(e);
33553             var r = Roo.lib.Dom.getRegion(n.firstChild);
33554             var pt = (r.right - x) <= ((r.right-r.left)/2) ? "after" : "before";
33555             var oldIndex = this.view.getCellIndex(h);
33556             var newIndex = this.view.getCellIndex(n);
33557             var locked = cm.isLocked(newIndex);
33558             if(pt == "after"){
33559                 newIndex++;
33560             }
33561             if(oldIndex < newIndex){
33562                 newIndex--;
33563             }
33564             if(oldIndex == newIndex && (locked == cm.isLocked(oldIndex))){
33565                 return false;
33566             }
33567             cm.setLocked(oldIndex, locked, true);
33568             cm.moveColumn(oldIndex, newIndex);
33569             this.grid.fireEvent("columnmove", oldIndex, newIndex);
33570             return true;
33571         }
33572         return false;
33573     }
33574 });
33575 /*
33576  * Based on:
33577  * Ext JS Library 1.1.1
33578  * Copyright(c) 2006-2007, Ext JS, LLC.
33579  *
33580  * Originally Released Under LGPL - original licence link has changed is not relivant.
33581  *
33582  * Fork - LGPL
33583  * <script type="text/javascript">
33584  */
33585   
33586 /**
33587  * @class Roo.grid.GridView
33588  * @extends Roo.util.Observable
33589  *
33590  * @constructor
33591  * @param {Object} config
33592  */
33593 Roo.grid.GridView = function(config){
33594     Roo.grid.GridView.superclass.constructor.call(this);
33595     this.el = null;
33596
33597     Roo.apply(this, config);
33598 };
33599
33600 Roo.extend(Roo.grid.GridView, Roo.grid.AbstractGridView, {
33601
33602     unselectable :  'unselectable="on"',
33603     unselectableCls :  'x-unselectable',
33604     
33605     
33606     rowClass : "x-grid-row",
33607
33608     cellClass : "x-grid-col",
33609
33610     tdClass : "x-grid-td",
33611
33612     hdClass : "x-grid-hd",
33613
33614     splitClass : "x-grid-split",
33615
33616     sortClasses : ["sort-asc", "sort-desc"],
33617
33618     enableMoveAnim : false,
33619
33620     hlColor: "C3DAF9",
33621
33622     dh : Roo.DomHelper,
33623
33624     fly : Roo.Element.fly,
33625
33626     css : Roo.util.CSS,
33627
33628     borderWidth: 1,
33629
33630     splitOffset: 3,
33631
33632     scrollIncrement : 22,
33633
33634     cellRE: /(?:.*?)x-grid-(?:hd|cell|csplit)-(?:[\d]+)-([\d]+)(?:.*?)/,
33635
33636     findRE: /\s?(?:x-grid-hd|x-grid-col|x-grid-csplit)\s/,
33637
33638     bind : function(ds, cm){
33639         if(this.ds){
33640             this.ds.un("load", this.onLoad, this);
33641             this.ds.un("datachanged", this.onDataChange, this);
33642             this.ds.un("add", this.onAdd, this);
33643             this.ds.un("remove", this.onRemove, this);
33644             this.ds.un("update", this.onUpdate, this);
33645             this.ds.un("clear", this.onClear, this);
33646         }
33647         if(ds){
33648             ds.on("load", this.onLoad, this);
33649             ds.on("datachanged", this.onDataChange, this);
33650             ds.on("add", this.onAdd, this);
33651             ds.on("remove", this.onRemove, this);
33652             ds.on("update", this.onUpdate, this);
33653             ds.on("clear", this.onClear, this);
33654         }
33655         this.ds = ds;
33656
33657         if(this.cm){
33658             this.cm.un("widthchange", this.onColWidthChange, this);
33659             this.cm.un("headerchange", this.onHeaderChange, this);
33660             this.cm.un("hiddenchange", this.onHiddenChange, this);
33661             this.cm.un("columnmoved", this.onColumnMove, this);
33662             this.cm.un("columnlockchange", this.onColumnLock, this);
33663         }
33664         if(cm){
33665             this.generateRules(cm);
33666             cm.on("widthchange", this.onColWidthChange, this);
33667             cm.on("headerchange", this.onHeaderChange, this);
33668             cm.on("hiddenchange", this.onHiddenChange, this);
33669             cm.on("columnmoved", this.onColumnMove, this);
33670             cm.on("columnlockchange", this.onColumnLock, this);
33671         }
33672         this.cm = cm;
33673     },
33674
33675     init: function(grid){
33676         Roo.grid.GridView.superclass.init.call(this, grid);
33677
33678         this.bind(grid.dataSource, grid.colModel);
33679
33680         grid.on("headerclick", this.handleHeaderClick, this);
33681
33682         if(grid.trackMouseOver){
33683             grid.on("mouseover", this.onRowOver, this);
33684             grid.on("mouseout", this.onRowOut, this);
33685         }
33686         grid.cancelTextSelection = function(){};
33687         this.gridId = grid.id;
33688
33689         var tpls = this.templates || {};
33690
33691         if(!tpls.master){
33692             tpls.master = new Roo.Template(
33693                '<div class="x-grid" hidefocus="true">',
33694                 '<a href="#" class="x-grid-focus" tabIndex="-1"></a>',
33695                   '<div class="x-grid-topbar"></div>',
33696                   '<div class="x-grid-scroller"><div></div></div>',
33697                   '<div class="x-grid-locked">',
33698                       '<div class="x-grid-header">{lockedHeader}</div>',
33699                       '<div class="x-grid-body">{lockedBody}</div>',
33700                   "</div>",
33701                   '<div class="x-grid-viewport">',
33702                       '<div class="x-grid-header">{header}</div>',
33703                       '<div class="x-grid-body">{body}</div>',
33704                   "</div>",
33705                   '<div class="x-grid-bottombar"></div>',
33706                  
33707                   '<div class="x-grid-resize-proxy">&#160;</div>',
33708                "</div>"
33709             );
33710             tpls.master.disableformats = true;
33711         }
33712
33713         if(!tpls.header){
33714             tpls.header = new Roo.Template(
33715                '<table border="0" cellspacing="0" cellpadding="0">',
33716                '<tbody><tr class="x-grid-hd-row">{cells}</tr></tbody>',
33717                "</table>{splits}"
33718             );
33719             tpls.header.disableformats = true;
33720         }
33721         tpls.header.compile();
33722
33723         if(!tpls.hcell){
33724             tpls.hcell = new Roo.Template(
33725                 '<td class="x-grid-hd x-grid-td-{id} {cellId}"><div title="{title}" class="x-grid-hd-inner x-grid-hd-{id}">',
33726                 '<div class="x-grid-hd-text ' + this.unselectableCls +  '" ' + this.unselectable +'>{value}<img class="x-grid-sort-icon" src="', Roo.BLANK_IMAGE_URL, '" /></div>',
33727                 "</div></td>"
33728              );
33729              tpls.hcell.disableFormats = true;
33730         }
33731         tpls.hcell.compile();
33732
33733         if(!tpls.hsplit){
33734             tpls.hsplit = new Roo.Template('<div class="x-grid-split {splitId} x-grid-split-{id}" style="{style} ' +
33735                                             this.unselectableCls +  '" ' + this.unselectable +'>&#160;</div>');
33736             tpls.hsplit.disableFormats = true;
33737         }
33738         tpls.hsplit.compile();
33739
33740         if(!tpls.body){
33741             tpls.body = new Roo.Template(
33742                '<table border="0" cellspacing="0" cellpadding="0">',
33743                "<tbody>{rows}</tbody>",
33744                "</table>"
33745             );
33746             tpls.body.disableFormats = true;
33747         }
33748         tpls.body.compile();
33749
33750         if(!tpls.row){
33751             tpls.row = new Roo.Template('<tr class="x-grid-row {alt}">{cells}</tr>');
33752             tpls.row.disableFormats = true;
33753         }
33754         tpls.row.compile();
33755
33756         if(!tpls.cell){
33757             tpls.cell = new Roo.Template(
33758                 '<td class="x-grid-col x-grid-td-{id} {cellId} {css}" tabIndex="0">',
33759                 '<div class="x-grid-col-{id} x-grid-cell-inner"><div class="x-grid-cell-text ' +
33760                     this.unselectableCls +  '" ' + this.unselectable +'" {attr}>{value}</div></div>',
33761                 "</td>"
33762             );
33763             tpls.cell.disableFormats = true;
33764         }
33765         tpls.cell.compile();
33766
33767         this.templates = tpls;
33768     },
33769
33770     // remap these for backwards compat
33771     onColWidthChange : function(){
33772         this.updateColumns.apply(this, arguments);
33773     },
33774     onHeaderChange : function(){
33775         this.updateHeaders.apply(this, arguments);
33776     }, 
33777     onHiddenChange : function(){
33778         this.handleHiddenChange.apply(this, arguments);
33779     },
33780     onColumnMove : function(){
33781         this.handleColumnMove.apply(this, arguments);
33782     },
33783     onColumnLock : function(){
33784         this.handleLockChange.apply(this, arguments);
33785     },
33786
33787     onDataChange : function(){
33788         this.refresh();
33789         this.updateHeaderSortState();
33790     },
33791
33792     onClear : function(){
33793         this.refresh();
33794     },
33795
33796     onUpdate : function(ds, record){
33797         this.refreshRow(record);
33798     },
33799
33800     refreshRow : function(record){
33801         var ds = this.ds, index;
33802         if(typeof record == 'number'){
33803             index = record;
33804             record = ds.getAt(index);
33805         }else{
33806             index = ds.indexOf(record);
33807         }
33808         this.insertRows(ds, index, index, true);
33809         this.onRemove(ds, record, index+1, true);
33810         this.syncRowHeights(index, index);
33811         this.layout();
33812         this.fireEvent("rowupdated", this, index, record);
33813     },
33814
33815     onAdd : function(ds, records, index){
33816         this.insertRows(ds, index, index + (records.length-1));
33817     },
33818
33819     onRemove : function(ds, record, index, isUpdate){
33820         if(isUpdate !== true){
33821             this.fireEvent("beforerowremoved", this, index, record);
33822         }
33823         var bt = this.getBodyTable(), lt = this.getLockedTable();
33824         if(bt.rows[index]){
33825             bt.firstChild.removeChild(bt.rows[index]);
33826         }
33827         if(lt.rows[index]){
33828             lt.firstChild.removeChild(lt.rows[index]);
33829         }
33830         if(isUpdate !== true){
33831             this.stripeRows(index);
33832             this.syncRowHeights(index, index);
33833             this.layout();
33834             this.fireEvent("rowremoved", this, index, record);
33835         }
33836     },
33837
33838     onLoad : function(){
33839         this.scrollToTop();
33840     },
33841
33842     /**
33843      * Scrolls the grid to the top
33844      */
33845     scrollToTop : function(){
33846         if(this.scroller){
33847             this.scroller.dom.scrollTop = 0;
33848             this.syncScroll();
33849         }
33850     },
33851
33852     /**
33853      * Gets a panel in the header of the grid that can be used for toolbars etc.
33854      * After modifying the contents of this panel a call to grid.autoSize() may be
33855      * required to register any changes in size.
33856      * @param {Boolean} doShow By default the header is hidden. Pass true to show the panel
33857      * @return Roo.Element
33858      */
33859     getHeaderPanel : function(doShow){
33860         if(doShow){
33861             this.headerPanel.show();
33862         }
33863         return this.headerPanel;
33864     },
33865
33866     /**
33867      * Gets a panel in the footer of the grid that can be used for toolbars etc.
33868      * After modifying the contents of this panel a call to grid.autoSize() may be
33869      * required to register any changes in size.
33870      * @param {Boolean} doShow By default the footer is hidden. Pass true to show the panel
33871      * @return Roo.Element
33872      */
33873     getFooterPanel : function(doShow){
33874         if(doShow){
33875             this.footerPanel.show();
33876         }
33877         return this.footerPanel;
33878     },
33879
33880     initElements : function(){
33881         var E = Roo.Element;
33882         var el = this.grid.getGridEl().dom.firstChild;
33883         var cs = el.childNodes;
33884
33885         this.el = new E(el);
33886         
33887          this.focusEl = new E(el.firstChild);
33888         this.focusEl.swallowEvent("click", true);
33889         
33890         this.headerPanel = new E(cs[1]);
33891         this.headerPanel.enableDisplayMode("block");
33892
33893         this.scroller = new E(cs[2]);
33894         this.scrollSizer = new E(this.scroller.dom.firstChild);
33895
33896         this.lockedWrap = new E(cs[3]);
33897         this.lockedHd = new E(this.lockedWrap.dom.firstChild);
33898         this.lockedBody = new E(this.lockedWrap.dom.childNodes[1]);
33899
33900         this.mainWrap = new E(cs[4]);
33901         this.mainHd = new E(this.mainWrap.dom.firstChild);
33902         this.mainBody = new E(this.mainWrap.dom.childNodes[1]);
33903
33904         this.footerPanel = new E(cs[5]);
33905         this.footerPanel.enableDisplayMode("block");
33906
33907         this.resizeProxy = new E(cs[6]);
33908
33909         this.headerSelector = String.format(
33910            '#{0} td.x-grid-hd, #{1} td.x-grid-hd',
33911            this.lockedHd.id, this.mainHd.id
33912         );
33913
33914         this.splitterSelector = String.format(
33915            '#{0} div.x-grid-split, #{1} div.x-grid-split',
33916            this.idToCssName(this.lockedHd.id), this.idToCssName(this.mainHd.id)
33917         );
33918     },
33919     idToCssName : function(s)
33920     {
33921         return s.replace(/[^a-z0-9]+/ig, '-');
33922     },
33923
33924     getHeaderCell : function(index){
33925         return Roo.DomQuery.select(this.headerSelector)[index];
33926     },
33927
33928     getHeaderCellMeasure : function(index){
33929         return this.getHeaderCell(index).firstChild;
33930     },
33931
33932     getHeaderCellText : function(index){
33933         return this.getHeaderCell(index).firstChild.firstChild;
33934     },
33935
33936     getLockedTable : function(){
33937         return this.lockedBody.dom.firstChild;
33938     },
33939
33940     getBodyTable : function(){
33941         return this.mainBody.dom.firstChild;
33942     },
33943
33944     getLockedRow : function(index){
33945         return this.getLockedTable().rows[index];
33946     },
33947
33948     getRow : function(index){
33949         return this.getBodyTable().rows[index];
33950     },
33951
33952     getRowComposite : function(index){
33953         if(!this.rowEl){
33954             this.rowEl = new Roo.CompositeElementLite();
33955         }
33956         var els = [], lrow, mrow;
33957         if(lrow = this.getLockedRow(index)){
33958             els.push(lrow);
33959         }
33960         if(mrow = this.getRow(index)){
33961             els.push(mrow);
33962         }
33963         this.rowEl.elements = els;
33964         return this.rowEl;
33965     },
33966     /**
33967      * Gets the 'td' of the cell
33968      * 
33969      * @param {Integer} rowIndex row to select
33970      * @param {Integer} colIndex column to select
33971      * 
33972      * @return {Object} 
33973      */
33974     getCell : function(rowIndex, colIndex){
33975         var locked = this.cm.getLockedCount();
33976         var source;
33977         if(colIndex < locked){
33978             source = this.lockedBody.dom.firstChild;
33979         }else{
33980             source = this.mainBody.dom.firstChild;
33981             colIndex -= locked;
33982         }
33983         return source.rows[rowIndex].childNodes[colIndex];
33984     },
33985
33986     getCellText : function(rowIndex, colIndex){
33987         return this.getCell(rowIndex, colIndex).firstChild.firstChild;
33988     },
33989
33990     getCellBox : function(cell){
33991         var b = this.fly(cell).getBox();
33992         if(Roo.isOpera){ // opera fails to report the Y
33993             b.y = cell.offsetTop + this.mainBody.getY();
33994         }
33995         return b;
33996     },
33997
33998     getCellIndex : function(cell){
33999         var id = String(cell.className).match(this.cellRE);
34000         if(id){
34001             return parseInt(id[1], 10);
34002         }
34003         return 0;
34004     },
34005
34006     findHeaderIndex : function(n){
34007         var r = Roo.fly(n).findParent("td." + this.hdClass, 6);
34008         return r ? this.getCellIndex(r) : false;
34009     },
34010
34011     findHeaderCell : function(n){
34012         var r = Roo.fly(n).findParent("td." + this.hdClass, 6);
34013         return r ? r : false;
34014     },
34015
34016     findRowIndex : function(n){
34017         if(!n){
34018             return false;
34019         }
34020         var r = Roo.fly(n).findParent("tr." + this.rowClass, 6);
34021         return r ? r.rowIndex : false;
34022     },
34023
34024     findCellIndex : function(node){
34025         var stop = this.el.dom;
34026         while(node && node != stop){
34027             if(this.findRE.test(node.className)){
34028                 return this.getCellIndex(node);
34029             }
34030             node = node.parentNode;
34031         }
34032         return false;
34033     },
34034
34035     getColumnId : function(index){
34036         return this.cm.getColumnId(index);
34037     },
34038
34039     getSplitters : function()
34040     {
34041         if(this.splitterSelector){
34042            return Roo.DomQuery.select(this.splitterSelector);
34043         }else{
34044             return null;
34045       }
34046     },
34047
34048     getSplitter : function(index){
34049         return this.getSplitters()[index];
34050     },
34051
34052     onRowOver : function(e, t){
34053         var row;
34054         if((row = this.findRowIndex(t)) !== false){
34055             this.getRowComposite(row).addClass("x-grid-row-over");
34056         }
34057     },
34058
34059     onRowOut : function(e, t){
34060         var row;
34061         if((row = this.findRowIndex(t)) !== false && row !== this.findRowIndex(e.getRelatedTarget())){
34062             this.getRowComposite(row).removeClass("x-grid-row-over");
34063         }
34064     },
34065
34066     renderHeaders : function(){
34067         var cm = this.cm;
34068         var ct = this.templates.hcell, ht = this.templates.header, st = this.templates.hsplit;
34069         var cb = [], lb = [], sb = [], lsb = [], p = {};
34070         for(var i = 0, len = cm.getColumnCount(); i < len; i++){
34071             p.cellId = "x-grid-hd-0-" + i;
34072             p.splitId = "x-grid-csplit-0-" + i;
34073             p.id = cm.getColumnId(i);
34074             p.value = cm.getColumnHeader(i) || "";
34075             p.title = cm.getColumnTooltip(i) || (''+p.value).match(/\</)  ? '' :  p.value  || "";
34076             p.style = (this.grid.enableColumnResize === false || !cm.isResizable(i) || cm.isFixed(i)) ? 'cursor:default' : '';
34077             if(!cm.isLocked(i)){
34078                 cb[cb.length] = ct.apply(p);
34079                 sb[sb.length] = st.apply(p);
34080             }else{
34081                 lb[lb.length] = ct.apply(p);
34082                 lsb[lsb.length] = st.apply(p);
34083             }
34084         }
34085         return [ht.apply({cells: lb.join(""), splits:lsb.join("")}),
34086                 ht.apply({cells: cb.join(""), splits:sb.join("")})];
34087     },
34088
34089     updateHeaders : function(){
34090         var html = this.renderHeaders();
34091         this.lockedHd.update(html[0]);
34092         this.mainHd.update(html[1]);
34093     },
34094
34095     /**
34096      * Focuses the specified row.
34097      * @param {Number} row The row index
34098      */
34099     focusRow : function(row)
34100     {
34101         //Roo.log('GridView.focusRow');
34102         var x = this.scroller.dom.scrollLeft;
34103         this.focusCell(row, 0, false);
34104         this.scroller.dom.scrollLeft = x;
34105     },
34106
34107     /**
34108      * Focuses the specified cell.
34109      * @param {Number} row The row index
34110      * @param {Number} col The column index
34111      * @param {Boolean} hscroll false to disable horizontal scrolling
34112      */
34113     focusCell : function(row, col, hscroll)
34114     {
34115         //Roo.log('GridView.focusCell');
34116         var el = this.ensureVisible(row, col, hscroll);
34117         this.focusEl.alignTo(el, "tl-tl");
34118         if(Roo.isGecko){
34119             this.focusEl.focus();
34120         }else{
34121             this.focusEl.focus.defer(1, this.focusEl);
34122         }
34123     },
34124
34125     /**
34126      * Scrolls the specified cell into view
34127      * @param {Number} row The row index
34128      * @param {Number} col The column index
34129      * @param {Boolean} hscroll false to disable horizontal scrolling
34130      */
34131     ensureVisible : function(row, col, hscroll)
34132     {
34133         //Roo.log('GridView.ensureVisible,' + row + ',' + col);
34134         //return null; //disable for testing.
34135         if(typeof row != "number"){
34136             row = row.rowIndex;
34137         }
34138         if(row < 0 && row >= this.ds.getCount()){
34139             return  null;
34140         }
34141         col = (col !== undefined ? col : 0);
34142         var cm = this.grid.colModel;
34143         while(cm.isHidden(col)){
34144             col++;
34145         }
34146
34147         var el = this.getCell(row, col);
34148         if(!el){
34149             return null;
34150         }
34151         var c = this.scroller.dom;
34152
34153         var ctop = parseInt(el.offsetTop, 10);
34154         var cleft = parseInt(el.offsetLeft, 10);
34155         var cbot = ctop + el.offsetHeight;
34156         var cright = cleft + el.offsetWidth;
34157         
34158         var ch = c.clientHeight - this.mainHd.dom.offsetHeight;
34159         var stop = parseInt(c.scrollTop, 10);
34160         var sleft = parseInt(c.scrollLeft, 10);
34161         var sbot = stop + ch;
34162         var sright = sleft + c.clientWidth;
34163         /*
34164         Roo.log('GridView.ensureVisible:' +
34165                 ' ctop:' + ctop +
34166                 ' c.clientHeight:' + c.clientHeight +
34167                 ' this.mainHd.dom.offsetHeight:' + this.mainHd.dom.offsetHeight +
34168                 ' stop:' + stop +
34169                 ' cbot:' + cbot +
34170                 ' sbot:' + sbot +
34171                 ' ch:' + ch  
34172                 );
34173         */
34174         if(ctop < stop){
34175              c.scrollTop = ctop;
34176             //Roo.log("set scrolltop to ctop DISABLE?");
34177         }else if(cbot > sbot){
34178             //Roo.log("set scrolltop to cbot-ch");
34179             c.scrollTop = cbot-ch;
34180         }
34181         
34182         if(hscroll !== false){
34183             if(cleft < sleft){
34184                 c.scrollLeft = cleft;
34185             }else if(cright > sright){
34186                 c.scrollLeft = cright-c.clientWidth;
34187             }
34188         }
34189          
34190         return el;
34191     },
34192
34193     updateColumns : function(){
34194         this.grid.stopEditing();
34195         var cm = this.grid.colModel, colIds = this.getColumnIds();
34196         //var totalWidth = cm.getTotalWidth();
34197         var pos = 0;
34198         for(var i = 0, len = cm.getColumnCount(); i < len; i++){
34199             //if(cm.isHidden(i)) continue;
34200             var w = cm.getColumnWidth(i);
34201             this.css.updateRule(this.colSelector+this.idToCssName(colIds[i]), "width", (w - this.borderWidth) + "px");
34202             this.css.updateRule(this.hdSelector+this.idToCssName(colIds[i]), "width", (w - this.borderWidth) + "px");
34203         }
34204         this.updateSplitters();
34205     },
34206
34207     generateRules : function(cm){
34208         var ruleBuf = [], rulesId = this.idToCssName(this.grid.id)+ '-cssrules';
34209         Roo.util.CSS.removeStyleSheet(rulesId);
34210         for(var i = 0, len = cm.getColumnCount(); i < len; i++){
34211             var cid = cm.getColumnId(i);
34212             var align = '';
34213             if(cm.config[i].align){
34214                 align = 'text-align:'+cm.config[i].align+';';
34215             }
34216             var hidden = '';
34217             if(cm.isHidden(i)){
34218                 hidden = 'display:none;';
34219             }
34220             var width = "width:" + (cm.getColumnWidth(i) - this.borderWidth) + "px;";
34221             ruleBuf.push(
34222                     this.colSelector, cid, " {\n", cm.config[i].css, align, width, "\n}\n",
34223                     this.hdSelector, cid, " {\n", align, width, "}\n",
34224                     this.tdSelector, cid, " {\n",hidden,"\n}\n",
34225                     this.splitSelector, cid, " {\n", hidden , "\n}\n");
34226         }
34227         return Roo.util.CSS.createStyleSheet(ruleBuf.join(""), rulesId);
34228     },
34229
34230     updateSplitters : function(){
34231         var cm = this.cm, s = this.getSplitters();
34232         if(s){ // splitters not created yet
34233             var pos = 0, locked = true;
34234             for(var i = 0, len = cm.getColumnCount(); i < len; i++){
34235                 if(cm.isHidden(i)) {
34236                     continue;
34237                 }
34238                 var w = cm.getColumnWidth(i); // make sure it's a number
34239                 if(!cm.isLocked(i) && locked){
34240                     pos = 0;
34241                     locked = false;
34242                 }
34243                 pos += w;
34244                 s[i].style.left = (pos-this.splitOffset) + "px";
34245             }
34246         }
34247     },
34248
34249     handleHiddenChange : function(colModel, colIndex, hidden){
34250         if(hidden){
34251             this.hideColumn(colIndex);
34252         }else{
34253             this.unhideColumn(colIndex);
34254         }
34255     },
34256
34257     hideColumn : function(colIndex){
34258         var cid = this.getColumnId(colIndex);
34259         this.css.updateRule(this.tdSelector+this.idToCssName(cid), "display", "none");
34260         this.css.updateRule(this.splitSelector+this.idToCssName(cid), "display", "none");
34261         if(Roo.isSafari){
34262             this.updateHeaders();
34263         }
34264         this.updateSplitters();
34265         this.layout();
34266     },
34267
34268     unhideColumn : function(colIndex){
34269         var cid = this.getColumnId(colIndex);
34270         this.css.updateRule(this.tdSelector+this.idToCssName(cid), "display", "");
34271         this.css.updateRule(this.splitSelector+this.idToCssName(cid), "display", "");
34272
34273         if(Roo.isSafari){
34274             this.updateHeaders();
34275         }
34276         this.updateSplitters();
34277         this.layout();
34278     },
34279
34280     insertRows : function(dm, firstRow, lastRow, isUpdate){
34281         if(firstRow == 0 && lastRow == dm.getCount()-1){
34282             this.refresh();
34283         }else{
34284             if(!isUpdate){
34285                 this.fireEvent("beforerowsinserted", this, firstRow, lastRow);
34286             }
34287             var s = this.getScrollState();
34288             var markup = this.renderRows(firstRow, lastRow);
34289             this.bufferRows(markup[0], this.getLockedTable(), firstRow);
34290             this.bufferRows(markup[1], this.getBodyTable(), firstRow);
34291             this.restoreScroll(s);
34292             if(!isUpdate){
34293                 this.fireEvent("rowsinserted", this, firstRow, lastRow);
34294                 this.syncRowHeights(firstRow, lastRow);
34295                 this.stripeRows(firstRow);
34296                 this.layout();
34297             }
34298         }
34299     },
34300
34301     bufferRows : function(markup, target, index){
34302         var before = null, trows = target.rows, tbody = target.tBodies[0];
34303         if(index < trows.length){
34304             before = trows[index];
34305         }
34306         var b = document.createElement("div");
34307         b.innerHTML = "<table><tbody>"+markup+"</tbody></table>";
34308         var rows = b.firstChild.rows;
34309         for(var i = 0, len = rows.length; i < len; i++){
34310             if(before){
34311                 tbody.insertBefore(rows[0], before);
34312             }else{
34313                 tbody.appendChild(rows[0]);
34314             }
34315         }
34316         b.innerHTML = "";
34317         b = null;
34318     },
34319
34320     deleteRows : function(dm, firstRow, lastRow){
34321         if(dm.getRowCount()<1){
34322             this.fireEvent("beforerefresh", this);
34323             this.mainBody.update("");
34324             this.lockedBody.update("");
34325             this.fireEvent("refresh", this);
34326         }else{
34327             this.fireEvent("beforerowsdeleted", this, firstRow, lastRow);
34328             var bt = this.getBodyTable();
34329             var tbody = bt.firstChild;
34330             var rows = bt.rows;
34331             for(var rowIndex = firstRow; rowIndex <= lastRow; rowIndex++){
34332                 tbody.removeChild(rows[firstRow]);
34333             }
34334             this.stripeRows(firstRow);
34335             this.fireEvent("rowsdeleted", this, firstRow, lastRow);
34336         }
34337     },
34338
34339     updateRows : function(dataSource, firstRow, lastRow){
34340         var s = this.getScrollState();
34341         this.refresh();
34342         this.restoreScroll(s);
34343     },
34344
34345     handleSort : function(dataSource, sortColumnIndex, sortDir, noRefresh){
34346         if(!noRefresh){
34347            this.refresh();
34348         }
34349         this.updateHeaderSortState();
34350     },
34351
34352     getScrollState : function(){
34353         
34354         var sb = this.scroller.dom;
34355         return {left: sb.scrollLeft, top: sb.scrollTop};
34356     },
34357
34358     stripeRows : function(startRow){
34359         if(!this.grid.stripeRows || this.ds.getCount() < 1){
34360             return;
34361         }
34362         startRow = startRow || 0;
34363         var rows = this.getBodyTable().rows;
34364         var lrows = this.getLockedTable().rows;
34365         var cls = ' x-grid-row-alt ';
34366         for(var i = startRow, len = rows.length; i < len; i++){
34367             var row = rows[i], lrow = lrows[i];
34368             var isAlt = ((i+1) % 2 == 0);
34369             var hasAlt = (' '+row.className + ' ').indexOf(cls) != -1;
34370             if(isAlt == hasAlt){
34371                 continue;
34372             }
34373             if(isAlt){
34374                 row.className += " x-grid-row-alt";
34375             }else{
34376                 row.className = row.className.replace("x-grid-row-alt", "");
34377             }
34378             if(lrow){
34379                 lrow.className = row.className;
34380             }
34381         }
34382     },
34383
34384     restoreScroll : function(state){
34385         //Roo.log('GridView.restoreScroll');
34386         var sb = this.scroller.dom;
34387         sb.scrollLeft = state.left;
34388         sb.scrollTop = state.top;
34389         this.syncScroll();
34390     },
34391
34392     syncScroll : function(){
34393         //Roo.log('GridView.syncScroll');
34394         var sb = this.scroller.dom;
34395         var sh = this.mainHd.dom;
34396         var bs = this.mainBody.dom;
34397         var lv = this.lockedBody.dom;
34398         sh.scrollLeft = bs.scrollLeft = sb.scrollLeft;
34399         lv.scrollTop = bs.scrollTop = sb.scrollTop;
34400     },
34401
34402     handleScroll : function(e){
34403         this.syncScroll();
34404         var sb = this.scroller.dom;
34405         this.grid.fireEvent("bodyscroll", sb.scrollLeft, sb.scrollTop);
34406         e.stopEvent();
34407     },
34408
34409     handleWheel : function(e){
34410         var d = e.getWheelDelta();
34411         this.scroller.dom.scrollTop -= d*22;
34412         // set this here to prevent jumpy scrolling on large tables
34413         this.lockedBody.dom.scrollTop = this.mainBody.dom.scrollTop = this.scroller.dom.scrollTop;
34414         e.stopEvent();
34415     },
34416
34417     renderRows : function(startRow, endRow){
34418         // pull in all the crap needed to render rows
34419         var g = this.grid, cm = g.colModel, ds = g.dataSource, stripe = g.stripeRows;
34420         var colCount = cm.getColumnCount();
34421
34422         if(ds.getCount() < 1){
34423             return ["", ""];
34424         }
34425
34426         // build a map for all the columns
34427         var cs = [];
34428         for(var i = 0; i < colCount; i++){
34429             var name = cm.getDataIndex(i);
34430             cs[i] = {
34431                 name : typeof name == 'undefined' ? ds.fields.get(i).name : name,
34432                 renderer : cm.getRenderer(i),
34433                 id : cm.getColumnId(i),
34434                 locked : cm.isLocked(i),
34435                 has_editor : cm.isCellEditable(i)
34436             };
34437         }
34438
34439         startRow = startRow || 0;
34440         endRow = typeof endRow == "undefined"? ds.getCount()-1 : endRow;
34441
34442         // records to render
34443         var rs = ds.getRange(startRow, endRow);
34444
34445         return this.doRender(cs, rs, ds, startRow, colCount, stripe);
34446     },
34447
34448     // As much as I hate to duplicate code, this was branched because FireFox really hates
34449     // [].join("") on strings. The performance difference was substantial enough to
34450     // branch this function
34451     doRender : Roo.isGecko ?
34452             function(cs, rs, ds, startRow, colCount, stripe){
34453                 var ts = this.templates, ct = ts.cell, rt = ts.row;
34454                 // buffers
34455                 var buf = "", lbuf = "", cb, lcb, c, p = {}, rp = {}, r, rowIndex;
34456                 
34457                 var hasListener = this.grid.hasListener('rowclass');
34458                 var rowcfg = {};
34459                 for(var j = 0, len = rs.length; j < len; j++){
34460                     r = rs[j]; cb = ""; lcb = ""; rowIndex = (j+startRow);
34461                     for(var i = 0; i < colCount; i++){
34462                         c = cs[i];
34463                         p.cellId = "x-grid-cell-" + rowIndex + "-" + i;
34464                         p.id = c.id;
34465                         p.css = p.attr = "";
34466                         p.value = c.renderer(r.data[c.name], p, r, rowIndex, i, ds);
34467                         if(p.value == undefined || p.value === "") {
34468                             p.value = "&#160;";
34469                         }
34470                         if(c.has_editor){
34471                             p.css += ' x-grid-editable-cell';
34472                         }
34473                         if(c.dirty && typeof r.modified[c.name] !== 'undefined'){
34474                             p.css +=  ' x-grid-dirty-cell';
34475                         }
34476                         var markup = ct.apply(p);
34477                         if(!c.locked){
34478                             cb+= markup;
34479                         }else{
34480                             lcb+= markup;
34481                         }
34482                     }
34483                     var alt = [];
34484                     if(stripe && ((rowIndex+1) % 2 == 0)){
34485                         alt.push("x-grid-row-alt")
34486                     }
34487                     if(r.dirty){
34488                         alt.push(  " x-grid-dirty-row");
34489                     }
34490                     rp.cells = lcb;
34491                     if(this.getRowClass){
34492                         alt.push(this.getRowClass(r, rowIndex));
34493                     }
34494                     if (hasListener) {
34495                         rowcfg = {
34496                              
34497                             record: r,
34498                             rowIndex : rowIndex,
34499                             rowClass : ''
34500                         };
34501                         this.grid.fireEvent('rowclass', this, rowcfg);
34502                         alt.push(rowcfg.rowClass);
34503                     }
34504                     rp.alt = alt.join(" ");
34505                     lbuf+= rt.apply(rp);
34506                     rp.cells = cb;
34507                     buf+=  rt.apply(rp);
34508                 }
34509                 return [lbuf, buf];
34510             } :
34511             function(cs, rs, ds, startRow, colCount, stripe){
34512                 var ts = this.templates, ct = ts.cell, rt = ts.row;
34513                 // buffers
34514                 var buf = [], lbuf = [], cb, lcb, c, p = {}, rp = {}, r, rowIndex;
34515                 var hasListener = this.grid.hasListener('rowclass');
34516  
34517                 var rowcfg = {};
34518                 for(var j = 0, len = rs.length; j < len; j++){
34519                     r = rs[j]; cb = []; lcb = []; rowIndex = (j+startRow);
34520                     for(var i = 0; i < colCount; i++){
34521                         c = cs[i];
34522                         p.cellId = "x-grid-cell-" + rowIndex + "-" + i;
34523                         p.id = c.id;
34524                         p.css = p.attr = "";
34525                         p.value = c.renderer(r.data[c.name], p, r, rowIndex, i, ds);
34526                         if(p.value == undefined || p.value === "") {
34527                             p.value = "&#160;";
34528                         }
34529                         //Roo.log(c);
34530                          if(c.has_editor){
34531                             p.css += ' x-grid-editable-cell';
34532                         }
34533                         if(r.dirty && typeof r.modified[c.name] !== 'undefined'){
34534                             p.css += ' x-grid-dirty-cell' 
34535                         }
34536                         
34537                         var markup = ct.apply(p);
34538                         if(!c.locked){
34539                             cb[cb.length] = markup;
34540                         }else{
34541                             lcb[lcb.length] = markup;
34542                         }
34543                     }
34544                     var alt = [];
34545                     if(stripe && ((rowIndex+1) % 2 == 0)){
34546                         alt.push( "x-grid-row-alt");
34547                     }
34548                     if(r.dirty){
34549                         alt.push(" x-grid-dirty-row");
34550                     }
34551                     rp.cells = lcb;
34552                     if(this.getRowClass){
34553                         alt.push( this.getRowClass(r, rowIndex));
34554                     }
34555                     if (hasListener) {
34556                         rowcfg = {
34557                              
34558                             record: r,
34559                             rowIndex : rowIndex,
34560                             rowClass : ''
34561                         };
34562                         this.grid.fireEvent('rowclass', this, rowcfg);
34563                         alt.push(rowcfg.rowClass);
34564                     }
34565                     
34566                     rp.alt = alt.join(" ");
34567                     rp.cells = lcb.join("");
34568                     lbuf[lbuf.length] = rt.apply(rp);
34569                     rp.cells = cb.join("");
34570                     buf[buf.length] =  rt.apply(rp);
34571                 }
34572                 return [lbuf.join(""), buf.join("")];
34573             },
34574
34575     renderBody : function(){
34576         var markup = this.renderRows();
34577         var bt = this.templates.body;
34578         return [bt.apply({rows: markup[0]}), bt.apply({rows: markup[1]})];
34579     },
34580
34581     /**
34582      * Refreshes the grid
34583      * @param {Boolean} headersToo
34584      */
34585     refresh : function(headersToo){
34586         this.fireEvent("beforerefresh", this);
34587         this.grid.stopEditing();
34588         var result = this.renderBody();
34589         this.lockedBody.update(result[0]);
34590         this.mainBody.update(result[1]);
34591         if(headersToo === true){
34592             this.updateHeaders();
34593             this.updateColumns();
34594             this.updateSplitters();
34595             this.updateHeaderSortState();
34596         }
34597         this.syncRowHeights();
34598         this.layout();
34599         this.fireEvent("refresh", this);
34600     },
34601
34602     handleColumnMove : function(cm, oldIndex, newIndex){
34603         this.indexMap = null;
34604         var s = this.getScrollState();
34605         this.refresh(true);
34606         this.restoreScroll(s);
34607         this.afterMove(newIndex);
34608     },
34609
34610     afterMove : function(colIndex){
34611         if(this.enableMoveAnim && Roo.enableFx){
34612             this.fly(this.getHeaderCell(colIndex).firstChild).highlight(this.hlColor);
34613         }
34614         // if multisort - fix sortOrder, and reload..
34615         if (this.grid.dataSource.multiSort) {
34616             // the we can call sort again..
34617             var dm = this.grid.dataSource;
34618             var cm = this.grid.colModel;
34619             var so = [];
34620             for(var i = 0; i < cm.config.length; i++ ) {
34621                 
34622                 if ((typeof(dm.sortToggle[cm.config[i].dataIndex]) == 'undefined')) {
34623                     continue; // dont' bother, it's not in sort list or being set.
34624                 }
34625                 
34626                 so.push(cm.config[i].dataIndex);
34627             };
34628             dm.sortOrder = so;
34629             dm.load(dm.lastOptions);
34630             
34631             
34632         }
34633         
34634     },
34635
34636     updateCell : function(dm, rowIndex, dataIndex){
34637         var colIndex = this.getColumnIndexByDataIndex(dataIndex);
34638         if(typeof colIndex == "undefined"){ // not present in grid
34639             return;
34640         }
34641         var cm = this.grid.colModel;
34642         var cell = this.getCell(rowIndex, colIndex);
34643         var cellText = this.getCellText(rowIndex, colIndex);
34644
34645         var p = {
34646             cellId : "x-grid-cell-" + rowIndex + "-" + colIndex,
34647             id : cm.getColumnId(colIndex),
34648             css: colIndex == cm.getColumnCount()-1 ? "x-grid-col-last" : ""
34649         };
34650         var renderer = cm.getRenderer(colIndex);
34651         var val = renderer(dm.getValueAt(rowIndex, dataIndex), p, rowIndex, colIndex, dm);
34652         if(typeof val == "undefined" || val === "") {
34653             val = "&#160;";
34654         }
34655         cellText.innerHTML = val;
34656         cell.className = this.cellClass + " " + this.idToCssName(p.cellId) + " " + p.css;
34657         this.syncRowHeights(rowIndex, rowIndex);
34658     },
34659
34660     calcColumnWidth : function(colIndex, maxRowsToMeasure){
34661         var maxWidth = 0;
34662         if(this.grid.autoSizeHeaders){
34663             var h = this.getHeaderCellMeasure(colIndex);
34664             maxWidth = Math.max(maxWidth, h.scrollWidth);
34665         }
34666         var tb, index;
34667         if(this.cm.isLocked(colIndex)){
34668             tb = this.getLockedTable();
34669             index = colIndex;
34670         }else{
34671             tb = this.getBodyTable();
34672             index = colIndex - this.cm.getLockedCount();
34673         }
34674         if(tb && tb.rows){
34675             var rows = tb.rows;
34676             var stopIndex = Math.min(maxRowsToMeasure || rows.length, rows.length);
34677             for(var i = 0; i < stopIndex; i++){
34678                 var cell = rows[i].childNodes[index].firstChild;
34679                 maxWidth = Math.max(maxWidth, cell.scrollWidth);
34680             }
34681         }
34682         return maxWidth + /*margin for error in IE*/ 5;
34683     },
34684     /**
34685      * Autofit a column to its content.
34686      * @param {Number} colIndex
34687      * @param {Boolean} forceMinSize true to force the column to go smaller if possible
34688      */
34689      autoSizeColumn : function(colIndex, forceMinSize, suppressEvent){
34690          if(this.cm.isHidden(colIndex)){
34691              return; // can't calc a hidden column
34692          }
34693         if(forceMinSize){
34694             var cid = this.cm.getColumnId(colIndex);
34695             this.css.updateRule(this.colSelector +this.idToCssName( cid), "width", this.grid.minColumnWidth + "px");
34696            if(this.grid.autoSizeHeaders){
34697                this.css.updateRule(this.hdSelector + this.idToCssName(cid), "width", this.grid.minColumnWidth + "px");
34698            }
34699         }
34700         var newWidth = this.calcColumnWidth(colIndex);
34701         this.cm.setColumnWidth(colIndex,
34702             Math.max(this.grid.minColumnWidth, newWidth), suppressEvent);
34703         if(!suppressEvent){
34704             this.grid.fireEvent("columnresize", colIndex, newWidth);
34705         }
34706     },
34707
34708     /**
34709      * Autofits all columns to their content and then expands to fit any extra space in the grid
34710      */
34711      autoSizeColumns : function(){
34712         var cm = this.grid.colModel;
34713         var colCount = cm.getColumnCount();
34714         for(var i = 0; i < colCount; i++){
34715             this.autoSizeColumn(i, true, true);
34716         }
34717         if(cm.getTotalWidth() < this.scroller.dom.clientWidth){
34718             this.fitColumns();
34719         }else{
34720             this.updateColumns();
34721             this.layout();
34722         }
34723     },
34724
34725     /**
34726      * Autofits all columns to the grid's width proportionate with their current size
34727      * @param {Boolean} reserveScrollSpace Reserve space for a scrollbar
34728      */
34729     fitColumns : function(reserveScrollSpace){
34730         var cm = this.grid.colModel;
34731         var colCount = cm.getColumnCount();
34732         var cols = [];
34733         var width = 0;
34734         var i, w;
34735         for (i = 0; i < colCount; i++){
34736             if(!cm.isHidden(i) && !cm.isFixed(i)){
34737                 w = cm.getColumnWidth(i);
34738                 cols.push(i);
34739                 cols.push(w);
34740                 width += w;
34741             }
34742         }
34743         var avail = Math.min(this.scroller.dom.clientWidth, this.el.getWidth());
34744         if(reserveScrollSpace){
34745             avail -= 17;
34746         }
34747         var frac = (avail - cm.getTotalWidth())/width;
34748         while (cols.length){
34749             w = cols.pop();
34750             i = cols.pop();
34751             cm.setColumnWidth(i, Math.floor(w + w*frac), true);
34752         }
34753         this.updateColumns();
34754         this.layout();
34755     },
34756
34757     onRowSelect : function(rowIndex){
34758         var row = this.getRowComposite(rowIndex);
34759         row.addClass("x-grid-row-selected");
34760     },
34761
34762     onRowDeselect : function(rowIndex){
34763         var row = this.getRowComposite(rowIndex);
34764         row.removeClass("x-grid-row-selected");
34765     },
34766
34767     onCellSelect : function(row, col){
34768         var cell = this.getCell(row, col);
34769         if(cell){
34770             Roo.fly(cell).addClass("x-grid-cell-selected");
34771         }
34772     },
34773
34774     onCellDeselect : function(row, col){
34775         var cell = this.getCell(row, col);
34776         if(cell){
34777             Roo.fly(cell).removeClass("x-grid-cell-selected");
34778         }
34779     },
34780
34781     updateHeaderSortState : function(){
34782         
34783         // sort state can be single { field: xxx, direction : yyy}
34784         // or   { xxx=>ASC , yyy : DESC ..... }
34785         
34786         var mstate = {};
34787         if (!this.ds.multiSort) { 
34788             var state = this.ds.getSortState();
34789             if(!state){
34790                 return;
34791             }
34792             mstate[state.field] = state.direction;
34793             // FIXME... - this is not used here.. but might be elsewhere..
34794             this.sortState = state;
34795             
34796         } else {
34797             mstate = this.ds.sortToggle;
34798         }
34799         //remove existing sort classes..
34800         
34801         var sc = this.sortClasses;
34802         var hds = this.el.select(this.headerSelector).removeClass(sc);
34803         
34804         for(var f in mstate) {
34805         
34806             var sortColumn = this.cm.findColumnIndex(f);
34807             
34808             if(sortColumn != -1){
34809                 var sortDir = mstate[f];        
34810                 hds.item(sortColumn).addClass(sc[sortDir == "DESC" ? 1 : 0]);
34811             }
34812         }
34813         
34814          
34815         
34816     },
34817
34818
34819     handleHeaderClick : function(g, index,e){
34820         
34821         Roo.log("header click");
34822         
34823         if (Roo.isTouch) {
34824             // touch events on header are handled by context
34825             this.handleHdCtx(g,index,e);
34826             return;
34827         }
34828         
34829         
34830         if(this.headersDisabled){
34831             return;
34832         }
34833         var dm = g.dataSource, cm = g.colModel;
34834         if(!cm.isSortable(index)){
34835             return;
34836         }
34837         g.stopEditing();
34838         
34839         if (dm.multiSort) {
34840             // update the sortOrder
34841             var so = [];
34842             for(var i = 0; i < cm.config.length; i++ ) {
34843                 
34844                 if ((typeof(dm.sortToggle[cm.config[i].dataIndex]) == 'undefined') && (index != i)) {
34845                     continue; // dont' bother, it's not in sort list or being set.
34846                 }
34847                 
34848                 so.push(cm.config[i].dataIndex);
34849             };
34850             dm.sortOrder = so;
34851         }
34852         
34853         
34854         dm.sort(cm.getDataIndex(index));
34855     },
34856
34857
34858     destroy : function(){
34859         if(this.colMenu){
34860             this.colMenu.removeAll();
34861             Roo.menu.MenuMgr.unregister(this.colMenu);
34862             this.colMenu.getEl().remove();
34863             delete this.colMenu;
34864         }
34865         if(this.hmenu){
34866             this.hmenu.removeAll();
34867             Roo.menu.MenuMgr.unregister(this.hmenu);
34868             this.hmenu.getEl().remove();
34869             delete this.hmenu;
34870         }
34871         if(this.grid.enableColumnMove){
34872             var dds = Roo.dd.DDM.ids['gridHeader' + this.grid.getGridEl().id];
34873             if(dds){
34874                 for(var dd in dds){
34875                     if(!dds[dd].config.isTarget && dds[dd].dragElId){
34876                         var elid = dds[dd].dragElId;
34877                         dds[dd].unreg();
34878                         Roo.get(elid).remove();
34879                     } else if(dds[dd].config.isTarget){
34880                         dds[dd].proxyTop.remove();
34881                         dds[dd].proxyBottom.remove();
34882                         dds[dd].unreg();
34883                     }
34884                     if(Roo.dd.DDM.locationCache[dd]){
34885                         delete Roo.dd.DDM.locationCache[dd];
34886                     }
34887                 }
34888                 delete Roo.dd.DDM.ids['gridHeader' + this.grid.getGridEl().id];
34889             }
34890         }
34891         Roo.util.CSS.removeStyleSheet(this.idToCssName(this.grid.id) + '-cssrules');
34892         this.bind(null, null);
34893         Roo.EventManager.removeResizeListener(this.onWindowResize, this);
34894     },
34895
34896     handleLockChange : function(){
34897         this.refresh(true);
34898     },
34899
34900     onDenyColumnLock : function(){
34901
34902     },
34903
34904     onDenyColumnHide : function(){
34905
34906     },
34907
34908     handleHdMenuClick : function(item){
34909         var index = this.hdCtxIndex;
34910         var cm = this.cm, ds = this.ds;
34911         switch(item.id){
34912             case "asc":
34913                 ds.sort(cm.getDataIndex(index), "ASC");
34914                 break;
34915             case "desc":
34916                 ds.sort(cm.getDataIndex(index), "DESC");
34917                 break;
34918             case "lock":
34919                 var lc = cm.getLockedCount();
34920                 if(cm.getColumnCount(true) <= lc+1){
34921                     this.onDenyColumnLock();
34922                     return;
34923                 }
34924                 if(lc != index){
34925                     cm.setLocked(index, true, true);
34926                     cm.moveColumn(index, lc);
34927                     this.grid.fireEvent("columnmove", index, lc);
34928                 }else{
34929                     cm.setLocked(index, true);
34930                 }
34931             break;
34932             case "unlock":
34933                 var lc = cm.getLockedCount();
34934                 if((lc-1) != index){
34935                     cm.setLocked(index, false, true);
34936                     cm.moveColumn(index, lc-1);
34937                     this.grid.fireEvent("columnmove", index, lc-1);
34938                 }else{
34939                     cm.setLocked(index, false);
34940                 }
34941             break;
34942             case 'wider': // used to expand cols on touch..
34943             case 'narrow':
34944                 var cw = cm.getColumnWidth(index);
34945                 cw += (item.id == 'wider' ? 1 : -1) * 50;
34946                 cw = Math.max(0, cw);
34947                 cw = Math.min(cw,4000);
34948                 cm.setColumnWidth(index, cw);
34949                 break;
34950                 
34951             default:
34952                 index = cm.getIndexById(item.id.substr(4));
34953                 if(index != -1){
34954                     if(item.checked && cm.getColumnCount(true) <= 1){
34955                         this.onDenyColumnHide();
34956                         return false;
34957                     }
34958                     cm.setHidden(index, item.checked);
34959                 }
34960         }
34961         return true;
34962     },
34963
34964     beforeColMenuShow : function(){
34965         var cm = this.cm,  colCount = cm.getColumnCount();
34966         this.colMenu.removeAll();
34967         for(var i = 0; i < colCount; i++){
34968             this.colMenu.add(new Roo.menu.CheckItem({
34969                 id: "col-"+cm.getColumnId(i),
34970                 text: cm.getColumnHeader(i),
34971                 checked: !cm.isHidden(i),
34972                 hideOnClick:false
34973             }));
34974         }
34975     },
34976
34977     handleHdCtx : function(g, index, e){
34978         e.stopEvent();
34979         var hd = this.getHeaderCell(index);
34980         this.hdCtxIndex = index;
34981         var ms = this.hmenu.items, cm = this.cm;
34982         ms.get("asc").setDisabled(!cm.isSortable(index));
34983         ms.get("desc").setDisabled(!cm.isSortable(index));
34984         if(this.grid.enableColLock !== false){
34985             ms.get("lock").setDisabled(cm.isLocked(index));
34986             ms.get("unlock").setDisabled(!cm.isLocked(index));
34987         }
34988         this.hmenu.show(hd, "tl-bl");
34989     },
34990
34991     handleHdOver : function(e){
34992         var hd = this.findHeaderCell(e.getTarget());
34993         if(hd && !this.headersDisabled){
34994             if(this.grid.colModel.isSortable(this.getCellIndex(hd))){
34995                this.fly(hd).addClass("x-grid-hd-over");
34996             }
34997         }
34998     },
34999
35000     handleHdOut : function(e){
35001         var hd = this.findHeaderCell(e.getTarget());
35002         if(hd){
35003             this.fly(hd).removeClass("x-grid-hd-over");
35004         }
35005     },
35006
35007     handleSplitDblClick : function(e, t){
35008         var i = this.getCellIndex(t);
35009         if(this.grid.enableColumnResize !== false && this.cm.isResizable(i) && !this.cm.isFixed(i)){
35010             this.autoSizeColumn(i, true);
35011             this.layout();
35012         }
35013     },
35014
35015     render : function(){
35016
35017         var cm = this.cm;
35018         var colCount = cm.getColumnCount();
35019
35020         if(this.grid.monitorWindowResize === true){
35021             Roo.EventManager.onWindowResize(this.onWindowResize, this, true);
35022         }
35023         var header = this.renderHeaders();
35024         var body = this.templates.body.apply({rows:""});
35025         var html = this.templates.master.apply({
35026             lockedBody: body,
35027             body: body,
35028             lockedHeader: header[0],
35029             header: header[1]
35030         });
35031
35032         //this.updateColumns();
35033
35034         this.grid.getGridEl().dom.innerHTML = html;
35035
35036         this.initElements();
35037         
35038         // a kludge to fix the random scolling effect in webkit
35039         this.el.on("scroll", function() {
35040             this.el.dom.scrollTop=0; // hopefully not recursive..
35041         },this);
35042
35043         this.scroller.on("scroll", this.handleScroll, this);
35044         this.lockedBody.on("mousewheel", this.handleWheel, this);
35045         this.mainBody.on("mousewheel", this.handleWheel, this);
35046
35047         this.mainHd.on("mouseover", this.handleHdOver, this);
35048         this.mainHd.on("mouseout", this.handleHdOut, this);
35049         this.mainHd.on("dblclick", this.handleSplitDblClick, this,
35050                 {delegate: "."+this.splitClass});
35051
35052         this.lockedHd.on("mouseover", this.handleHdOver, this);
35053         this.lockedHd.on("mouseout", this.handleHdOut, this);
35054         this.lockedHd.on("dblclick", this.handleSplitDblClick, this,
35055                 {delegate: "."+this.splitClass});
35056
35057         if(this.grid.enableColumnResize !== false && Roo.grid.SplitDragZone){
35058             new Roo.grid.SplitDragZone(this.grid, this.lockedHd.dom, this.mainHd.dom);
35059         }
35060
35061         this.updateSplitters();
35062
35063         if(this.grid.enableColumnMove && Roo.grid.HeaderDragZone){
35064             new Roo.grid.HeaderDragZone(this.grid, this.lockedHd.dom, this.mainHd.dom);
35065             new Roo.grid.HeaderDropZone(this.grid, this.lockedHd.dom, this.mainHd.dom);
35066         }
35067
35068         if(this.grid.enableCtxMenu !== false && Roo.menu.Menu){
35069             this.hmenu = new Roo.menu.Menu({id: this.grid.id + "-hctx"});
35070             this.hmenu.add(
35071                 {id:"asc", text: this.sortAscText, cls: "xg-hmenu-sort-asc"},
35072                 {id:"desc", text: this.sortDescText, cls: "xg-hmenu-sort-desc"}
35073             );
35074             if(this.grid.enableColLock !== false){
35075                 this.hmenu.add('-',
35076                     {id:"lock", text: this.lockText, cls: "xg-hmenu-lock"},
35077                     {id:"unlock", text: this.unlockText, cls: "xg-hmenu-unlock"}
35078                 );
35079             }
35080             if (Roo.isTouch) {
35081                  this.hmenu.add('-',
35082                     {id:"wider", text: this.columnsWiderText},
35083                     {id:"narrow", text: this.columnsNarrowText }
35084                 );
35085                 
35086                  
35087             }
35088             
35089             if(this.grid.enableColumnHide !== false){
35090
35091                 this.colMenu = new Roo.menu.Menu({id:this.grid.id + "-hcols-menu"});
35092                 this.colMenu.on("beforeshow", this.beforeColMenuShow, this);
35093                 this.colMenu.on("itemclick", this.handleHdMenuClick, this);
35094
35095                 this.hmenu.add('-',
35096                     {id:"columns", text: this.columnsText, menu: this.colMenu}
35097                 );
35098             }
35099             this.hmenu.on("itemclick", this.handleHdMenuClick, this);
35100
35101             this.grid.on("headercontextmenu", this.handleHdCtx, this);
35102         }
35103
35104         if((this.grid.enableDragDrop || this.grid.enableDrag) && Roo.grid.GridDragZone){
35105             this.dd = new Roo.grid.GridDragZone(this.grid, {
35106                 ddGroup : this.grid.ddGroup || 'GridDD'
35107             });
35108             
35109         }
35110
35111         /*
35112         for(var i = 0; i < colCount; i++){
35113             if(cm.isHidden(i)){
35114                 this.hideColumn(i);
35115             }
35116             if(cm.config[i].align){
35117                 this.css.updateRule(this.colSelector + i, "textAlign", cm.config[i].align);
35118                 this.css.updateRule(this.hdSelector + i, "textAlign", cm.config[i].align);
35119             }
35120         }*/
35121         
35122         this.updateHeaderSortState();
35123
35124         this.beforeInitialResize();
35125         this.layout(true);
35126
35127         // two part rendering gives faster view to the user
35128         this.renderPhase2.defer(1, this);
35129     },
35130
35131     renderPhase2 : function(){
35132         // render the rows now
35133         this.refresh();
35134         if(this.grid.autoSizeColumns){
35135             this.autoSizeColumns();
35136         }
35137     },
35138
35139     beforeInitialResize : function(){
35140
35141     },
35142
35143     onColumnSplitterMoved : function(i, w){
35144         this.userResized = true;
35145         var cm = this.grid.colModel;
35146         cm.setColumnWidth(i, w, true);
35147         var cid = cm.getColumnId(i);
35148         this.css.updateRule(this.colSelector + this.idToCssName(cid), "width", (w-this.borderWidth) + "px");
35149         this.css.updateRule(this.hdSelector + this.idToCssName(cid), "width", (w-this.borderWidth) + "px");
35150         this.updateSplitters();
35151         this.layout();
35152         this.grid.fireEvent("columnresize", i, w);
35153     },
35154
35155     syncRowHeights : function(startIndex, endIndex){
35156         if(this.grid.enableRowHeightSync === true && this.cm.getLockedCount() > 0){
35157             startIndex = startIndex || 0;
35158             var mrows = this.getBodyTable().rows;
35159             var lrows = this.getLockedTable().rows;
35160             var len = mrows.length-1;
35161             endIndex = Math.min(endIndex || len, len);
35162             for(var i = startIndex; i <= endIndex; i++){
35163                 var m = mrows[i], l = lrows[i];
35164                 var h = Math.max(m.offsetHeight, l.offsetHeight);
35165                 m.style.height = l.style.height = h + "px";
35166             }
35167         }
35168     },
35169
35170     layout : function(initialRender, is2ndPass){
35171         var g = this.grid;
35172         var auto = g.autoHeight;
35173         var scrollOffset = 16;
35174         var c = g.getGridEl(), cm = this.cm,
35175                 expandCol = g.autoExpandColumn,
35176                 gv = this;
35177         //c.beginMeasure();
35178
35179         if(!c.dom.offsetWidth){ // display:none?
35180             if(initialRender){
35181                 this.lockedWrap.show();
35182                 this.mainWrap.show();
35183             }
35184             return;
35185         }
35186
35187         var hasLock = this.cm.isLocked(0);
35188
35189         var tbh = this.headerPanel.getHeight();
35190         var bbh = this.footerPanel.getHeight();
35191
35192         if(auto){
35193             var ch = this.getBodyTable().offsetHeight + tbh + bbh + this.mainHd.getHeight();
35194             var newHeight = ch + c.getBorderWidth("tb");
35195             if(g.maxHeight){
35196                 newHeight = Math.min(g.maxHeight, newHeight);
35197             }
35198             c.setHeight(newHeight);
35199         }
35200
35201         if(g.autoWidth){
35202             c.setWidth(cm.getTotalWidth()+c.getBorderWidth('lr'));
35203         }
35204
35205         var s = this.scroller;
35206
35207         var csize = c.getSize(true);
35208
35209         this.el.setSize(csize.width, csize.height);
35210
35211         this.headerPanel.setWidth(csize.width);
35212         this.footerPanel.setWidth(csize.width);
35213
35214         var hdHeight = this.mainHd.getHeight();
35215         var vw = csize.width;
35216         var vh = csize.height - (tbh + bbh);
35217
35218         s.setSize(vw, vh);
35219
35220         var bt = this.getBodyTable();
35221         
35222         if(cm.getLockedCount() == cm.config.length){
35223             bt = this.getLockedTable();
35224         }
35225         
35226         var ltWidth = hasLock ?
35227                       Math.max(this.getLockedTable().offsetWidth, this.lockedHd.dom.firstChild.offsetWidth) : 0;
35228
35229         var scrollHeight = bt.offsetHeight;
35230         var scrollWidth = ltWidth + bt.offsetWidth;
35231         var vscroll = false, hscroll = false;
35232
35233         this.scrollSizer.setSize(scrollWidth, scrollHeight+hdHeight);
35234
35235         var lw = this.lockedWrap, mw = this.mainWrap;
35236         var lb = this.lockedBody, mb = this.mainBody;
35237
35238         setTimeout(function(){
35239             var t = s.dom.offsetTop;
35240             var w = s.dom.clientWidth,
35241                 h = s.dom.clientHeight;
35242
35243             lw.setTop(t);
35244             lw.setSize(ltWidth, h);
35245
35246             mw.setLeftTop(ltWidth, t);
35247             mw.setSize(w-ltWidth, h);
35248
35249             lb.setHeight(h-hdHeight);
35250             mb.setHeight(h-hdHeight);
35251
35252             if(is2ndPass !== true && !gv.userResized && expandCol){
35253                 // high speed resize without full column calculation
35254                 
35255                 var ci = cm.getIndexById(expandCol);
35256                 if (ci < 0) {
35257                     ci = cm.findColumnIndex(expandCol);
35258                 }
35259                 ci = Math.max(0, ci); // make sure it's got at least the first col.
35260                 var expandId = cm.getColumnId(ci);
35261                 var  tw = cm.getTotalWidth(false);
35262                 var currentWidth = cm.getColumnWidth(ci);
35263                 var cw = Math.min(Math.max(((w-tw)+currentWidth-2)-/*scrollbar*/(w <= s.dom.offsetWidth ? 0 : 18), g.autoExpandMin), g.autoExpandMax);
35264                 if(currentWidth != cw){
35265                     cm.setColumnWidth(ci, cw, true);
35266                     gv.css.updateRule(gv.colSelector+gv.idToCssName(expandId), "width", (cw - gv.borderWidth) + "px");
35267                     gv.css.updateRule(gv.hdSelector+gv.idToCssName(expandId), "width", (cw - gv.borderWidth) + "px");
35268                     gv.updateSplitters();
35269                     gv.layout(false, true);
35270                 }
35271             }
35272
35273             if(initialRender){
35274                 lw.show();
35275                 mw.show();
35276             }
35277             //c.endMeasure();
35278         }, 10);
35279     },
35280
35281     onWindowResize : function(){
35282         if(!this.grid.monitorWindowResize || this.grid.autoHeight){
35283             return;
35284         }
35285         this.layout();
35286     },
35287
35288     appendFooter : function(parentEl){
35289         return null;
35290     },
35291
35292     sortAscText : "Sort Ascending",
35293     sortDescText : "Sort Descending",
35294     lockText : "Lock Column",
35295     unlockText : "Unlock Column",
35296     columnsText : "Columns",
35297  
35298     columnsWiderText : "Wider",
35299     columnsNarrowText : "Thinner"
35300 });
35301
35302
35303 Roo.grid.GridView.ColumnDragZone = function(grid, hd){
35304     Roo.grid.GridView.ColumnDragZone.superclass.constructor.call(this, grid, hd, null);
35305     this.proxy.el.addClass('x-grid3-col-dd');
35306 };
35307
35308 Roo.extend(Roo.grid.GridView.ColumnDragZone, Roo.grid.HeaderDragZone, {
35309     handleMouseDown : function(e){
35310
35311     },
35312
35313     callHandleMouseDown : function(e){
35314         Roo.grid.GridView.ColumnDragZone.superclass.handleMouseDown.call(this, e);
35315     }
35316 });
35317 /*
35318  * Based on:
35319  * Ext JS Library 1.1.1
35320  * Copyright(c) 2006-2007, Ext JS, LLC.
35321  *
35322  * Originally Released Under LGPL - original licence link has changed is not relivant.
35323  *
35324  * Fork - LGPL
35325  * <script type="text/javascript">
35326  */
35327  
35328 // private
35329 // This is a support class used internally by the Grid components
35330 Roo.grid.SplitDragZone = function(grid, hd, hd2){
35331     this.grid = grid;
35332     this.view = grid.getView();
35333     this.proxy = this.view.resizeProxy;
35334     Roo.grid.SplitDragZone.superclass.constructor.call(this, hd,
35335         "gridSplitters" + this.grid.getGridEl().id, {
35336         dragElId : Roo.id(this.proxy.dom), resizeFrame:false
35337     });
35338     this.setHandleElId(Roo.id(hd));
35339     this.setOuterHandleElId(Roo.id(hd2));
35340     this.scroll = false;
35341 };
35342 Roo.extend(Roo.grid.SplitDragZone, Roo.dd.DDProxy, {
35343     fly: Roo.Element.fly,
35344
35345     b4StartDrag : function(x, y){
35346         this.view.headersDisabled = true;
35347         this.proxy.setHeight(this.view.mainWrap.getHeight());
35348         var w = this.cm.getColumnWidth(this.cellIndex);
35349         var minw = Math.max(w-this.grid.minColumnWidth, 0);
35350         this.resetConstraints();
35351         this.setXConstraint(minw, 1000);
35352         this.setYConstraint(0, 0);
35353         this.minX = x - minw;
35354         this.maxX = x + 1000;
35355         this.startPos = x;
35356         Roo.dd.DDProxy.prototype.b4StartDrag.call(this, x, y);
35357     },
35358
35359
35360     handleMouseDown : function(e){
35361         ev = Roo.EventObject.setEvent(e);
35362         var t = this.fly(ev.getTarget());
35363         if(t.hasClass("x-grid-split")){
35364             this.cellIndex = this.view.getCellIndex(t.dom);
35365             this.split = t.dom;
35366             this.cm = this.grid.colModel;
35367             if(this.cm.isResizable(this.cellIndex) && !this.cm.isFixed(this.cellIndex)){
35368                 Roo.grid.SplitDragZone.superclass.handleMouseDown.apply(this, arguments);
35369             }
35370         }
35371     },
35372
35373     endDrag : function(e){
35374         this.view.headersDisabled = false;
35375         var endX = Math.max(this.minX, Roo.lib.Event.getPageX(e));
35376         var diff = endX - this.startPos;
35377         this.view.onColumnSplitterMoved(this.cellIndex, this.cm.getColumnWidth(this.cellIndex)+diff);
35378     },
35379
35380     autoOffset : function(){
35381         this.setDelta(0,0);
35382     }
35383 });/*
35384  * Based on:
35385  * Ext JS Library 1.1.1
35386  * Copyright(c) 2006-2007, Ext JS, LLC.
35387  *
35388  * Originally Released Under LGPL - original licence link has changed is not relivant.
35389  *
35390  * Fork - LGPL
35391  * <script type="text/javascript">
35392  */
35393  
35394 // private
35395 // This is a support class used internally by the Grid components
35396 Roo.grid.GridDragZone = function(grid, config){
35397     this.view = grid.getView();
35398     Roo.grid.GridDragZone.superclass.constructor.call(this, this.view.mainBody.dom, config);
35399     if(this.view.lockedBody){
35400         this.setHandleElId(Roo.id(this.view.mainBody.dom));
35401         this.setOuterHandleElId(Roo.id(this.view.lockedBody.dom));
35402     }
35403     this.scroll = false;
35404     this.grid = grid;
35405     this.ddel = document.createElement('div');
35406     this.ddel.className = 'x-grid-dd-wrap';
35407 };
35408
35409 Roo.extend(Roo.grid.GridDragZone, Roo.dd.DragZone, {
35410     ddGroup : "GridDD",
35411
35412     getDragData : function(e){
35413         var t = Roo.lib.Event.getTarget(e);
35414         var rowIndex = this.view.findRowIndex(t);
35415         var sm = this.grid.selModel;
35416             
35417         //Roo.log(rowIndex);
35418         
35419         if (sm.getSelectedCell) {
35420             // cell selection..
35421             if (!sm.getSelectedCell()) {
35422                 return false;
35423             }
35424             if (rowIndex != sm.getSelectedCell()[0]) {
35425                 return false;
35426             }
35427         
35428         }
35429         
35430         if(rowIndex !== false){
35431             
35432             // if editorgrid.. 
35433             
35434             
35435             //Roo.log([ sm.getSelectedCell() ? sm.getSelectedCell()[0] : 'NO' , rowIndex ]);
35436                
35437             //if(!sm.isSelected(rowIndex) || e.hasModifier()){
35438               //  
35439             //}
35440             if (e.hasModifier()){
35441                 sm.handleMouseDown(e, t); // non modifier buttons are handled by row select.
35442             }
35443             
35444             Roo.log("getDragData");
35445             
35446             return {
35447                 grid: this.grid,
35448                 ddel: this.ddel,
35449                 rowIndex: rowIndex,
35450                 selections:sm.getSelections ? sm.getSelections() : (
35451                     sm.getSelectedCell() ? [ this.grid.ds.getAt(sm.getSelectedCell()[0]) ] : []
35452                 )
35453             };
35454         }
35455         return false;
35456     },
35457
35458     onInitDrag : function(e){
35459         var data = this.dragData;
35460         this.ddel.innerHTML = this.grid.getDragDropText();
35461         this.proxy.update(this.ddel);
35462         // fire start drag?
35463     },
35464
35465     afterRepair : function(){
35466         this.dragging = false;
35467     },
35468
35469     getRepairXY : function(e, data){
35470         return false;
35471     },
35472
35473     onEndDrag : function(data, e){
35474         // fire end drag?
35475     },
35476
35477     onValidDrop : function(dd, e, id){
35478         // fire drag drop?
35479         this.hideProxy();
35480     },
35481
35482     beforeInvalidDrop : function(e, id){
35483
35484     }
35485 });/*
35486  * Based on:
35487  * Ext JS Library 1.1.1
35488  * Copyright(c) 2006-2007, Ext JS, LLC.
35489  *
35490  * Originally Released Under LGPL - original licence link has changed is not relivant.
35491  *
35492  * Fork - LGPL
35493  * <script type="text/javascript">
35494  */
35495  
35496
35497 /**
35498  * @class Roo.grid.ColumnModel
35499  * @extends Roo.util.Observable
35500  * This is the default implementation of a ColumnModel used by the Grid. It defines
35501  * the columns in the grid.
35502  * <br>Usage:<br>
35503  <pre><code>
35504  var colModel = new Roo.grid.ColumnModel([
35505         {header: "Ticker", width: 60, sortable: true, locked: true},
35506         {header: "Company Name", width: 150, sortable: true},
35507         {header: "Market Cap.", width: 100, sortable: true},
35508         {header: "$ Sales", width: 100, sortable: true, renderer: money},
35509         {header: "Employees", width: 100, sortable: true, resizable: false}
35510  ]);
35511  </code></pre>
35512  * <p>
35513  
35514  * The config options listed for this class are options which may appear in each
35515  * individual column definition.
35516  * <br/>RooJS Fix - column id's are not sequential but use Roo.id() - fixes bugs with layouts.
35517  * @constructor
35518  * @param {Object} config An Array of column config objects. See this class's
35519  * config objects for details.
35520 */
35521 Roo.grid.ColumnModel = function(config){
35522         /**
35523      * The config passed into the constructor
35524      */
35525     this.config = config;
35526     this.lookup = {};
35527
35528     // if no id, create one
35529     // if the column does not have a dataIndex mapping,
35530     // map it to the order it is in the config
35531     for(var i = 0, len = config.length; i < len; i++){
35532         var c = config[i];
35533         if(typeof c.dataIndex == "undefined"){
35534             c.dataIndex = i;
35535         }
35536         if(typeof c.renderer == "string"){
35537             c.renderer = Roo.util.Format[c.renderer];
35538         }
35539         if(typeof c.id == "undefined"){
35540             c.id = Roo.id();
35541         }
35542         if(c.editor && c.editor.xtype){
35543             c.editor  = Roo.factory(c.editor, Roo.grid);
35544         }
35545         if(c.editor && c.editor.isFormField){
35546             c.editor = new Roo.grid.GridEditor(c.editor);
35547         }
35548         this.lookup[c.id] = c;
35549     }
35550
35551     /**
35552      * The width of columns which have no width specified (defaults to 100)
35553      * @type Number
35554      */
35555     this.defaultWidth = 100;
35556
35557     /**
35558      * Default sortable of columns which have no sortable specified (defaults to false)
35559      * @type Boolean
35560      */
35561     this.defaultSortable = false;
35562
35563     this.addEvents({
35564         /**
35565              * @event widthchange
35566              * Fires when the width of a column changes.
35567              * @param {ColumnModel} this
35568              * @param {Number} columnIndex The column index
35569              * @param {Number} newWidth The new width
35570              */
35571             "widthchange": true,
35572         /**
35573              * @event headerchange
35574              * Fires when the text of a header changes.
35575              * @param {ColumnModel} this
35576              * @param {Number} columnIndex The column index
35577              * @param {Number} newText The new header text
35578              */
35579             "headerchange": true,
35580         /**
35581              * @event hiddenchange
35582              * Fires when a column is hidden or "unhidden".
35583              * @param {ColumnModel} this
35584              * @param {Number} columnIndex The column index
35585              * @param {Boolean} hidden true if hidden, false otherwise
35586              */
35587             "hiddenchange": true,
35588             /**
35589          * @event columnmoved
35590          * Fires when a column is moved.
35591          * @param {ColumnModel} this
35592          * @param {Number} oldIndex
35593          * @param {Number} newIndex
35594          */
35595         "columnmoved" : true,
35596         /**
35597          * @event columlockchange
35598          * Fires when a column's locked state is changed
35599          * @param {ColumnModel} this
35600          * @param {Number} colIndex
35601          * @param {Boolean} locked true if locked
35602          */
35603         "columnlockchange" : true
35604     });
35605     Roo.grid.ColumnModel.superclass.constructor.call(this);
35606 };
35607 Roo.extend(Roo.grid.ColumnModel, Roo.util.Observable, {
35608     /**
35609      * @cfg {String} header The header text to display in the Grid view.
35610      */
35611     /**
35612      * @cfg {String} dataIndex (Optional) The name of the field in the grid's {@link Roo.data.Store}'s
35613      * {@link Roo.data.Record} definition from which to draw the column's value. If not
35614      * specified, the column's index is used as an index into the Record's data Array.
35615      */
35616     /**
35617      * @cfg {Number} width (Optional) The initial width in pixels of the column. Using this
35618      * instead of {@link Roo.grid.Grid#autoSizeColumns} is more efficient.
35619      */
35620     /**
35621      * @cfg {Boolean} sortable (Optional) True if sorting is to be allowed on this column.
35622      * Defaults to the value of the {@link #defaultSortable} property.
35623      * Whether local/remote sorting is used is specified in {@link Roo.data.Store#remoteSort}.
35624      */
35625     /**
35626      * @cfg {Boolean} locked (Optional) True to lock the column in place while scrolling the Grid.  Defaults to false.
35627      */
35628     /**
35629      * @cfg {Boolean} fixed (Optional) True if the column width cannot be changed.  Defaults to false.
35630      */
35631     /**
35632      * @cfg {Boolean} resizable (Optional) False to disable column resizing. Defaults to true.
35633      */
35634     /**
35635      * @cfg {Boolean} hidden (Optional) True to hide the column. Defaults to false.
35636      */
35637     /**
35638      * @cfg {Function} renderer (Optional) A function used to generate HTML markup for a cell
35639      * given the cell's data value. See {@link #setRenderer}. If not specified, the
35640      * default renderer returns the escaped data value. If an object is returned (bootstrap only)
35641      * then it is treated as a Roo Component object instance, and it is rendered after the initial row is rendered
35642      */
35643        /**
35644      * @cfg {Roo.grid.GridEditor} editor (Optional) For grid editors - returns the grid editor 
35645      */
35646     /**
35647      * @cfg {String} align (Optional) Set the CSS text-align property of the column.  Defaults to undefined.
35648      */
35649     /**
35650      * @cfg {String} valign (Optional) Set the CSS vertical-align property of the column (eg. middle, top, bottom etc).  Defaults to undefined.
35651      */
35652     /**
35653      * @cfg {String} cursor (Optional)
35654      */
35655     /**
35656      * @cfg {String} tooltip (Optional)
35657      */
35658     /**
35659      * @cfg {Number} xs (Optional)
35660      */
35661     /**
35662      * @cfg {Number} sm (Optional)
35663      */
35664     /**
35665      * @cfg {Number} md (Optional)
35666      */
35667     /**
35668      * @cfg {Number} lg (Optional)
35669      */
35670     /**
35671      * Returns the id of the column at the specified index.
35672      * @param {Number} index The column index
35673      * @return {String} the id
35674      */
35675     getColumnId : function(index){
35676         return this.config[index].id;
35677     },
35678
35679     /**
35680      * Returns the column for a specified id.
35681      * @param {String} id The column id
35682      * @return {Object} the column
35683      */
35684     getColumnById : function(id){
35685         return this.lookup[id];
35686     },
35687
35688     
35689     /**
35690      * Returns the column for a specified dataIndex.
35691      * @param {String} dataIndex The column dataIndex
35692      * @return {Object|Boolean} the column or false if not found
35693      */
35694     getColumnByDataIndex: function(dataIndex){
35695         var index = this.findColumnIndex(dataIndex);
35696         return index > -1 ? this.config[index] : false;
35697     },
35698     
35699     /**
35700      * Returns the index for a specified column id.
35701      * @param {String} id The column id
35702      * @return {Number} the index, or -1 if not found
35703      */
35704     getIndexById : function(id){
35705         for(var i = 0, len = this.config.length; i < len; i++){
35706             if(this.config[i].id == id){
35707                 return i;
35708             }
35709         }
35710         return -1;
35711     },
35712     
35713     /**
35714      * Returns the index for a specified column dataIndex.
35715      * @param {String} dataIndex The column dataIndex
35716      * @return {Number} the index, or -1 if not found
35717      */
35718     
35719     findColumnIndex : function(dataIndex){
35720         for(var i = 0, len = this.config.length; i < len; i++){
35721             if(this.config[i].dataIndex == dataIndex){
35722                 return i;
35723             }
35724         }
35725         return -1;
35726     },
35727     
35728     
35729     moveColumn : function(oldIndex, newIndex){
35730         var c = this.config[oldIndex];
35731         this.config.splice(oldIndex, 1);
35732         this.config.splice(newIndex, 0, c);
35733         this.dataMap = null;
35734         this.fireEvent("columnmoved", this, oldIndex, newIndex);
35735     },
35736
35737     isLocked : function(colIndex){
35738         return this.config[colIndex].locked === true;
35739     },
35740
35741     setLocked : function(colIndex, value, suppressEvent){
35742         if(this.isLocked(colIndex) == value){
35743             return;
35744         }
35745         this.config[colIndex].locked = value;
35746         if(!suppressEvent){
35747             this.fireEvent("columnlockchange", this, colIndex, value);
35748         }
35749     },
35750
35751     getTotalLockedWidth : function(){
35752         var totalWidth = 0;
35753         for(var i = 0; i < this.config.length; i++){
35754             if(this.isLocked(i) && !this.isHidden(i)){
35755                 this.totalWidth += this.getColumnWidth(i);
35756             }
35757         }
35758         return totalWidth;
35759     },
35760
35761     getLockedCount : function(){
35762         for(var i = 0, len = this.config.length; i < len; i++){
35763             if(!this.isLocked(i)){
35764                 return i;
35765             }
35766         }
35767         
35768         return this.config.length;
35769     },
35770
35771     /**
35772      * Returns the number of columns.
35773      * @return {Number}
35774      */
35775     getColumnCount : function(visibleOnly){
35776         if(visibleOnly === true){
35777             var c = 0;
35778             for(var i = 0, len = this.config.length; i < len; i++){
35779                 if(!this.isHidden(i)){
35780                     c++;
35781                 }
35782             }
35783             return c;
35784         }
35785         return this.config.length;
35786     },
35787
35788     /**
35789      * Returns the column configs that return true by the passed function that is called with (columnConfig, index)
35790      * @param {Function} fn
35791      * @param {Object} scope (optional)
35792      * @return {Array} result
35793      */
35794     getColumnsBy : function(fn, scope){
35795         var r = [];
35796         for(var i = 0, len = this.config.length; i < len; i++){
35797             var c = this.config[i];
35798             if(fn.call(scope||this, c, i) === true){
35799                 r[r.length] = c;
35800             }
35801         }
35802         return r;
35803     },
35804
35805     /**
35806      * Returns true if the specified column is sortable.
35807      * @param {Number} col The column index
35808      * @return {Boolean}
35809      */
35810     isSortable : function(col){
35811         if(typeof this.config[col].sortable == "undefined"){
35812             return this.defaultSortable;
35813         }
35814         return this.config[col].sortable;
35815     },
35816
35817     /**
35818      * Returns the rendering (formatting) function defined for the column.
35819      * @param {Number} col The column index.
35820      * @return {Function} The function used to render the cell. See {@link #setRenderer}.
35821      */
35822     getRenderer : function(col){
35823         if(!this.config[col].renderer){
35824             return Roo.grid.ColumnModel.defaultRenderer;
35825         }
35826         return this.config[col].renderer;
35827     },
35828
35829     /**
35830      * Sets the rendering (formatting) function for a column.
35831      * @param {Number} col The column index
35832      * @param {Function} fn The function to use to process the cell's raw data
35833      * to return HTML markup for the grid view. The render function is called with
35834      * the following parameters:<ul>
35835      * <li>Data value.</li>
35836      * <li>Cell metadata. An object in which you may set the following attributes:<ul>
35837      * <li>css A CSS style string to apply to the table cell.</li>
35838      * <li>attr An HTML attribute definition string to apply to the data container element <i>within</i> the table cell.</li></ul>
35839      * <li>The {@link Roo.data.Record} from which the data was extracted.</li>
35840      * <li>Row index</li>
35841      * <li>Column index</li>
35842      * <li>The {@link Roo.data.Store} object from which the Record was extracted</li></ul>
35843      */
35844     setRenderer : function(col, fn){
35845         this.config[col].renderer = fn;
35846     },
35847
35848     /**
35849      * Returns the width for the specified column.
35850      * @param {Number} col The column index
35851      * @return {Number}
35852      */
35853     getColumnWidth : function(col){
35854         return this.config[col].width * 1 || this.defaultWidth;
35855     },
35856
35857     /**
35858      * Sets the width for a column.
35859      * @param {Number} col The column index
35860      * @param {Number} width The new width
35861      */
35862     setColumnWidth : function(col, width, suppressEvent){
35863         this.config[col].width = width;
35864         this.totalWidth = null;
35865         if(!suppressEvent){
35866              this.fireEvent("widthchange", this, col, width);
35867         }
35868     },
35869
35870     /**
35871      * Returns the total width of all columns.
35872      * @param {Boolean} includeHidden True to include hidden column widths
35873      * @return {Number}
35874      */
35875     getTotalWidth : function(includeHidden){
35876         if(!this.totalWidth){
35877             this.totalWidth = 0;
35878             for(var i = 0, len = this.config.length; i < len; i++){
35879                 if(includeHidden || !this.isHidden(i)){
35880                     this.totalWidth += this.getColumnWidth(i);
35881                 }
35882             }
35883         }
35884         return this.totalWidth;
35885     },
35886
35887     /**
35888      * Returns the header for the specified column.
35889      * @param {Number} col The column index
35890      * @return {String}
35891      */
35892     getColumnHeader : function(col){
35893         return this.config[col].header;
35894     },
35895
35896     /**
35897      * Sets the header for a column.
35898      * @param {Number} col The column index
35899      * @param {String} header The new header
35900      */
35901     setColumnHeader : function(col, header){
35902         this.config[col].header = header;
35903         this.fireEvent("headerchange", this, col, header);
35904     },
35905
35906     /**
35907      * Returns the tooltip for the specified column.
35908      * @param {Number} col The column index
35909      * @return {String}
35910      */
35911     getColumnTooltip : function(col){
35912             return this.config[col].tooltip;
35913     },
35914     /**
35915      * Sets the tooltip for a column.
35916      * @param {Number} col The column index
35917      * @param {String} tooltip The new tooltip
35918      */
35919     setColumnTooltip : function(col, tooltip){
35920             this.config[col].tooltip = tooltip;
35921     },
35922
35923     /**
35924      * Returns the dataIndex for the specified column.
35925      * @param {Number} col The column index
35926      * @return {Number}
35927      */
35928     getDataIndex : function(col){
35929         return this.config[col].dataIndex;
35930     },
35931
35932     /**
35933      * Sets the dataIndex for a column.
35934      * @param {Number} col The column index
35935      * @param {Number} dataIndex The new dataIndex
35936      */
35937     setDataIndex : function(col, dataIndex){
35938         this.config[col].dataIndex = dataIndex;
35939     },
35940
35941     
35942     
35943     /**
35944      * Returns true if the cell is editable.
35945      * @param {Number} colIndex The column index
35946      * @param {Number} rowIndex The row index - this is nto actually used..?
35947      * @return {Boolean}
35948      */
35949     isCellEditable : function(colIndex, rowIndex){
35950         return (this.config[colIndex].editable || (typeof this.config[colIndex].editable == "undefined" && this.config[colIndex].editor)) ? true : false;
35951     },
35952
35953     /**
35954      * Returns the editor defined for the cell/column.
35955      * return false or null to disable editing.
35956      * @param {Number} colIndex The column index
35957      * @param {Number} rowIndex The row index
35958      * @return {Object}
35959      */
35960     getCellEditor : function(colIndex, rowIndex){
35961         return this.config[colIndex].editor;
35962     },
35963
35964     /**
35965      * Sets if a column is editable.
35966      * @param {Number} col The column index
35967      * @param {Boolean} editable True if the column is editable
35968      */
35969     setEditable : function(col, editable){
35970         this.config[col].editable = editable;
35971     },
35972
35973
35974     /**
35975      * Returns true if the column is hidden.
35976      * @param {Number} colIndex The column index
35977      * @return {Boolean}
35978      */
35979     isHidden : function(colIndex){
35980         return this.config[colIndex].hidden;
35981     },
35982
35983
35984     /**
35985      * Returns true if the column width cannot be changed
35986      */
35987     isFixed : function(colIndex){
35988         return this.config[colIndex].fixed;
35989     },
35990
35991     /**
35992      * Returns true if the column can be resized
35993      * @return {Boolean}
35994      */
35995     isResizable : function(colIndex){
35996         return colIndex >= 0 && this.config[colIndex].resizable !== false && this.config[colIndex].fixed !== true;
35997     },
35998     /**
35999      * Sets if a column is hidden.
36000      * @param {Number} colIndex The column index
36001      * @param {Boolean} hidden True if the column is hidden
36002      */
36003     setHidden : function(colIndex, hidden){
36004         this.config[colIndex].hidden = hidden;
36005         this.totalWidth = null;
36006         this.fireEvent("hiddenchange", this, colIndex, hidden);
36007     },
36008
36009     /**
36010      * Sets the editor for a column.
36011      * @param {Number} col The column index
36012      * @param {Object} editor The editor object
36013      */
36014     setEditor : function(col, editor){
36015         this.config[col].editor = editor;
36016     }
36017 });
36018
36019 Roo.grid.ColumnModel.defaultRenderer = function(value)
36020 {
36021     if(typeof value == "object") {
36022         return value;
36023     }
36024         if(typeof value == "string" && value.length < 1){
36025             return "&#160;";
36026         }
36027     
36028         return String.format("{0}", value);
36029 };
36030
36031 // Alias for backwards compatibility
36032 Roo.grid.DefaultColumnModel = Roo.grid.ColumnModel;
36033 /*
36034  * Based on:
36035  * Ext JS Library 1.1.1
36036  * Copyright(c) 2006-2007, Ext JS, LLC.
36037  *
36038  * Originally Released Under LGPL - original licence link has changed is not relivant.
36039  *
36040  * Fork - LGPL
36041  * <script type="text/javascript">
36042  */
36043
36044 /**
36045  * @class Roo.grid.AbstractSelectionModel
36046  * @extends Roo.util.Observable
36047  * Abstract base class for grid SelectionModels.  It provides the interface that should be
36048  * implemented by descendant classes.  This class should not be directly instantiated.
36049  * @constructor
36050  */
36051 Roo.grid.AbstractSelectionModel = function(){
36052     this.locked = false;
36053     Roo.grid.AbstractSelectionModel.superclass.constructor.call(this);
36054 };
36055
36056 Roo.extend(Roo.grid.AbstractSelectionModel, Roo.util.Observable,  {
36057     /** @ignore Called by the grid automatically. Do not call directly. */
36058     init : function(grid){
36059         this.grid = grid;
36060         this.initEvents();
36061     },
36062
36063     /**
36064      * Locks the selections.
36065      */
36066     lock : function(){
36067         this.locked = true;
36068     },
36069
36070     /**
36071      * Unlocks the selections.
36072      */
36073     unlock : function(){
36074         this.locked = false;
36075     },
36076
36077     /**
36078      * Returns true if the selections are locked.
36079      * @return {Boolean}
36080      */
36081     isLocked : function(){
36082         return this.locked;
36083     }
36084 });/*
36085  * Based on:
36086  * Ext JS Library 1.1.1
36087  * Copyright(c) 2006-2007, Ext JS, LLC.
36088  *
36089  * Originally Released Under LGPL - original licence link has changed is not relivant.
36090  *
36091  * Fork - LGPL
36092  * <script type="text/javascript">
36093  */
36094 /**
36095  * @extends Roo.grid.AbstractSelectionModel
36096  * @class Roo.grid.RowSelectionModel
36097  * The default SelectionModel used by {@link Roo.grid.Grid}.
36098  * It supports multiple selections and keyboard selection/navigation. 
36099  * @constructor
36100  * @param {Object} config
36101  */
36102 Roo.grid.RowSelectionModel = function(config){
36103     Roo.apply(this, config);
36104     this.selections = new Roo.util.MixedCollection(false, function(o){
36105         return o.id;
36106     });
36107
36108     this.last = false;
36109     this.lastActive = false;
36110
36111     this.addEvents({
36112         /**
36113              * @event selectionchange
36114              * Fires when the selection changes
36115              * @param {SelectionModel} this
36116              */
36117             "selectionchange" : true,
36118         /**
36119              * @event afterselectionchange
36120              * Fires after the selection changes (eg. by key press or clicking)
36121              * @param {SelectionModel} this
36122              */
36123             "afterselectionchange" : true,
36124         /**
36125              * @event beforerowselect
36126              * Fires when a row is selected being selected, return false to cancel.
36127              * @param {SelectionModel} this
36128              * @param {Number} rowIndex The selected index
36129              * @param {Boolean} keepExisting False if other selections will be cleared
36130              */
36131             "beforerowselect" : true,
36132         /**
36133              * @event rowselect
36134              * Fires when a row is selected.
36135              * @param {SelectionModel} this
36136              * @param {Number} rowIndex The selected index
36137              * @param {Roo.data.Record} r The record
36138              */
36139             "rowselect" : true,
36140         /**
36141              * @event rowdeselect
36142              * Fires when a row is deselected.
36143              * @param {SelectionModel} this
36144              * @param {Number} rowIndex The selected index
36145              */
36146         "rowdeselect" : true
36147     });
36148     Roo.grid.RowSelectionModel.superclass.constructor.call(this);
36149     this.locked = false;
36150 };
36151
36152 Roo.extend(Roo.grid.RowSelectionModel, Roo.grid.AbstractSelectionModel,  {
36153     /**
36154      * @cfg {Boolean} singleSelect
36155      * True to allow selection of only one row at a time (defaults to false)
36156      */
36157     singleSelect : false,
36158
36159     // private
36160     initEvents : function(){
36161
36162         if(!this.grid.enableDragDrop && !this.grid.enableDrag){
36163             this.grid.on("mousedown", this.handleMouseDown, this);
36164         }else{ // allow click to work like normal
36165             this.grid.on("rowclick", this.handleDragableRowClick, this);
36166         }
36167
36168         this.rowNav = new Roo.KeyNav(this.grid.getGridEl(), {
36169             "up" : function(e){
36170                 if(!e.shiftKey){
36171                     this.selectPrevious(e.shiftKey);
36172                 }else if(this.last !== false && this.lastActive !== false){
36173                     var last = this.last;
36174                     this.selectRange(this.last,  this.lastActive-1);
36175                     this.grid.getView().focusRow(this.lastActive);
36176                     if(last !== false){
36177                         this.last = last;
36178                     }
36179                 }else{
36180                     this.selectFirstRow();
36181                 }
36182                 this.fireEvent("afterselectionchange", this);
36183             },
36184             "down" : function(e){
36185                 if(!e.shiftKey){
36186                     this.selectNext(e.shiftKey);
36187                 }else if(this.last !== false && this.lastActive !== false){
36188                     var last = this.last;
36189                     this.selectRange(this.last,  this.lastActive+1);
36190                     this.grid.getView().focusRow(this.lastActive);
36191                     if(last !== false){
36192                         this.last = last;
36193                     }
36194                 }else{
36195                     this.selectFirstRow();
36196                 }
36197                 this.fireEvent("afterselectionchange", this);
36198             },
36199             scope: this
36200         });
36201
36202         var view = this.grid.view;
36203         view.on("refresh", this.onRefresh, this);
36204         view.on("rowupdated", this.onRowUpdated, this);
36205         view.on("rowremoved", this.onRemove, this);
36206     },
36207
36208     // private
36209     onRefresh : function(){
36210         var ds = this.grid.dataSource, i, v = this.grid.view;
36211         var s = this.selections;
36212         s.each(function(r){
36213             if((i = ds.indexOfId(r.id)) != -1){
36214                 v.onRowSelect(i);
36215                 s.add(ds.getAt(i)); // updating the selection relate data
36216             }else{
36217                 s.remove(r);
36218             }
36219         });
36220     },
36221
36222     // private
36223     onRemove : function(v, index, r){
36224         this.selections.remove(r);
36225     },
36226
36227     // private
36228     onRowUpdated : function(v, index, r){
36229         if(this.isSelected(r)){
36230             v.onRowSelect(index);
36231         }
36232     },
36233
36234     /**
36235      * Select records.
36236      * @param {Array} records The records to select
36237      * @param {Boolean} keepExisting (optional) True to keep existing selections
36238      */
36239     selectRecords : function(records, keepExisting){
36240         if(!keepExisting){
36241             this.clearSelections();
36242         }
36243         var ds = this.grid.dataSource;
36244         for(var i = 0, len = records.length; i < len; i++){
36245             this.selectRow(ds.indexOf(records[i]), true);
36246         }
36247     },
36248
36249     /**
36250      * Gets the number of selected rows.
36251      * @return {Number}
36252      */
36253     getCount : function(){
36254         return this.selections.length;
36255     },
36256
36257     /**
36258      * Selects the first row in the grid.
36259      */
36260     selectFirstRow : function(){
36261         this.selectRow(0);
36262     },
36263
36264     /**
36265      * Select the last row.
36266      * @param {Boolean} keepExisting (optional) True to keep existing selections
36267      */
36268     selectLastRow : function(keepExisting){
36269         this.selectRow(this.grid.dataSource.getCount() - 1, keepExisting);
36270     },
36271
36272     /**
36273      * Selects the row immediately following the last selected row.
36274      * @param {Boolean} keepExisting (optional) True to keep existing selections
36275      */
36276     selectNext : function(keepExisting){
36277         if(this.last !== false && (this.last+1) < this.grid.dataSource.getCount()){
36278             this.selectRow(this.last+1, keepExisting);
36279             this.grid.getView().focusRow(this.last);
36280         }
36281     },
36282
36283     /**
36284      * Selects the row that precedes the last selected row.
36285      * @param {Boolean} keepExisting (optional) True to keep existing selections
36286      */
36287     selectPrevious : function(keepExisting){
36288         if(this.last){
36289             this.selectRow(this.last-1, keepExisting);
36290             this.grid.getView().focusRow(this.last);
36291         }
36292     },
36293
36294     /**
36295      * Returns the selected records
36296      * @return {Array} Array of selected records
36297      */
36298     getSelections : function(){
36299         return [].concat(this.selections.items);
36300     },
36301
36302     /**
36303      * Returns the first selected record.
36304      * @return {Record}
36305      */
36306     getSelected : function(){
36307         return this.selections.itemAt(0);
36308     },
36309
36310
36311     /**
36312      * Clears all selections.
36313      */
36314     clearSelections : function(fast){
36315         if(this.locked) {
36316             return;
36317         }
36318         if(fast !== true){
36319             var ds = this.grid.dataSource;
36320             var s = this.selections;
36321             s.each(function(r){
36322                 this.deselectRow(ds.indexOfId(r.id));
36323             }, this);
36324             s.clear();
36325         }else{
36326             this.selections.clear();
36327         }
36328         this.last = false;
36329     },
36330
36331
36332     /**
36333      * Selects all rows.
36334      */
36335     selectAll : function(){
36336         if(this.locked) {
36337             return;
36338         }
36339         this.selections.clear();
36340         for(var i = 0, len = this.grid.dataSource.getCount(); i < len; i++){
36341             this.selectRow(i, true);
36342         }
36343     },
36344
36345     /**
36346      * Returns True if there is a selection.
36347      * @return {Boolean}
36348      */
36349     hasSelection : function(){
36350         return this.selections.length > 0;
36351     },
36352
36353     /**
36354      * Returns True if the specified row is selected.
36355      * @param {Number/Record} record The record or index of the record to check
36356      * @return {Boolean}
36357      */
36358     isSelected : function(index){
36359         var r = typeof index == "number" ? this.grid.dataSource.getAt(index) : index;
36360         return (r && this.selections.key(r.id) ? true : false);
36361     },
36362
36363     /**
36364      * Returns True if the specified record id is selected.
36365      * @param {String} id The id of record to check
36366      * @return {Boolean}
36367      */
36368     isIdSelected : function(id){
36369         return (this.selections.key(id) ? true : false);
36370     },
36371
36372     // private
36373     handleMouseDown : function(e, t){
36374         var view = this.grid.getView(), rowIndex;
36375         if(this.isLocked() || (rowIndex = view.findRowIndex(t)) === false){
36376             return;
36377         };
36378         if(e.shiftKey && this.last !== false){
36379             var last = this.last;
36380             this.selectRange(last, rowIndex, e.ctrlKey);
36381             this.last = last; // reset the last
36382             view.focusRow(rowIndex);
36383         }else{
36384             var isSelected = this.isSelected(rowIndex);
36385             if(e.button !== 0 && isSelected){
36386                 view.focusRow(rowIndex);
36387             }else if(e.ctrlKey && isSelected){
36388                 this.deselectRow(rowIndex);
36389             }else if(!isSelected){
36390                 this.selectRow(rowIndex, e.button === 0 && (e.ctrlKey || e.shiftKey));
36391                 view.focusRow(rowIndex);
36392             }
36393         }
36394         this.fireEvent("afterselectionchange", this);
36395     },
36396     // private
36397     handleDragableRowClick :  function(grid, rowIndex, e) 
36398     {
36399         if(e.button === 0 && !e.shiftKey && !e.ctrlKey) {
36400             this.selectRow(rowIndex, false);
36401             grid.view.focusRow(rowIndex);
36402              this.fireEvent("afterselectionchange", this);
36403         }
36404     },
36405     
36406     /**
36407      * Selects multiple rows.
36408      * @param {Array} rows Array of the indexes of the row to select
36409      * @param {Boolean} keepExisting (optional) True to keep existing selections
36410      */
36411     selectRows : function(rows, keepExisting){
36412         if(!keepExisting){
36413             this.clearSelections();
36414         }
36415         for(var i = 0, len = rows.length; i < len; i++){
36416             this.selectRow(rows[i], true);
36417         }
36418     },
36419
36420     /**
36421      * Selects a range of rows. All rows in between startRow and endRow are also selected.
36422      * @param {Number} startRow The index of the first row in the range
36423      * @param {Number} endRow The index of the last row in the range
36424      * @param {Boolean} keepExisting (optional) True to retain existing selections
36425      */
36426     selectRange : function(startRow, endRow, keepExisting){
36427         if(this.locked) {
36428             return;
36429         }
36430         if(!keepExisting){
36431             this.clearSelections();
36432         }
36433         if(startRow <= endRow){
36434             for(var i = startRow; i <= endRow; i++){
36435                 this.selectRow(i, true);
36436             }
36437         }else{
36438             for(var i = startRow; i >= endRow; i--){
36439                 this.selectRow(i, true);
36440             }
36441         }
36442     },
36443
36444     /**
36445      * Deselects a range of rows. All rows in between startRow and endRow are also deselected.
36446      * @param {Number} startRow The index of the first row in the range
36447      * @param {Number} endRow The index of the last row in the range
36448      */
36449     deselectRange : function(startRow, endRow, preventViewNotify){
36450         if(this.locked) {
36451             return;
36452         }
36453         for(var i = startRow; i <= endRow; i++){
36454             this.deselectRow(i, preventViewNotify);
36455         }
36456     },
36457
36458     /**
36459      * Selects a row.
36460      * @param {Number} row The index of the row to select
36461      * @param {Boolean} keepExisting (optional) True to keep existing selections
36462      */
36463     selectRow : function(index, keepExisting, preventViewNotify){
36464         if(this.locked || (index < 0 || index >= this.grid.dataSource.getCount())) {
36465             return;
36466         }
36467         if(this.fireEvent("beforerowselect", this, index, keepExisting) !== false){
36468             if(!keepExisting || this.singleSelect){
36469                 this.clearSelections();
36470             }
36471             var r = this.grid.dataSource.getAt(index);
36472             this.selections.add(r);
36473             this.last = this.lastActive = index;
36474             if(!preventViewNotify){
36475                 this.grid.getView().onRowSelect(index);
36476             }
36477             this.fireEvent("rowselect", this, index, r);
36478             this.fireEvent("selectionchange", this);
36479         }
36480     },
36481
36482     /**
36483      * Deselects a row.
36484      * @param {Number} row The index of the row to deselect
36485      */
36486     deselectRow : function(index, preventViewNotify){
36487         if(this.locked) {
36488             return;
36489         }
36490         if(this.last == index){
36491             this.last = false;
36492         }
36493         if(this.lastActive == index){
36494             this.lastActive = false;
36495         }
36496         var r = this.grid.dataSource.getAt(index);
36497         this.selections.remove(r);
36498         if(!preventViewNotify){
36499             this.grid.getView().onRowDeselect(index);
36500         }
36501         this.fireEvent("rowdeselect", this, index);
36502         this.fireEvent("selectionchange", this);
36503     },
36504
36505     // private
36506     restoreLast : function(){
36507         if(this._last){
36508             this.last = this._last;
36509         }
36510     },
36511
36512     // private
36513     acceptsNav : function(row, col, cm){
36514         return !cm.isHidden(col) && cm.isCellEditable(col, row);
36515     },
36516
36517     // private
36518     onEditorKey : function(field, e){
36519         var k = e.getKey(), newCell, g = this.grid, ed = g.activeEditor;
36520         if(k == e.TAB){
36521             e.stopEvent();
36522             ed.completeEdit();
36523             if(e.shiftKey){
36524                 newCell = g.walkCells(ed.row, ed.col-1, -1, this.acceptsNav, this);
36525             }else{
36526                 newCell = g.walkCells(ed.row, ed.col+1, 1, this.acceptsNav, this);
36527             }
36528         }else if(k == e.ENTER && !e.ctrlKey){
36529             e.stopEvent();
36530             ed.completeEdit();
36531             if(e.shiftKey){
36532                 newCell = g.walkCells(ed.row-1, ed.col, -1, this.acceptsNav, this);
36533             }else{
36534                 newCell = g.walkCells(ed.row+1, ed.col, 1, this.acceptsNav, this);
36535             }
36536         }else if(k == e.ESC){
36537             ed.cancelEdit();
36538         }
36539         if(newCell){
36540             g.startEditing(newCell[0], newCell[1]);
36541         }
36542     }
36543 });/*
36544  * Based on:
36545  * Ext JS Library 1.1.1
36546  * Copyright(c) 2006-2007, Ext JS, LLC.
36547  *
36548  * Originally Released Under LGPL - original licence link has changed is not relivant.
36549  *
36550  * Fork - LGPL
36551  * <script type="text/javascript">
36552  */
36553 /**
36554  * @class Roo.grid.CellSelectionModel
36555  * @extends Roo.grid.AbstractSelectionModel
36556  * This class provides the basic implementation for cell selection in a grid.
36557  * @constructor
36558  * @param {Object} config The object containing the configuration of this model.
36559  * @cfg {Boolean} enter_is_tab Enter behaves the same as tab. (eg. goes to next cell) default: false
36560  */
36561 Roo.grid.CellSelectionModel = function(config){
36562     Roo.apply(this, config);
36563
36564     this.selection = null;
36565
36566     this.addEvents({
36567         /**
36568              * @event beforerowselect
36569              * Fires before a cell is selected.
36570              * @param {SelectionModel} this
36571              * @param {Number} rowIndex The selected row index
36572              * @param {Number} colIndex The selected cell index
36573              */
36574             "beforecellselect" : true,
36575         /**
36576              * @event cellselect
36577              * Fires when a cell is selected.
36578              * @param {SelectionModel} this
36579              * @param {Number} rowIndex The selected row index
36580              * @param {Number} colIndex The selected cell index
36581              */
36582             "cellselect" : true,
36583         /**
36584              * @event selectionchange
36585              * Fires when the active selection changes.
36586              * @param {SelectionModel} this
36587              * @param {Object} selection null for no selection or an object (o) with two properties
36588                 <ul>
36589                 <li>o.record: the record object for the row the selection is in</li>
36590                 <li>o.cell: An array of [rowIndex, columnIndex]</li>
36591                 </ul>
36592              */
36593             "selectionchange" : true,
36594         /**
36595              * @event tabend
36596              * Fires when the tab (or enter) was pressed on the last editable cell
36597              * You can use this to trigger add new row.
36598              * @param {SelectionModel} this
36599              */
36600             "tabend" : true,
36601          /**
36602              * @event beforeeditnext
36603              * Fires before the next editable sell is made active
36604              * You can use this to skip to another cell or fire the tabend
36605              *    if you set cell to false
36606              * @param {Object} eventdata object : { cell : [ row, col ] } 
36607              */
36608             "beforeeditnext" : true
36609     });
36610     Roo.grid.CellSelectionModel.superclass.constructor.call(this);
36611 };
36612
36613 Roo.extend(Roo.grid.CellSelectionModel, Roo.grid.AbstractSelectionModel,  {
36614     
36615     enter_is_tab: false,
36616
36617     /** @ignore */
36618     initEvents : function(){
36619         this.grid.on("mousedown", this.handleMouseDown, this);
36620         this.grid.getGridEl().on(Roo.isIE ? "keydown" : "keypress", this.handleKeyDown, this);
36621         var view = this.grid.view;
36622         view.on("refresh", this.onViewChange, this);
36623         view.on("rowupdated", this.onRowUpdated, this);
36624         view.on("beforerowremoved", this.clearSelections, this);
36625         view.on("beforerowsinserted", this.clearSelections, this);
36626         if(this.grid.isEditor){
36627             this.grid.on("beforeedit", this.beforeEdit,  this);
36628         }
36629     },
36630
36631         //private
36632     beforeEdit : function(e){
36633         this.select(e.row, e.column, false, true, e.record);
36634     },
36635
36636         //private
36637     onRowUpdated : function(v, index, r){
36638         if(this.selection && this.selection.record == r){
36639             v.onCellSelect(index, this.selection.cell[1]);
36640         }
36641     },
36642
36643         //private
36644     onViewChange : function(){
36645         this.clearSelections(true);
36646     },
36647
36648         /**
36649          * Returns the currently selected cell,.
36650          * @return {Array} The selected cell (row, column) or null if none selected.
36651          */
36652     getSelectedCell : function(){
36653         return this.selection ? this.selection.cell : null;
36654     },
36655
36656     /**
36657      * Clears all selections.
36658      * @param {Boolean} true to prevent the gridview from being notified about the change.
36659      */
36660     clearSelections : function(preventNotify){
36661         var s = this.selection;
36662         if(s){
36663             if(preventNotify !== true){
36664                 this.grid.view.onCellDeselect(s.cell[0], s.cell[1]);
36665             }
36666             this.selection = null;
36667             this.fireEvent("selectionchange", this, null);
36668         }
36669     },
36670
36671     /**
36672      * Returns true if there is a selection.
36673      * @return {Boolean}
36674      */
36675     hasSelection : function(){
36676         return this.selection ? true : false;
36677     },
36678
36679     /** @ignore */
36680     handleMouseDown : function(e, t){
36681         var v = this.grid.getView();
36682         if(this.isLocked()){
36683             return;
36684         };
36685         var row = v.findRowIndex(t);
36686         var cell = v.findCellIndex(t);
36687         if(row !== false && cell !== false){
36688             this.select(row, cell);
36689         }
36690     },
36691
36692     /**
36693      * Selects a cell.
36694      * @param {Number} rowIndex
36695      * @param {Number} collIndex
36696      */
36697     select : function(rowIndex, colIndex, preventViewNotify, preventFocus, /*internal*/ r){
36698         if(this.fireEvent("beforecellselect", this, rowIndex, colIndex) !== false){
36699             this.clearSelections();
36700             r = r || this.grid.dataSource.getAt(rowIndex);
36701             this.selection = {
36702                 record : r,
36703                 cell : [rowIndex, colIndex]
36704             };
36705             if(!preventViewNotify){
36706                 var v = this.grid.getView();
36707                 v.onCellSelect(rowIndex, colIndex);
36708                 if(preventFocus !== true){
36709                     v.focusCell(rowIndex, colIndex);
36710                 }
36711             }
36712             this.fireEvent("cellselect", this, rowIndex, colIndex);
36713             this.fireEvent("selectionchange", this, this.selection);
36714         }
36715     },
36716
36717         //private
36718     isSelectable : function(rowIndex, colIndex, cm){
36719         return !cm.isHidden(colIndex);
36720     },
36721
36722     /** @ignore */
36723     handleKeyDown : function(e){
36724         //Roo.log('Cell Sel Model handleKeyDown');
36725         if(!e.isNavKeyPress()){
36726             return;
36727         }
36728         var g = this.grid, s = this.selection;
36729         if(!s){
36730             e.stopEvent();
36731             var cell = g.walkCells(0, 0, 1, this.isSelectable,  this);
36732             if(cell){
36733                 this.select(cell[0], cell[1]);
36734             }
36735             return;
36736         }
36737         var sm = this;
36738         var walk = function(row, col, step){
36739             return g.walkCells(row, col, step, sm.isSelectable,  sm);
36740         };
36741         var k = e.getKey(), r = s.cell[0], c = s.cell[1];
36742         var newCell;
36743
36744       
36745
36746         switch(k){
36747             case e.TAB:
36748                 // handled by onEditorKey
36749                 if (g.isEditor && g.editing) {
36750                     return;
36751                 }
36752                 if(e.shiftKey) {
36753                     newCell = walk(r, c-1, -1);
36754                 } else {
36755                     newCell = walk(r, c+1, 1);
36756                 }
36757                 break;
36758             
36759             case e.DOWN:
36760                newCell = walk(r+1, c, 1);
36761                 break;
36762             
36763             case e.UP:
36764                 newCell = walk(r-1, c, -1);
36765                 break;
36766             
36767             case e.RIGHT:
36768                 newCell = walk(r, c+1, 1);
36769                 break;
36770             
36771             case e.LEFT:
36772                 newCell = walk(r, c-1, -1);
36773                 break;
36774             
36775             case e.ENTER:
36776                 
36777                 if(g.isEditor && !g.editing){
36778                    g.startEditing(r, c);
36779                    e.stopEvent();
36780                    return;
36781                 }
36782                 
36783                 
36784              break;
36785         };
36786         if(newCell){
36787             this.select(newCell[0], newCell[1]);
36788             e.stopEvent();
36789             
36790         }
36791     },
36792
36793     acceptsNav : function(row, col, cm){
36794         return !cm.isHidden(col) && cm.isCellEditable(col, row);
36795     },
36796     /**
36797      * Selects a cell.
36798      * @param {Number} field (not used) - as it's normally used as a listener
36799      * @param {Number} e - event - fake it by using
36800      *
36801      * var e = Roo.EventObjectImpl.prototype;
36802      * e.keyCode = e.TAB
36803      *
36804      * 
36805      */
36806     onEditorKey : function(field, e){
36807         
36808         var k = e.getKey(),
36809             newCell,
36810             g = this.grid,
36811             ed = g.activeEditor,
36812             forward = false;
36813         ///Roo.log('onEditorKey' + k);
36814         
36815         
36816         if (this.enter_is_tab && k == e.ENTER) {
36817             k = e.TAB;
36818         }
36819         
36820         if(k == e.TAB){
36821             if(e.shiftKey){
36822                 newCell = g.walkCells(ed.row, ed.col-1, -1, this.acceptsNav, this);
36823             }else{
36824                 newCell = g.walkCells(ed.row, ed.col+1, 1, this.acceptsNav, this);
36825                 forward = true;
36826             }
36827             
36828             e.stopEvent();
36829             
36830         } else if(k == e.ENTER &&  !e.ctrlKey){
36831             ed.completeEdit();
36832             e.stopEvent();
36833             newCell = g.walkCells(ed.row, ed.col+1, 1, this.acceptsNav, this);
36834         
36835                 } else if(k == e.ESC){
36836             ed.cancelEdit();
36837         }
36838                 
36839         if (newCell) {
36840             var ecall = { cell : newCell, forward : forward };
36841             this.fireEvent('beforeeditnext', ecall );
36842             newCell = ecall.cell;
36843                         forward = ecall.forward;
36844         }
36845                 
36846         if(newCell){
36847             //Roo.log('next cell after edit');
36848             g.startEditing.defer(100, g, [newCell[0], newCell[1]]);
36849         } else if (forward) {
36850             // tabbed past last
36851             this.fireEvent.defer(100, this, ['tabend',this]);
36852         }
36853     }
36854 });/*
36855  * Based on:
36856  * Ext JS Library 1.1.1
36857  * Copyright(c) 2006-2007, Ext JS, LLC.
36858  *
36859  * Originally Released Under LGPL - original licence link has changed is not relivant.
36860  *
36861  * Fork - LGPL
36862  * <script type="text/javascript">
36863  */
36864  
36865 /**
36866  * @class Roo.grid.EditorGrid
36867  * @extends Roo.grid.Grid
36868  * Class for creating and editable grid.
36869  * @param {String/HTMLElement/Roo.Element} container The element into which this grid will be rendered - 
36870  * The container MUST have some type of size defined for the grid to fill. The container will be 
36871  * automatically set to position relative if it isn't already.
36872  * @param {Object} dataSource The data model to bind to
36873  * @param {Object} colModel The column model with info about this grid's columns
36874  */
36875 Roo.grid.EditorGrid = function(container, config){
36876     Roo.grid.EditorGrid.superclass.constructor.call(this, container, config);
36877     this.getGridEl().addClass("xedit-grid");
36878
36879     if(!this.selModel){
36880         this.selModel = new Roo.grid.CellSelectionModel();
36881     }
36882
36883     this.activeEditor = null;
36884
36885         this.addEvents({
36886             /**
36887              * @event beforeedit
36888              * Fires before cell editing is triggered. The edit event object has the following properties <br />
36889              * <ul style="padding:5px;padding-left:16px;">
36890              * <li>grid - This grid</li>
36891              * <li>record - The record being edited</li>
36892              * <li>field - The field name being edited</li>
36893              * <li>value - The value for the field being edited.</li>
36894              * <li>row - The grid row index</li>
36895              * <li>column - The grid column index</li>
36896              * <li>cancel - Set this to true to cancel the edit or return false from your handler.</li>
36897              * </ul>
36898              * @param {Object} e An edit event (see above for description)
36899              */
36900             "beforeedit" : true,
36901             /**
36902              * @event afteredit
36903              * Fires after a cell is edited. <br />
36904              * <ul style="padding:5px;padding-left:16px;">
36905              * <li>grid - This grid</li>
36906              * <li>record - The record being edited</li>
36907              * <li>field - The field name being edited</li>
36908              * <li>value - The value being set</li>
36909              * <li>originalValue - The original value for the field, before the edit.</li>
36910              * <li>row - The grid row index</li>
36911              * <li>column - The grid column index</li>
36912              * </ul>
36913              * @param {Object} e An edit event (see above for description)
36914              */
36915             "afteredit" : true,
36916             /**
36917              * @event validateedit
36918              * Fires after a cell is edited, but before the value is set in the record. 
36919          * You can use this to modify the value being set in the field, Return false
36920              * to cancel the change. The edit event object has the following properties <br />
36921              * <ul style="padding:5px;padding-left:16px;">
36922          * <li>editor - This editor</li>
36923              * <li>grid - This grid</li>
36924              * <li>record - The record being edited</li>
36925              * <li>field - The field name being edited</li>
36926              * <li>value - The value being set</li>
36927              * <li>originalValue - The original value for the field, before the edit.</li>
36928              * <li>row - The grid row index</li>
36929              * <li>column - The grid column index</li>
36930              * <li>cancel - Set this to true to cancel the edit or return false from your handler.</li>
36931              * </ul>
36932              * @param {Object} e An edit event (see above for description)
36933              */
36934             "validateedit" : true
36935         });
36936     this.on("bodyscroll", this.stopEditing,  this);
36937     this.on(this.clicksToEdit == 1 ? "cellclick" : "celldblclick", this.onCellDblClick,  this);
36938 };
36939
36940 Roo.extend(Roo.grid.EditorGrid, Roo.grid.Grid, {
36941     /**
36942      * @cfg {Number} clicksToEdit
36943      * The number of clicks on a cell required to display the cell's editor (defaults to 2)
36944      */
36945     clicksToEdit: 2,
36946
36947     // private
36948     isEditor : true,
36949     // private
36950     trackMouseOver: false, // causes very odd FF errors
36951
36952     onCellDblClick : function(g, row, col){
36953         this.startEditing(row, col);
36954     },
36955
36956     onEditComplete : function(ed, value, startValue){
36957         this.editing = false;
36958         this.activeEditor = null;
36959         ed.un("specialkey", this.selModel.onEditorKey, this.selModel);
36960         var r = ed.record;
36961         var field = this.colModel.getDataIndex(ed.col);
36962         var e = {
36963             grid: this,
36964             record: r,
36965             field: field,
36966             originalValue: startValue,
36967             value: value,
36968             row: ed.row,
36969             column: ed.col,
36970             cancel:false,
36971             editor: ed
36972         };
36973         var cell = Roo.get(this.view.getCell(ed.row,ed.col));
36974         cell.show();
36975           
36976         if(String(value) !== String(startValue)){
36977             
36978             if(this.fireEvent("validateedit", e) !== false && !e.cancel){
36979                 r.set(field, e.value);
36980                 // if we are dealing with a combo box..
36981                 // then we also set the 'name' colum to be the displayField
36982                 if (ed.field.displayField && ed.field.name) {
36983                     r.set(ed.field.name, ed.field.el.dom.value);
36984                 }
36985                 
36986                 delete e.cancel; //?? why!!!
36987                 this.fireEvent("afteredit", e);
36988             }
36989         } else {
36990             this.fireEvent("afteredit", e); // always fire it!
36991         }
36992         this.view.focusCell(ed.row, ed.col);
36993     },
36994
36995     /**
36996      * Starts editing the specified for the specified row/column
36997      * @param {Number} rowIndex
36998      * @param {Number} colIndex
36999      */
37000     startEditing : function(row, col){
37001         this.stopEditing();
37002         if(this.colModel.isCellEditable(col, row)){
37003             this.view.ensureVisible(row, col, true);
37004           
37005             var r = this.dataSource.getAt(row);
37006             var field = this.colModel.getDataIndex(col);
37007             var cell = Roo.get(this.view.getCell(row,col));
37008             var e = {
37009                 grid: this,
37010                 record: r,
37011                 field: field,
37012                 value: r.data[field],
37013                 row: row,
37014                 column: col,
37015                 cancel:false 
37016             };
37017             if(this.fireEvent("beforeedit", e) !== false && !e.cancel){
37018                 this.editing = true;
37019                 var ed = this.colModel.getCellEditor(col, row);
37020                 
37021                 if (!ed) {
37022                     return;
37023                 }
37024                 if(!ed.rendered){
37025                     ed.render(ed.parentEl || document.body);
37026                 }
37027                 ed.field.reset();
37028                
37029                 cell.hide();
37030                 
37031                 (function(){ // complex but required for focus issues in safari, ie and opera
37032                     ed.row = row;
37033                     ed.col = col;
37034                     ed.record = r;
37035                     ed.on("complete",   this.onEditComplete,        this,       {single: true});
37036                     ed.on("specialkey", this.selModel.onEditorKey,  this.selModel);
37037                     this.activeEditor = ed;
37038                     var v = r.data[field];
37039                     ed.startEdit(this.view.getCell(row, col), v);
37040                     // combo's with 'displayField and name set
37041                     if (ed.field.displayField && ed.field.name) {
37042                         ed.field.el.dom.value = r.data[ed.field.name];
37043                     }
37044                     
37045                     
37046                 }).defer(50, this);
37047             }
37048         }
37049     },
37050         
37051     /**
37052      * Stops any active editing
37053      */
37054     stopEditing : function(){
37055         if(this.activeEditor){
37056             this.activeEditor.completeEdit();
37057         }
37058         this.activeEditor = null;
37059     },
37060         
37061          /**
37062      * Called to get grid's drag proxy text, by default returns this.ddText.
37063      * @return {String}
37064      */
37065     getDragDropText : function(){
37066         var count = this.selModel.getSelectedCell() ? 1 : 0;
37067         return String.format(this.ddText, count, count == 1 ? '' : 's');
37068     }
37069         
37070 });/*
37071  * Based on:
37072  * Ext JS Library 1.1.1
37073  * Copyright(c) 2006-2007, Ext JS, LLC.
37074  *
37075  * Originally Released Under LGPL - original licence link has changed is not relivant.
37076  *
37077  * Fork - LGPL
37078  * <script type="text/javascript">
37079  */
37080
37081 // private - not really -- you end up using it !
37082 // This is a support class used internally by the Grid components
37083
37084 /**
37085  * @class Roo.grid.GridEditor
37086  * @extends Roo.Editor
37087  * Class for creating and editable grid elements.
37088  * @param {Object} config any settings (must include field)
37089  */
37090 Roo.grid.GridEditor = function(field, config){
37091     if (!config && field.field) {
37092         config = field;
37093         field = Roo.factory(config.field, Roo.form);
37094     }
37095     Roo.grid.GridEditor.superclass.constructor.call(this, field, config);
37096     field.monitorTab = false;
37097 };
37098
37099 Roo.extend(Roo.grid.GridEditor, Roo.Editor, {
37100     
37101     /**
37102      * @cfg {Roo.form.Field} field Field to wrap (or xtyped)
37103      */
37104     
37105     alignment: "tl-tl",
37106     autoSize: "width",
37107     hideEl : false,
37108     cls: "x-small-editor x-grid-editor",
37109     shim:false,
37110     shadow:"frame"
37111 });/*
37112  * Based on:
37113  * Ext JS Library 1.1.1
37114  * Copyright(c) 2006-2007, Ext JS, LLC.
37115  *
37116  * Originally Released Under LGPL - original licence link has changed is not relivant.
37117  *
37118  * Fork - LGPL
37119  * <script type="text/javascript">
37120  */
37121   
37122
37123   
37124 Roo.grid.PropertyRecord = Roo.data.Record.create([
37125     {name:'name',type:'string'},  'value'
37126 ]);
37127
37128
37129 Roo.grid.PropertyStore = function(grid, source){
37130     this.grid = grid;
37131     this.store = new Roo.data.Store({
37132         recordType : Roo.grid.PropertyRecord
37133     });
37134     this.store.on('update', this.onUpdate,  this);
37135     if(source){
37136         this.setSource(source);
37137     }
37138     Roo.grid.PropertyStore.superclass.constructor.call(this);
37139 };
37140
37141
37142
37143 Roo.extend(Roo.grid.PropertyStore, Roo.util.Observable, {
37144     setSource : function(o){
37145         this.source = o;
37146         this.store.removeAll();
37147         var data = [];
37148         for(var k in o){
37149             if(this.isEditableValue(o[k])){
37150                 data.push(new Roo.grid.PropertyRecord({name: k, value: o[k]}, k));
37151             }
37152         }
37153         this.store.loadRecords({records: data}, {}, true);
37154     },
37155
37156     onUpdate : function(ds, record, type){
37157         if(type == Roo.data.Record.EDIT){
37158             var v = record.data['value'];
37159             var oldValue = record.modified['value'];
37160             if(this.grid.fireEvent('beforepropertychange', this.source, record.id, v, oldValue) !== false){
37161                 this.source[record.id] = v;
37162                 record.commit();
37163                 this.grid.fireEvent('propertychange', this.source, record.id, v, oldValue);
37164             }else{
37165                 record.reject();
37166             }
37167         }
37168     },
37169
37170     getProperty : function(row){
37171        return this.store.getAt(row);
37172     },
37173
37174     isEditableValue: function(val){
37175         if(val && val instanceof Date){
37176             return true;
37177         }else if(typeof val == 'object' || typeof val == 'function'){
37178             return false;
37179         }
37180         return true;
37181     },
37182
37183     setValue : function(prop, value){
37184         this.source[prop] = value;
37185         this.store.getById(prop).set('value', value);
37186     },
37187
37188     getSource : function(){
37189         return this.source;
37190     }
37191 });
37192
37193 Roo.grid.PropertyColumnModel = function(grid, store){
37194     this.grid = grid;
37195     var g = Roo.grid;
37196     g.PropertyColumnModel.superclass.constructor.call(this, [
37197         {header: this.nameText, sortable: true, dataIndex:'name', id: 'name'},
37198         {header: this.valueText, resizable:false, dataIndex: 'value', id: 'value'}
37199     ]);
37200     this.store = store;
37201     this.bselect = Roo.DomHelper.append(document.body, {
37202         tag: 'select', style:'display:none', cls: 'x-grid-editor', children: [
37203             {tag: 'option', value: 'true', html: 'true'},
37204             {tag: 'option', value: 'false', html: 'false'}
37205         ]
37206     });
37207     Roo.id(this.bselect);
37208     var f = Roo.form;
37209     this.editors = {
37210         'date' : new g.GridEditor(new f.DateField({selectOnFocus:true})),
37211         'string' : new g.GridEditor(new f.TextField({selectOnFocus:true})),
37212         'number' : new g.GridEditor(new f.NumberField({selectOnFocus:true, style:'text-align:left;'})),
37213         'int' : new g.GridEditor(new f.NumberField({selectOnFocus:true, allowDecimals:false, style:'text-align:left;'})),
37214         'boolean' : new g.GridEditor(new f.Field({el:this.bselect,selectOnFocus:true}))
37215     };
37216     this.renderCellDelegate = this.renderCell.createDelegate(this);
37217     this.renderPropDelegate = this.renderProp.createDelegate(this);
37218 };
37219
37220 Roo.extend(Roo.grid.PropertyColumnModel, Roo.grid.ColumnModel, {
37221     
37222     
37223     nameText : 'Name',
37224     valueText : 'Value',
37225     
37226     dateFormat : 'm/j/Y',
37227     
37228     
37229     renderDate : function(dateVal){
37230         return dateVal.dateFormat(this.dateFormat);
37231     },
37232
37233     renderBool : function(bVal){
37234         return bVal ? 'true' : 'false';
37235     },
37236
37237     isCellEditable : function(colIndex, rowIndex){
37238         return colIndex == 1;
37239     },
37240
37241     getRenderer : function(col){
37242         return col == 1 ?
37243             this.renderCellDelegate : this.renderPropDelegate;
37244     },
37245
37246     renderProp : function(v){
37247         return this.getPropertyName(v);
37248     },
37249
37250     renderCell : function(val){
37251         var rv = val;
37252         if(val instanceof Date){
37253             rv = this.renderDate(val);
37254         }else if(typeof val == 'boolean'){
37255             rv = this.renderBool(val);
37256         }
37257         return Roo.util.Format.htmlEncode(rv);
37258     },
37259
37260     getPropertyName : function(name){
37261         var pn = this.grid.propertyNames;
37262         return pn && pn[name] ? pn[name] : name;
37263     },
37264
37265     getCellEditor : function(colIndex, rowIndex){
37266         var p = this.store.getProperty(rowIndex);
37267         var n = p.data['name'], val = p.data['value'];
37268         
37269         if(typeof(this.grid.customEditors[n]) == 'string'){
37270             return this.editors[this.grid.customEditors[n]];
37271         }
37272         if(typeof(this.grid.customEditors[n]) != 'undefined'){
37273             return this.grid.customEditors[n];
37274         }
37275         if(val instanceof Date){
37276             return this.editors['date'];
37277         }else if(typeof val == 'number'){
37278             return this.editors['number'];
37279         }else if(typeof val == 'boolean'){
37280             return this.editors['boolean'];
37281         }else{
37282             return this.editors['string'];
37283         }
37284     }
37285 });
37286
37287 /**
37288  * @class Roo.grid.PropertyGrid
37289  * @extends Roo.grid.EditorGrid
37290  * This class represents the  interface of a component based property grid control.
37291  * <br><br>Usage:<pre><code>
37292  var grid = new Roo.grid.PropertyGrid("my-container-id", {
37293       
37294  });
37295  // set any options
37296  grid.render();
37297  * </code></pre>
37298   
37299  * @constructor
37300  * @param {String/HTMLElement/Roo.Element} container The element into which this grid will be rendered -
37301  * The container MUST have some type of size defined for the grid to fill. The container will be
37302  * automatically set to position relative if it isn't already.
37303  * @param {Object} config A config object that sets properties on this grid.
37304  */
37305 Roo.grid.PropertyGrid = function(container, config){
37306     config = config || {};
37307     var store = new Roo.grid.PropertyStore(this);
37308     this.store = store;
37309     var cm = new Roo.grid.PropertyColumnModel(this, store);
37310     store.store.sort('name', 'ASC');
37311     Roo.grid.PropertyGrid.superclass.constructor.call(this, container, Roo.apply({
37312         ds: store.store,
37313         cm: cm,
37314         enableColLock:false,
37315         enableColumnMove:false,
37316         stripeRows:false,
37317         trackMouseOver: false,
37318         clicksToEdit:1
37319     }, config));
37320     this.getGridEl().addClass('x-props-grid');
37321     this.lastEditRow = null;
37322     this.on('columnresize', this.onColumnResize, this);
37323     this.addEvents({
37324          /**
37325              * @event beforepropertychange
37326              * Fires before a property changes (return false to stop?)
37327              * @param {Roo.grid.PropertyGrid} grid property grid? (check could be store)
37328              * @param {String} id Record Id
37329              * @param {String} newval New Value
37330          * @param {String} oldval Old Value
37331              */
37332         "beforepropertychange": true,
37333         /**
37334              * @event propertychange
37335              * Fires after a property changes
37336              * @param {Roo.grid.PropertyGrid} grid property grid? (check could be store)
37337              * @param {String} id Record Id
37338              * @param {String} newval New Value
37339          * @param {String} oldval Old Value
37340              */
37341         "propertychange": true
37342     });
37343     this.customEditors = this.customEditors || {};
37344 };
37345 Roo.extend(Roo.grid.PropertyGrid, Roo.grid.EditorGrid, {
37346     
37347      /**
37348      * @cfg {Object} customEditors map of colnames=> custom editors.
37349      * the custom editor can be one of the standard ones (date|string|number|int|boolean), or a
37350      * grid editor eg. Roo.grid.GridEditor(new Roo.form.TextArea({selectOnFocus:true})),
37351      * false disables editing of the field.
37352          */
37353     
37354       /**
37355      * @cfg {Object} propertyNames map of property Names to their displayed value
37356          */
37357     
37358     render : function(){
37359         Roo.grid.PropertyGrid.superclass.render.call(this);
37360         this.autoSize.defer(100, this);
37361     },
37362
37363     autoSize : function(){
37364         Roo.grid.PropertyGrid.superclass.autoSize.call(this);
37365         if(this.view){
37366             this.view.fitColumns();
37367         }
37368     },
37369
37370     onColumnResize : function(){
37371         this.colModel.setColumnWidth(1, this.container.getWidth(true)-this.colModel.getColumnWidth(0));
37372         this.autoSize();
37373     },
37374     /**
37375      * Sets the data for the Grid
37376      * accepts a Key => Value object of all the elements avaiable.
37377      * @param {Object} data  to appear in grid.
37378      */
37379     setSource : function(source){
37380         this.store.setSource(source);
37381         //this.autoSize();
37382     },
37383     /**
37384      * Gets all the data from the grid.
37385      * @return {Object} data  data stored in grid
37386      */
37387     getSource : function(){
37388         return this.store.getSource();
37389     }
37390 });/*
37391   
37392  * Licence LGPL
37393  
37394  */
37395  
37396 /**
37397  * @class Roo.grid.Calendar
37398  * @extends Roo.util.Grid
37399  * This class extends the Grid to provide a calendar widget
37400  * <br><br>Usage:<pre><code>
37401  var grid = new Roo.grid.Calendar("my-container-id", {
37402      ds: myDataStore,
37403      cm: myColModel,
37404      selModel: mySelectionModel,
37405      autoSizeColumns: true,
37406      monitorWindowResize: false,
37407      trackMouseOver: true
37408      eventstore : real data store..
37409  });
37410  // set any options
37411  grid.render();
37412   
37413   * @constructor
37414  * @param {String/HTMLElement/Roo.Element} container The element into which this grid will be rendered -
37415  * The container MUST have some type of size defined for the grid to fill. The container will be
37416  * automatically set to position relative if it isn't already.
37417  * @param {Object} config A config object that sets properties on this grid.
37418  */
37419 Roo.grid.Calendar = function(container, config){
37420         // initialize the container
37421         this.container = Roo.get(container);
37422         this.container.update("");
37423         this.container.setStyle("overflow", "hidden");
37424     this.container.addClass('x-grid-container');
37425
37426     this.id = this.container.id;
37427
37428     Roo.apply(this, config);
37429     // check and correct shorthanded configs
37430     
37431     var rows = [];
37432     var d =1;
37433     for (var r = 0;r < 6;r++) {
37434         
37435         rows[r]=[];
37436         for (var c =0;c < 7;c++) {
37437             rows[r][c]= '';
37438         }
37439     }
37440     if (this.eventStore) {
37441         this.eventStore= Roo.factory(this.eventStore, Roo.data);
37442         this.eventStore.on('load',this.onLoad, this);
37443         this.eventStore.on('beforeload',this.clearEvents, this);
37444          
37445     }
37446     
37447     this.dataSource = new Roo.data.Store({
37448             proxy: new Roo.data.MemoryProxy(rows),
37449             reader: new Roo.data.ArrayReader({}, [
37450                    'weekday0', 'weekday1', 'weekday2', 'weekday3', 'weekday4', 'weekday5', 'weekday6' ])
37451     });
37452
37453     this.dataSource.load();
37454     this.ds = this.dataSource;
37455     this.ds.xmodule = this.xmodule || false;
37456     
37457     
37458     var cellRender = function(v,x,r)
37459     {
37460         return String.format(
37461             '<div class="fc-day  fc-widget-content"><div>' +
37462                 '<div class="fc-event-container"></div>' +
37463                 '<div class="fc-day-number">{0}</div>'+
37464                 
37465                 '<div class="fc-day-content"><div style="position:relative"></div></div>' +
37466             '</div></div>', v);
37467     
37468     }
37469     
37470     
37471     this.colModel = new Roo.grid.ColumnModel( [
37472         {
37473             xtype: 'ColumnModel',
37474             xns: Roo.grid,
37475             dataIndex : 'weekday0',
37476             header : 'Sunday',
37477             renderer : cellRender
37478         },
37479         {
37480             xtype: 'ColumnModel',
37481             xns: Roo.grid,
37482             dataIndex : 'weekday1',
37483             header : 'Monday',
37484             renderer : cellRender
37485         },
37486         {
37487             xtype: 'ColumnModel',
37488             xns: Roo.grid,
37489             dataIndex : 'weekday2',
37490             header : 'Tuesday',
37491             renderer : cellRender
37492         },
37493         {
37494             xtype: 'ColumnModel',
37495             xns: Roo.grid,
37496             dataIndex : 'weekday3',
37497             header : 'Wednesday',
37498             renderer : cellRender
37499         },
37500         {
37501             xtype: 'ColumnModel',
37502             xns: Roo.grid,
37503             dataIndex : 'weekday4',
37504             header : 'Thursday',
37505             renderer : cellRender
37506         },
37507         {
37508             xtype: 'ColumnModel',
37509             xns: Roo.grid,
37510             dataIndex : 'weekday5',
37511             header : 'Friday',
37512             renderer : cellRender
37513         },
37514         {
37515             xtype: 'ColumnModel',
37516             xns: Roo.grid,
37517             dataIndex : 'weekday6',
37518             header : 'Saturday',
37519             renderer : cellRender
37520         }
37521     ]);
37522     this.cm = this.colModel;
37523     this.cm.xmodule = this.xmodule || false;
37524  
37525         
37526           
37527     //this.selModel = new Roo.grid.CellSelectionModel();
37528     //this.sm = this.selModel;
37529     //this.selModel.init(this);
37530     
37531     
37532     if(this.width){
37533         this.container.setWidth(this.width);
37534     }
37535
37536     if(this.height){
37537         this.container.setHeight(this.height);
37538     }
37539     /** @private */
37540         this.addEvents({
37541         // raw events
37542         /**
37543          * @event click
37544          * The raw click event for the entire grid.
37545          * @param {Roo.EventObject} e
37546          */
37547         "click" : true,
37548         /**
37549          * @event dblclick
37550          * The raw dblclick event for the entire grid.
37551          * @param {Roo.EventObject} e
37552          */
37553         "dblclick" : true,
37554         /**
37555          * @event contextmenu
37556          * The raw contextmenu event for the entire grid.
37557          * @param {Roo.EventObject} e
37558          */
37559         "contextmenu" : true,
37560         /**
37561          * @event mousedown
37562          * The raw mousedown event for the entire grid.
37563          * @param {Roo.EventObject} e
37564          */
37565         "mousedown" : true,
37566         /**
37567          * @event mouseup
37568          * The raw mouseup event for the entire grid.
37569          * @param {Roo.EventObject} e
37570          */
37571         "mouseup" : true,
37572         /**
37573          * @event mouseover
37574          * The raw mouseover event for the entire grid.
37575          * @param {Roo.EventObject} e
37576          */
37577         "mouseover" : true,
37578         /**
37579          * @event mouseout
37580          * The raw mouseout event for the entire grid.
37581          * @param {Roo.EventObject} e
37582          */
37583         "mouseout" : true,
37584         /**
37585          * @event keypress
37586          * The raw keypress event for the entire grid.
37587          * @param {Roo.EventObject} e
37588          */
37589         "keypress" : true,
37590         /**
37591          * @event keydown
37592          * The raw keydown event for the entire grid.
37593          * @param {Roo.EventObject} e
37594          */
37595         "keydown" : true,
37596
37597         // custom events
37598
37599         /**
37600          * @event cellclick
37601          * Fires when a cell is clicked
37602          * @param {Grid} this
37603          * @param {Number} rowIndex
37604          * @param {Number} columnIndex
37605          * @param {Roo.EventObject} e
37606          */
37607         "cellclick" : true,
37608         /**
37609          * @event celldblclick
37610          * Fires when a cell is double clicked
37611          * @param {Grid} this
37612          * @param {Number} rowIndex
37613          * @param {Number} columnIndex
37614          * @param {Roo.EventObject} e
37615          */
37616         "celldblclick" : true,
37617         /**
37618          * @event rowclick
37619          * Fires when a row is clicked
37620          * @param {Grid} this
37621          * @param {Number} rowIndex
37622          * @param {Roo.EventObject} e
37623          */
37624         "rowclick" : true,
37625         /**
37626          * @event rowdblclick
37627          * Fires when a row is double clicked
37628          * @param {Grid} this
37629          * @param {Number} rowIndex
37630          * @param {Roo.EventObject} e
37631          */
37632         "rowdblclick" : true,
37633         /**
37634          * @event headerclick
37635          * Fires when a header is clicked
37636          * @param {Grid} this
37637          * @param {Number} columnIndex
37638          * @param {Roo.EventObject} e
37639          */
37640         "headerclick" : true,
37641         /**
37642          * @event headerdblclick
37643          * Fires when a header cell is double clicked
37644          * @param {Grid} this
37645          * @param {Number} columnIndex
37646          * @param {Roo.EventObject} e
37647          */
37648         "headerdblclick" : true,
37649         /**
37650          * @event rowcontextmenu
37651          * Fires when a row is right clicked
37652          * @param {Grid} this
37653          * @param {Number} rowIndex
37654          * @param {Roo.EventObject} e
37655          */
37656         "rowcontextmenu" : true,
37657         /**
37658          * @event cellcontextmenu
37659          * Fires when a cell is right clicked
37660          * @param {Grid} this
37661          * @param {Number} rowIndex
37662          * @param {Number} cellIndex
37663          * @param {Roo.EventObject} e
37664          */
37665          "cellcontextmenu" : true,
37666         /**
37667          * @event headercontextmenu
37668          * Fires when a header is right clicked
37669          * @param {Grid} this
37670          * @param {Number} columnIndex
37671          * @param {Roo.EventObject} e
37672          */
37673         "headercontextmenu" : true,
37674         /**
37675          * @event bodyscroll
37676          * Fires when the body element is scrolled
37677          * @param {Number} scrollLeft
37678          * @param {Number} scrollTop
37679          */
37680         "bodyscroll" : true,
37681         /**
37682          * @event columnresize
37683          * Fires when the user resizes a column
37684          * @param {Number} columnIndex
37685          * @param {Number} newSize
37686          */
37687         "columnresize" : true,
37688         /**
37689          * @event columnmove
37690          * Fires when the user moves a column
37691          * @param {Number} oldIndex
37692          * @param {Number} newIndex
37693          */
37694         "columnmove" : true,
37695         /**
37696          * @event startdrag
37697          * Fires when row(s) start being dragged
37698          * @param {Grid} this
37699          * @param {Roo.GridDD} dd The drag drop object
37700          * @param {event} e The raw browser event
37701          */
37702         "startdrag" : true,
37703         /**
37704          * @event enddrag
37705          * Fires when a drag operation is complete
37706          * @param {Grid} this
37707          * @param {Roo.GridDD} dd The drag drop object
37708          * @param {event} e The raw browser event
37709          */
37710         "enddrag" : true,
37711         /**
37712          * @event dragdrop
37713          * Fires when dragged row(s) are dropped on a valid DD target
37714          * @param {Grid} this
37715          * @param {Roo.GridDD} dd The drag drop object
37716          * @param {String} targetId The target drag drop object
37717          * @param {event} e The raw browser event
37718          */
37719         "dragdrop" : true,
37720         /**
37721          * @event dragover
37722          * Fires while row(s) are being dragged. "targetId" is the id of the Yahoo.util.DD object the selected rows are being dragged over.
37723          * @param {Grid} this
37724          * @param {Roo.GridDD} dd The drag drop object
37725          * @param {String} targetId The target drag drop object
37726          * @param {event} e The raw browser event
37727          */
37728         "dragover" : true,
37729         /**
37730          * @event dragenter
37731          *  Fires when the dragged row(s) first cross another DD target while being dragged
37732          * @param {Grid} this
37733          * @param {Roo.GridDD} dd The drag drop object
37734          * @param {String} targetId The target drag drop object
37735          * @param {event} e The raw browser event
37736          */
37737         "dragenter" : true,
37738         /**
37739          * @event dragout
37740          * Fires when the dragged row(s) leave another DD target while being dragged
37741          * @param {Grid} this
37742          * @param {Roo.GridDD} dd The drag drop object
37743          * @param {String} targetId The target drag drop object
37744          * @param {event} e The raw browser event
37745          */
37746         "dragout" : true,
37747         /**
37748          * @event rowclass
37749          * Fires when a row is rendered, so you can change add a style to it.
37750          * @param {GridView} gridview   The grid view
37751          * @param {Object} rowcfg   contains record  rowIndex and rowClass - set rowClass to add a style.
37752          */
37753         'rowclass' : true,
37754
37755         /**
37756          * @event render
37757          * Fires when the grid is rendered
37758          * @param {Grid} grid
37759          */
37760         'render' : true,
37761             /**
37762              * @event select
37763              * Fires when a date is selected
37764              * @param {DatePicker} this
37765              * @param {Date} date The selected date
37766              */
37767         'select': true,
37768         /**
37769              * @event monthchange
37770              * Fires when the displayed month changes 
37771              * @param {DatePicker} this
37772              * @param {Date} date The selected month
37773              */
37774         'monthchange': true,
37775         /**
37776              * @event evententer
37777              * Fires when mouse over an event
37778              * @param {Calendar} this
37779              * @param {event} Event
37780              */
37781         'evententer': true,
37782         /**
37783              * @event eventleave
37784              * Fires when the mouse leaves an
37785              * @param {Calendar} this
37786              * @param {event}
37787              */
37788         'eventleave': true,
37789         /**
37790              * @event eventclick
37791              * Fires when the mouse click an
37792              * @param {Calendar} this
37793              * @param {event}
37794              */
37795         'eventclick': true,
37796         /**
37797              * @event eventrender
37798              * Fires before each cell is rendered, so you can modify the contents, like cls / title / qtip
37799              * @param {Calendar} this
37800              * @param {data} data to be modified
37801              */
37802         'eventrender': true
37803         
37804     });
37805
37806     Roo.grid.Grid.superclass.constructor.call(this);
37807     this.on('render', function() {
37808         this.view.el.addClass('x-grid-cal'); 
37809         
37810         (function() { this.setDate(new Date()); }).defer(100,this); //default today..
37811
37812     },this);
37813     
37814     if (!Roo.grid.Calendar.style) {
37815         Roo.grid.Calendar.style = Roo.util.CSS.createStyleSheet({
37816             
37817             
37818             '.x-grid-cal .x-grid-col' :  {
37819                 height: 'auto !important',
37820                 'vertical-align': 'top'
37821             },
37822             '.x-grid-cal  .fc-event-hori' : {
37823                 height: '14px'
37824             }
37825              
37826             
37827         }, Roo.id());
37828     }
37829
37830     
37831     
37832 };
37833 Roo.extend(Roo.grid.Calendar, Roo.grid.Grid, {
37834     /**
37835      * @cfg {Store} eventStore The store that loads events.
37836      */
37837     eventStore : 25,
37838
37839      
37840     activeDate : false,
37841     startDay : 0,
37842     autoWidth : true,
37843     monitorWindowResize : false,
37844
37845     
37846     resizeColumns : function() {
37847         var col = (this.view.el.getWidth() / 7) - 3;
37848         // loop through cols, and setWidth
37849         for(var i =0 ; i < 7 ; i++){
37850             this.cm.setColumnWidth(i, col);
37851         }
37852     },
37853      setDate :function(date) {
37854         
37855         Roo.log('setDate?');
37856         
37857         this.resizeColumns();
37858         var vd = this.activeDate;
37859         this.activeDate = date;
37860 //        if(vd && this.el){
37861 //            var t = date.getTime();
37862 //            if(vd.getMonth() == date.getMonth() && vd.getFullYear() == date.getFullYear()){
37863 //                Roo.log('using add remove');
37864 //                
37865 //                this.fireEvent('monthchange', this, date);
37866 //                
37867 //                this.cells.removeClass("fc-state-highlight");
37868 //                this.cells.each(function(c){
37869 //                   if(c.dateValue == t){
37870 //                       c.addClass("fc-state-highlight");
37871 //                       setTimeout(function(){
37872 //                            try{c.dom.firstChild.focus();}catch(e){}
37873 //                       }, 50);
37874 //                       return false;
37875 //                   }
37876 //                   return true;
37877 //                });
37878 //                return;
37879 //            }
37880 //        }
37881         
37882         var days = date.getDaysInMonth();
37883         
37884         var firstOfMonth = date.getFirstDateOfMonth();
37885         var startingPos = firstOfMonth.getDay()-this.startDay;
37886         
37887         if(startingPos < this.startDay){
37888             startingPos += 7;
37889         }
37890         
37891         var pm = date.add(Date.MONTH, -1);
37892         var prevStart = pm.getDaysInMonth()-startingPos;
37893 //        
37894         
37895         
37896         this.cells = this.view.el.select('.x-grid-row .x-grid-col',true);
37897         
37898         this.textNodes = this.view.el.query('.x-grid-row .x-grid-col .x-grid-cell-text');
37899         //this.cells.addClassOnOver('fc-state-hover');
37900         
37901         var cells = this.cells.elements;
37902         var textEls = this.textNodes;
37903         
37904         //Roo.each(cells, function(cell){
37905         //    cell.removeClass([ 'fc-past', 'fc-other-month', 'fc-future', 'fc-state-highlight', 'fc-state-disabled']);
37906         //});
37907         
37908         days += startingPos;
37909
37910         // convert everything to numbers so it's fast
37911         var day = 86400000;
37912         var d = (new Date(pm.getFullYear(), pm.getMonth(), prevStart)).clearTime();
37913         //Roo.log(d);
37914         //Roo.log(pm);
37915         //Roo.log(prevStart);
37916         
37917         var today = new Date().clearTime().getTime();
37918         var sel = date.clearTime().getTime();
37919         var min = this.minDate ? this.minDate.clearTime() : Number.NEGATIVE_INFINITY;
37920         var max = this.maxDate ? this.maxDate.clearTime() : Number.POSITIVE_INFINITY;
37921         var ddMatch = this.disabledDatesRE;
37922         var ddText = this.disabledDatesText;
37923         var ddays = this.disabledDays ? this.disabledDays.join("") : false;
37924         var ddaysText = this.disabledDaysText;
37925         var format = this.format;
37926         
37927         var setCellClass = function(cal, cell){
37928             
37929             //Roo.log('set Cell Class');
37930             cell.title = "";
37931             var t = d.getTime();
37932             
37933             //Roo.log(d);
37934             
37935             
37936             cell.dateValue = t;
37937             if(t == today){
37938                 cell.className += " fc-today";
37939                 cell.className += " fc-state-highlight";
37940                 cell.title = cal.todayText;
37941             }
37942             if(t == sel){
37943                 // disable highlight in other month..
37944                 cell.className += " fc-state-highlight";
37945                 
37946             }
37947             // disabling
37948             if(t < min) {
37949                 //cell.className = " fc-state-disabled";
37950                 cell.title = cal.minText;
37951                 return;
37952             }
37953             if(t > max) {
37954                 //cell.className = " fc-state-disabled";
37955                 cell.title = cal.maxText;
37956                 return;
37957             }
37958             if(ddays){
37959                 if(ddays.indexOf(d.getDay()) != -1){
37960                     // cell.title = ddaysText;
37961                    // cell.className = " fc-state-disabled";
37962                 }
37963             }
37964             if(ddMatch && format){
37965                 var fvalue = d.dateFormat(format);
37966                 if(ddMatch.test(fvalue)){
37967                     cell.title = ddText.replace("%0", fvalue);
37968                    cell.className = " fc-state-disabled";
37969                 }
37970             }
37971             
37972             if (!cell.initialClassName) {
37973                 cell.initialClassName = cell.dom.className;
37974             }
37975             
37976             cell.dom.className = cell.initialClassName  + ' ' +  cell.className;
37977         };
37978
37979         var i = 0;
37980         
37981         for(; i < startingPos; i++) {
37982             cells[i].dayName =  (++prevStart);
37983             Roo.log(textEls[i]);
37984             d.setDate(d.getDate()+1);
37985             
37986             //cells[i].className = "fc-past fc-other-month";
37987             setCellClass(this, cells[i]);
37988         }
37989         
37990         var intDay = 0;
37991         
37992         for(; i < days; i++){
37993             intDay = i - startingPos + 1;
37994             cells[i].dayName =  (intDay);
37995             d.setDate(d.getDate()+1);
37996             
37997             cells[i].className = ''; // "x-date-active";
37998             setCellClass(this, cells[i]);
37999         }
38000         var extraDays = 0;
38001         
38002         for(; i < 42; i++) {
38003             //textEls[i].innerHTML = (++extraDays);
38004             
38005             d.setDate(d.getDate()+1);
38006             cells[i].dayName = (++extraDays);
38007             cells[i].className = "fc-future fc-other-month";
38008             setCellClass(this, cells[i]);
38009         }
38010         
38011         //this.el.select('.fc-header-title h2',true).update(Date.monthNames[date.getMonth()] + " " + date.getFullYear());
38012         
38013         var totalRows = Math.ceil((date.getDaysInMonth() + date.getFirstDateOfMonth().getDay()) / 7);
38014         
38015         // this will cause all the cells to mis
38016         var rows= [];
38017         var i =0;
38018         for (var r = 0;r < 6;r++) {
38019             for (var c =0;c < 7;c++) {
38020                 this.ds.getAt(r).set('weekday' + c ,cells[i++].dayName );
38021             }    
38022         }
38023         
38024         this.cells = this.view.el.select('.x-grid-row .x-grid-col',true);
38025         for(i=0;i<cells.length;i++) {
38026             
38027             this.cells.elements[i].dayName = cells[i].dayName ;
38028             this.cells.elements[i].className = cells[i].className;
38029             this.cells.elements[i].initialClassName = cells[i].initialClassName ;
38030             this.cells.elements[i].title = cells[i].title ;
38031             this.cells.elements[i].dateValue = cells[i].dateValue ;
38032         }
38033         
38034         
38035         
38036         
38037         //this.el.select('tr.fc-week.fc-prev-last',true).removeClass('fc-last');
38038         //this.el.select('tr.fc-week.fc-next-last',true).addClass('fc-last').show();
38039         
38040         ////if(totalRows != 6){
38041             //this.el.select('tr.fc-week.fc-last',true).removeClass('fc-last').addClass('fc-next-last').hide();
38042            // this.el.select('tr.fc-week.fc-prev-last',true).addClass('fc-last');
38043        // }
38044         
38045         this.fireEvent('monthchange', this, date);
38046         
38047         
38048     },
38049  /**
38050      * Returns the grid's SelectionModel.
38051      * @return {SelectionModel}
38052      */
38053     getSelectionModel : function(){
38054         if(!this.selModel){
38055             this.selModel = new Roo.grid.CellSelectionModel();
38056         }
38057         return this.selModel;
38058     },
38059
38060     load: function() {
38061         this.eventStore.load()
38062         
38063         
38064         
38065     },
38066     
38067     findCell : function(dt) {
38068         dt = dt.clearTime().getTime();
38069         var ret = false;
38070         this.cells.each(function(c){
38071             //Roo.log("check " +c.dateValue + '?=' + dt);
38072             if(c.dateValue == dt){
38073                 ret = c;
38074                 return false;
38075             }
38076             return true;
38077         });
38078         
38079         return ret;
38080     },
38081     
38082     findCells : function(rec) {
38083         var s = rec.data.start_dt.clone().clearTime().getTime();
38084        // Roo.log(s);
38085         var e= rec.data.end_dt.clone().clearTime().getTime();
38086        // Roo.log(e);
38087         var ret = [];
38088         this.cells.each(function(c){
38089              ////Roo.log("check " +c.dateValue + '<' + e + ' > ' + s);
38090             
38091             if(c.dateValue > e){
38092                 return ;
38093             }
38094             if(c.dateValue < s){
38095                 return ;
38096             }
38097             ret.push(c);
38098         });
38099         
38100         return ret;    
38101     },
38102     
38103     findBestRow: function(cells)
38104     {
38105         var ret = 0;
38106         
38107         for (var i =0 ; i < cells.length;i++) {
38108             ret  = Math.max(cells[i].rows || 0,ret);
38109         }
38110         return ret;
38111         
38112     },
38113     
38114     
38115     addItem : function(rec)
38116     {
38117         // look for vertical location slot in
38118         var cells = this.findCells(rec);
38119         
38120         rec.row = this.findBestRow(cells);
38121         
38122         // work out the location.
38123         
38124         var crow = false;
38125         var rows = [];
38126         for(var i =0; i < cells.length; i++) {
38127             if (!crow) {
38128                 crow = {
38129                     start : cells[i],
38130                     end :  cells[i]
38131                 };
38132                 continue;
38133             }
38134             if (crow.start.getY() == cells[i].getY()) {
38135                 // on same row.
38136                 crow.end = cells[i];
38137                 continue;
38138             }
38139             // different row.
38140             rows.push(crow);
38141             crow = {
38142                 start: cells[i],
38143                 end : cells[i]
38144             };
38145             
38146         }
38147         
38148         rows.push(crow);
38149         rec.els = [];
38150         rec.rows = rows;
38151         rec.cells = cells;
38152         for (var i = 0; i < cells.length;i++) {
38153             cells[i].rows = Math.max(cells[i].rows || 0 , rec.row + 1 );
38154             
38155         }
38156         
38157         
38158     },
38159     
38160     clearEvents: function() {
38161         
38162         if (!this.eventStore.getCount()) {
38163             return;
38164         }
38165         // reset number of rows in cells.
38166         Roo.each(this.cells.elements, function(c){
38167             c.rows = 0;
38168         });
38169         
38170         this.eventStore.each(function(e) {
38171             this.clearEvent(e);
38172         },this);
38173         
38174     },
38175     
38176     clearEvent : function(ev)
38177     {
38178         if (ev.els) {
38179             Roo.each(ev.els, function(el) {
38180                 el.un('mouseenter' ,this.onEventEnter, this);
38181                 el.un('mouseleave' ,this.onEventLeave, this);
38182                 el.remove();
38183             },this);
38184             ev.els = [];
38185         }
38186     },
38187     
38188     
38189     renderEvent : function(ev,ctr) {
38190         if (!ctr) {
38191              ctr = this.view.el.select('.fc-event-container',true).first();
38192         }
38193         
38194          
38195         this.clearEvent(ev);
38196             //code
38197        
38198         
38199         
38200         ev.els = [];
38201         var cells = ev.cells;
38202         var rows = ev.rows;
38203         this.fireEvent('eventrender', this, ev);
38204         
38205         for(var i =0; i < rows.length; i++) {
38206             
38207             cls = '';
38208             if (i == 0) {
38209                 cls += ' fc-event-start';
38210             }
38211             if ((i+1) == rows.length) {
38212                 cls += ' fc-event-end';
38213             }
38214             
38215             //Roo.log(ev.data);
38216             // how many rows should it span..
38217             var cg = this.eventTmpl.append(ctr,Roo.apply({
38218                 fccls : cls
38219                 
38220             }, ev.data) , true);
38221             
38222             
38223             cg.on('mouseenter' ,this.onEventEnter, this, ev);
38224             cg.on('mouseleave' ,this.onEventLeave, this, ev);
38225             cg.on('click', this.onEventClick, this, ev);
38226             
38227             ev.els.push(cg);
38228             
38229             var sbox = rows[i].start.select('.fc-day-content',true).first().getBox();
38230             var ebox = rows[i].end.select('.fc-day-content',true).first().getBox();
38231             //Roo.log(cg);
38232              
38233             cg.setXY([sbox.x +2, sbox.y +(ev.row * 20)]);    
38234             cg.setWidth(ebox.right - sbox.x -2);
38235         }
38236     },
38237     
38238     renderEvents: function()
38239     {   
38240         // first make sure there is enough space..
38241         
38242         if (!this.eventTmpl) {
38243             this.eventTmpl = new Roo.Template(
38244                 '<div class="roo-dynamic fc-event fc-event-hori fc-event-draggable ui-draggable {fccls} {cls}"  style="position: absolute" unselectable="on">' +
38245                     '<div class="fc-event-inner">' +
38246                         '<span class="fc-event-time">{time}</span>' +
38247                         '<span class="fc-event-title" qtip="{qtip}">{title}</span>' +
38248                     '</div>' +
38249                     '<div class="ui-resizable-heandle ui-resizable-e">&nbsp;&nbsp;&nbsp;</div>' +
38250                 '</div>'
38251             );
38252                 
38253         }
38254                
38255         
38256         
38257         this.cells.each(function(c) {
38258             //Roo.log(c.select('.fc-day-content div',true).first());
38259             c.select('.fc-day-content div',true).first().setHeight(Math.max(34, (c.rows || 1) * 20));
38260         });
38261         
38262         var ctr = this.view.el.select('.fc-event-container',true).first();
38263         
38264         var cls;
38265         this.eventStore.each(function(ev){
38266             
38267             this.renderEvent(ev);
38268              
38269              
38270         }, this);
38271         this.view.layout();
38272         
38273     },
38274     
38275     onEventEnter: function (e, el,event,d) {
38276         this.fireEvent('evententer', this, el, event);
38277     },
38278     
38279     onEventLeave: function (e, el,event,d) {
38280         this.fireEvent('eventleave', this, el, event);
38281     },
38282     
38283     onEventClick: function (e, el,event,d) {
38284         this.fireEvent('eventclick', this, el, event);
38285     },
38286     
38287     onMonthChange: function () {
38288         this.store.load();
38289     },
38290     
38291     onLoad: function () {
38292         
38293         //Roo.log('calendar onload');
38294 //         
38295         if(this.eventStore.getCount() > 0){
38296             
38297            
38298             
38299             this.eventStore.each(function(d){
38300                 
38301                 
38302                 // FIXME..
38303                 var add =   d.data;
38304                 if (typeof(add.end_dt) == 'undefined')  {
38305                     Roo.log("Missing End time in calendar data: ");
38306                     Roo.log(d);
38307                     return;
38308                 }
38309                 if (typeof(add.start_dt) == 'undefined')  {
38310                     Roo.log("Missing Start time in calendar data: ");
38311                     Roo.log(d);
38312                     return;
38313                 }
38314                 add.start_dt = typeof(add.start_dt) == 'string' ? Date.parseDate(add.start_dt,'Y-m-d H:i:s') : add.start_dt,
38315                 add.end_dt = typeof(add.end_dt) == 'string' ? Date.parseDate(add.end_dt,'Y-m-d H:i:s') : add.end_dt,
38316                 add.id = add.id || d.id;
38317                 add.title = add.title || '??';
38318                 
38319                 this.addItem(d);
38320                 
38321              
38322             },this);
38323         }
38324         
38325         this.renderEvents();
38326     }
38327     
38328
38329 });
38330 /*
38331  grid : {
38332                 xtype: 'Grid',
38333                 xns: Roo.grid,
38334                 listeners : {
38335                     render : function ()
38336                     {
38337                         _this.grid = this;
38338                         
38339                         if (!this.view.el.hasClass('course-timesheet')) {
38340                             this.view.el.addClass('course-timesheet');
38341                         }
38342                         if (this.tsStyle) {
38343                             this.ds.load({});
38344                             return; 
38345                         }
38346                         Roo.log('width');
38347                         Roo.log(_this.grid.view.el.getWidth());
38348                         
38349                         
38350                         this.tsStyle =  Roo.util.CSS.createStyleSheet({
38351                             '.course-timesheet .x-grid-row' : {
38352                                 height: '80px'
38353                             },
38354                             '.x-grid-row td' : {
38355                                 'vertical-align' : 0
38356                             },
38357                             '.course-edit-link' : {
38358                                 'color' : 'blue',
38359                                 'text-overflow' : 'ellipsis',
38360                                 'overflow' : 'hidden',
38361                                 'white-space' : 'nowrap',
38362                                 'cursor' : 'pointer'
38363                             },
38364                             '.sub-link' : {
38365                                 'color' : 'green'
38366                             },
38367                             '.de-act-sup-link' : {
38368                                 'color' : 'purple',
38369                                 'text-decoration' : 'line-through'
38370                             },
38371                             '.de-act-link' : {
38372                                 'color' : 'red',
38373                                 'text-decoration' : 'line-through'
38374                             },
38375                             '.course-timesheet .course-highlight' : {
38376                                 'border-top-style': 'dashed !important',
38377                                 'border-bottom-bottom': 'dashed !important'
38378                             },
38379                             '.course-timesheet .course-item' : {
38380                                 'font-family'   : 'tahoma, arial, helvetica',
38381                                 'font-size'     : '11px',
38382                                 'overflow'      : 'hidden',
38383                                 'padding-left'  : '10px',
38384                                 'padding-right' : '10px',
38385                                 'padding-top' : '10px' 
38386                             }
38387                             
38388                         }, Roo.id());
38389                                 this.ds.load({});
38390                     }
38391                 },
38392                 autoWidth : true,
38393                 monitorWindowResize : false,
38394                 cellrenderer : function(v,x,r)
38395                 {
38396                     return v;
38397                 },
38398                 sm : {
38399                     xtype: 'CellSelectionModel',
38400                     xns: Roo.grid
38401                 },
38402                 dataSource : {
38403                     xtype: 'Store',
38404                     xns: Roo.data,
38405                     listeners : {
38406                         beforeload : function (_self, options)
38407                         {
38408                             options.params = options.params || {};
38409                             options.params._month = _this.monthField.getValue();
38410                             options.params.limit = 9999;
38411                             options.params['sort'] = 'when_dt';    
38412                             options.params['dir'] = 'ASC';    
38413                             this.proxy.loadResponse = this.loadResponse;
38414                             Roo.log("load?");
38415                             //this.addColumns();
38416                         },
38417                         load : function (_self, records, options)
38418                         {
38419                             _this.grid.view.el.select('.course-edit-link', true).on('click', function() {
38420                                 // if you click on the translation.. you can edit it...
38421                                 var el = Roo.get(this);
38422                                 var id = el.dom.getAttribute('data-id');
38423                                 var d = el.dom.getAttribute('data-date');
38424                                 var t = el.dom.getAttribute('data-time');
38425                                 //var id = this.child('span').dom.textContent;
38426                                 
38427                                 //Roo.log(this);
38428                                 Pman.Dialog.CourseCalendar.show({
38429                                     id : id,
38430                                     when_d : d,
38431                                     when_t : t,
38432                                     productitem_active : id ? 1 : 0
38433                                 }, function() {
38434                                     _this.grid.ds.load({});
38435                                 });
38436                            
38437                            });
38438                            
38439                            _this.panel.fireEvent('resize', [ '', '' ]);
38440                         }
38441                     },
38442                     loadResponse : function(o, success, response){
38443                             // this is overridden on before load..
38444                             
38445                             Roo.log("our code?");       
38446                             //Roo.log(success);
38447                             //Roo.log(response)
38448                             delete this.activeRequest;
38449                             if(!success){
38450                                 this.fireEvent("loadexception", this, o, response);
38451                                 o.request.callback.call(o.request.scope, null, o.request.arg, false);
38452                                 return;
38453                             }
38454                             var result;
38455                             try {
38456                                 result = o.reader.read(response);
38457                             }catch(e){
38458                                 Roo.log("load exception?");
38459                                 this.fireEvent("loadexception", this, o, response, e);
38460                                 o.request.callback.call(o.request.scope, null, o.request.arg, false);
38461                                 return;
38462                             }
38463                             Roo.log("ready...");        
38464                             // loop through result.records;
38465                             // and set this.tdate[date] = [] << array of records..
38466                             _this.tdata  = {};
38467                             Roo.each(result.records, function(r){
38468                                 //Roo.log(r.data);
38469                                 if(typeof(_this.tdata[r.data.when_dt.format('j')]) == 'undefined'){
38470                                     _this.tdata[r.data.when_dt.format('j')] = [];
38471                                 }
38472                                 _this.tdata[r.data.when_dt.format('j')].push(r.data);
38473                             });
38474                             
38475                             //Roo.log(_this.tdata);
38476                             
38477                             result.records = [];
38478                             result.totalRecords = 6;
38479                     
38480                             // let's generate some duumy records for the rows.
38481                             //var st = _this.dateField.getValue();
38482                             
38483                             // work out monday..
38484                             //st = st.add(Date.DAY, -1 * st.format('w'));
38485                             
38486                             var date = Date.parseDate(_this.monthField.getValue(), "Y-m-d");
38487                             
38488                             var firstOfMonth = date.getFirstDayOfMonth();
38489                             var days = date.getDaysInMonth();
38490                             var d = 1;
38491                             var firstAdded = false;
38492                             for (var i = 0; i < result.totalRecords ; i++) {
38493                                 //var d= st.add(Date.DAY, i);
38494                                 var row = {};
38495                                 var added = 0;
38496                                 for(var w = 0 ; w < 7 ; w++){
38497                                     if(!firstAdded && firstOfMonth != w){
38498                                         continue;
38499                                     }
38500                                     if(d > days){
38501                                         continue;
38502                                     }
38503                                     firstAdded = true;
38504                                     var dd = (d > 0 && d < 10) ? "0"+d : d;
38505                                     row['weekday'+w] = String.format(
38506                                                     '<span style="font-size: 16px;"><b>{0}</b></span>'+
38507                                                     '<span class="course-edit-link" style="color:blue;" data-id="0" data-date="{1}"> Add New</span>',
38508                                                     d,
38509                                                     date.format('Y-m-')+dd
38510                                                 );
38511                                     added++;
38512                                     if(typeof(_this.tdata[d]) != 'undefined'){
38513                                         Roo.each(_this.tdata[d], function(r){
38514                                             var is_sub = '';
38515                                             var deactive = '';
38516                                             var id = r.id;
38517                                             var desc = (r.productitem_id_descrip) ? r.productitem_id_descrip : '';
38518                                             if(r.parent_id*1>0){
38519                                                 is_sub = (r.productitem_id_visible*1 < 1) ? 'de-act-sup-link' :'sub-link';
38520                                                 id = r.parent_id;
38521                                             }
38522                                             if(r.productitem_id_visible*1 < 1 && r.parent_id*1 < 1){
38523                                                 deactive = 'de-act-link';
38524                                             }
38525                                             
38526                                             row['weekday'+w] += String.format(
38527                                                     '<br /><span class="course-edit-link {3} {4}" qtip="{5}" data-id="{0}">{2} - {1}</span>',
38528                                                     id, //0
38529                                                     r.product_id_name, //1
38530                                                     r.when_dt.format('h:ia'), //2
38531                                                     is_sub, //3
38532                                                     deactive, //4
38533                                                     desc // 5
38534                                             );
38535                                         });
38536                                     }
38537                                     d++;
38538                                 }
38539                                 
38540                                 // only do this if something added..
38541                                 if(added > 0){ 
38542                                     result.records.push(_this.grid.dataSource.reader.newRow(row));
38543                                 }
38544                                 
38545                                 
38546                                 // push it twice. (second one with an hour..
38547                                 
38548                             }
38549                             //Roo.log(result);
38550                             this.fireEvent("load", this, o, o.request.arg);
38551                             o.request.callback.call(o.request.scope, result, o.request.arg, true);
38552                         },
38553                     sortInfo : {field: 'when_dt', direction : 'ASC' },
38554                     proxy : {
38555                         xtype: 'HttpProxy',
38556                         xns: Roo.data,
38557                         method : 'GET',
38558                         url : baseURL + '/Roo/Shop_course.php'
38559                     },
38560                     reader : {
38561                         xtype: 'JsonReader',
38562                         xns: Roo.data,
38563                         id : 'id',
38564                         fields : [
38565                             {
38566                                 'name': 'id',
38567                                 'type': 'int'
38568                             },
38569                             {
38570                                 'name': 'when_dt',
38571                                 'type': 'string'
38572                             },
38573                             {
38574                                 'name': 'end_dt',
38575                                 'type': 'string'
38576                             },
38577                             {
38578                                 'name': 'parent_id',
38579                                 'type': 'int'
38580                             },
38581                             {
38582                                 'name': 'product_id',
38583                                 'type': 'int'
38584                             },
38585                             {
38586                                 'name': 'productitem_id',
38587                                 'type': 'int'
38588                             },
38589                             {
38590                                 'name': 'guid',
38591                                 'type': 'int'
38592                             }
38593                         ]
38594                     }
38595                 },
38596                 toolbar : {
38597                     xtype: 'Toolbar',
38598                     xns: Roo,
38599                     items : [
38600                         {
38601                             xtype: 'Button',
38602                             xns: Roo.Toolbar,
38603                             listeners : {
38604                                 click : function (_self, e)
38605                                 {
38606                                     var sd = Date.parseDate(_this.monthField.getValue(), "Y-m-d");
38607                                     sd.setMonth(sd.getMonth()-1);
38608                                     _this.monthField.setValue(sd.format('Y-m-d'));
38609                                     _this.grid.ds.load({});
38610                                 }
38611                             },
38612                             text : "Back"
38613                         },
38614                         {
38615                             xtype: 'Separator',
38616                             xns: Roo.Toolbar
38617                         },
38618                         {
38619                             xtype: 'MonthField',
38620                             xns: Roo.form,
38621                             listeners : {
38622                                 render : function (_self)
38623                                 {
38624                                     _this.monthField = _self;
38625                                    // _this.monthField.set  today
38626                                 },
38627                                 select : function (combo, date)
38628                                 {
38629                                     _this.grid.ds.load({});
38630                                 }
38631                             },
38632                             value : (function() { return new Date(); })()
38633                         },
38634                         {
38635                             xtype: 'Separator',
38636                             xns: Roo.Toolbar
38637                         },
38638                         {
38639                             xtype: 'TextItem',
38640                             xns: Roo.Toolbar,
38641                             text : "Blue: in-active, green: in-active sup-event, red: de-active, purple: de-active sup-event"
38642                         },
38643                         {
38644                             xtype: 'Fill',
38645                             xns: Roo.Toolbar
38646                         },
38647                         {
38648                             xtype: 'Button',
38649                             xns: Roo.Toolbar,
38650                             listeners : {
38651                                 click : function (_self, e)
38652                                 {
38653                                     var sd = Date.parseDate(_this.monthField.getValue(), "Y-m-d");
38654                                     sd.setMonth(sd.getMonth()+1);
38655                                     _this.monthField.setValue(sd.format('Y-m-d'));
38656                                     _this.grid.ds.load({});
38657                                 }
38658                             },
38659                             text : "Next"
38660                         }
38661                     ]
38662                 },
38663                  
38664             }
38665         };
38666         
38667         *//*
38668  * Based on:
38669  * Ext JS Library 1.1.1
38670  * Copyright(c) 2006-2007, Ext JS, LLC.
38671  *
38672  * Originally Released Under LGPL - original licence link has changed is not relivant.
38673  *
38674  * Fork - LGPL
38675  * <script type="text/javascript">
38676  */
38677  
38678 /**
38679  * @class Roo.LoadMask
38680  * A simple utility class for generically masking elements while loading data.  If the element being masked has
38681  * an underlying {@link Roo.data.Store}, the masking will be automatically synchronized with the store's loading
38682  * process and the mask element will be cached for reuse.  For all other elements, this mask will replace the
38683  * element's UpdateManager load indicator and will be destroyed after the initial load.
38684  * @constructor
38685  * Create a new LoadMask
38686  * @param {String/HTMLElement/Roo.Element} el The element or DOM node, or its id
38687  * @param {Object} config The config object
38688  */
38689 Roo.LoadMask = function(el, config){
38690     this.el = Roo.get(el);
38691     Roo.apply(this, config);
38692     if(this.store){
38693         this.store.on('beforeload', this.onBeforeLoad, this);
38694         this.store.on('load', this.onLoad, this);
38695         this.store.on('loadexception', this.onLoadException, this);
38696         this.removeMask = false;
38697     }else{
38698         var um = this.el.getUpdateManager();
38699         um.showLoadIndicator = false; // disable the default indicator
38700         um.on('beforeupdate', this.onBeforeLoad, this);
38701         um.on('update', this.onLoad, this);
38702         um.on('failure', this.onLoad, this);
38703         this.removeMask = true;
38704     }
38705 };
38706
38707 Roo.LoadMask.prototype = {
38708     /**
38709      * @cfg {Boolean} removeMask
38710      * True to create a single-use mask that is automatically destroyed after loading (useful for page loads),
38711      * False to persist the mask element reference for multiple uses (e.g., for paged data widgets).  Defaults to false.
38712      */
38713     /**
38714      * @cfg {String} msg
38715      * The text to display in a centered loading message box (defaults to 'Loading...')
38716      */
38717     msg : 'Loading...',
38718     /**
38719      * @cfg {String} msgCls
38720      * The CSS class to apply to the loading message element (defaults to "x-mask-loading")
38721      */
38722     msgCls : 'x-mask-loading',
38723
38724     /**
38725      * Read-only. True if the mask is currently disabled so that it will not be displayed (defaults to false)
38726      * @type Boolean
38727      */
38728     disabled: false,
38729
38730     /**
38731      * Disables the mask to prevent it from being displayed
38732      */
38733     disable : function(){
38734        this.disabled = true;
38735     },
38736
38737     /**
38738      * Enables the mask so that it can be displayed
38739      */
38740     enable : function(){
38741         this.disabled = false;
38742     },
38743     
38744     onLoadException : function()
38745     {
38746         Roo.log(arguments);
38747         
38748         if (typeof(arguments[3]) != 'undefined') {
38749             Roo.MessageBox.alert("Error loading",arguments[3]);
38750         } 
38751         /*
38752         try {
38753             if (this.store && typeof(this.store.reader.jsonData.errorMsg) != 'undefined') {
38754                 Roo.MessageBox.alert("Error loading",this.store.reader.jsonData.errorMsg);
38755             }   
38756         } catch(e) {
38757             
38758         }
38759         */
38760     
38761         (function() { this.el.unmask(this.removeMask); }).defer(50, this);
38762     },
38763     // private
38764     onLoad : function()
38765     {
38766         (function() { this.el.unmask(this.removeMask); }).defer(50, this);
38767     },
38768
38769     // private
38770     onBeforeLoad : function(){
38771         if(!this.disabled){
38772             (function() { this.el.mask(this.msg, this.msgCls); }).defer(50, this);
38773         }
38774     },
38775
38776     // private
38777     destroy : function(){
38778         if(this.store){
38779             this.store.un('beforeload', this.onBeforeLoad, this);
38780             this.store.un('load', this.onLoad, this);
38781             this.store.un('loadexception', this.onLoadException, this);
38782         }else{
38783             var um = this.el.getUpdateManager();
38784             um.un('beforeupdate', this.onBeforeLoad, this);
38785             um.un('update', this.onLoad, this);
38786             um.un('failure', this.onLoad, this);
38787         }
38788     }
38789 };/*
38790  * Based on:
38791  * Ext JS Library 1.1.1
38792  * Copyright(c) 2006-2007, Ext JS, LLC.
38793  *
38794  * Originally Released Under LGPL - original licence link has changed is not relivant.
38795  *
38796  * Fork - LGPL
38797  * <script type="text/javascript">
38798  */
38799
38800
38801 /**
38802  * @class Roo.XTemplate
38803  * @extends Roo.Template
38804  * Provides a template that can have nested templates for loops or conditionals. The syntax is:
38805 <pre><code>
38806 var t = new Roo.XTemplate(
38807         '&lt;select name="{name}"&gt;',
38808                 '&lt;tpl for="options"&gt;&lt;option value="{value:trim}"&gt;{text:ellipsis(10)}&lt;/option&gt;&lt;/tpl&gt;',
38809         '&lt;/select&gt;'
38810 );
38811  
38812 // then append, applying the master template values
38813  </code></pre>
38814  *
38815  * Supported features:
38816  *
38817  *  Tags:
38818
38819 <pre><code>
38820       {a_variable} - output encoded.
38821       {a_variable.format:("Y-m-d")} - call a method on the variable
38822       {a_variable:raw} - unencoded output
38823       {a_variable:toFixed(1,2)} - Roo.util.Format."toFixed"
38824       {a_variable:this.method_on_template(...)} - call a method on the template object.
38825  
38826 </code></pre>
38827  *  The tpl tag:
38828 <pre><code>
38829         &lt;tpl for="a_variable or condition.."&gt;&lt;/tpl&gt;
38830         &lt;tpl if="a_variable or condition"&gt;&lt;/tpl&gt;
38831         &lt;tpl exec="some javascript"&gt;&lt;/tpl&gt;
38832         &lt;tpl name="named_template"&gt;&lt;/tpl&gt; (experimental)
38833   
38834         &lt;tpl for="."&gt;&lt;/tpl&gt; - just iterate the property..
38835         &lt;tpl for=".."&gt;&lt;/tpl&gt; - iterates with the parent (probably the template) 
38836 </code></pre>
38837  *      
38838  */
38839 Roo.XTemplate = function()
38840 {
38841     Roo.XTemplate.superclass.constructor.apply(this, arguments);
38842     if (this.html) {
38843         this.compile();
38844     }
38845 };
38846
38847
38848 Roo.extend(Roo.XTemplate, Roo.Template, {
38849
38850     /**
38851      * The various sub templates
38852      */
38853     tpls : false,
38854     /**
38855      *
38856      * basic tag replacing syntax
38857      * WORD:WORD()
38858      *
38859      * // you can fake an object call by doing this
38860      *  x.t:(test,tesT) 
38861      * 
38862      */
38863     re : /\{([\w-\.]+)(?:\:([\w\.]*)(?:\((.*?)?\))?)?\}/g,
38864
38865     /**
38866      * compile the template
38867      *
38868      * This is not recursive, so I'm not sure how nested templates are really going to be handled..
38869      *
38870      */
38871     compile: function()
38872     {
38873         var s = this.html;
38874      
38875         s = ['<tpl>', s, '</tpl>'].join('');
38876     
38877         var re     = /<tpl\b[^>]*>((?:(?=([^<]+))\2|<(?!tpl\b[^>]*>))*?)<\/tpl>/,
38878             nameRe = /^<tpl\b[^>]*?for="(.*?)"/,
38879             ifRe   = /^<tpl\b[^>]*?if="(.*?)"/,
38880             execRe = /^<tpl\b[^>]*?exec="(.*?)"/,
38881             namedRe = /^<tpl\b[^>]*?name="(\w+)"/,  // named templates..
38882             m,
38883             id     = 0,
38884             tpls   = [];
38885     
38886         while(true == !!(m = s.match(re))){
38887             var forMatch   = m[0].match(nameRe),
38888                 ifMatch   = m[0].match(ifRe),
38889                 execMatch   = m[0].match(execRe),
38890                 namedMatch   = m[0].match(namedRe),
38891                 
38892                 exp  = null, 
38893                 fn   = null,
38894                 exec = null,
38895                 name = forMatch && forMatch[1] ? forMatch[1] : '';
38896                 
38897             if (ifMatch) {
38898                 // if - puts fn into test..
38899                 exp = ifMatch && ifMatch[1] ? ifMatch[1] : null;
38900                 if(exp){
38901                    fn = new Function('values', 'parent', 'with(values){ return '+(Roo.util.Format.htmlDecode(exp))+'; }');
38902                 }
38903             }
38904             
38905             if (execMatch) {
38906                 // exec - calls a function... returns empty if true is  returned.
38907                 exp = execMatch && execMatch[1] ? execMatch[1] : null;
38908                 if(exp){
38909                    exec = new Function('values', 'parent', 'with(values){ '+(Roo.util.Format.htmlDecode(exp))+'; }');
38910                 }
38911             }
38912             
38913             
38914             if (name) {
38915                 // for = 
38916                 switch(name){
38917                     case '.':  name = new Function('values', 'parent', 'with(values){ return values; }'); break;
38918                     case '..': name = new Function('values', 'parent', 'with(values){ return parent; }'); break;
38919                     default:   name = new Function('values', 'parent', 'with(values){ return '+name+'; }');
38920                 }
38921             }
38922             var uid = namedMatch ? namedMatch[1] : id;
38923             
38924             
38925             tpls.push({
38926                 id:     namedMatch ? namedMatch[1] : id,
38927                 target: name,
38928                 exec:   exec,
38929                 test:   fn,
38930                 body:   m[1] || ''
38931             });
38932             if (namedMatch) {
38933                 s = s.replace(m[0], '');
38934             } else { 
38935                 s = s.replace(m[0], '{xtpl'+ id + '}');
38936             }
38937             ++id;
38938         }
38939         this.tpls = [];
38940         for(var i = tpls.length-1; i >= 0; --i){
38941             this.compileTpl(tpls[i]);
38942             this.tpls[tpls[i].id] = tpls[i];
38943         }
38944         this.master = tpls[tpls.length-1];
38945         return this;
38946     },
38947     /**
38948      * same as applyTemplate, except it's done to one of the subTemplates
38949      * when using named templates, you can do:
38950      *
38951      * var str = pl.applySubTemplate('your-name', values);
38952      *
38953      * 
38954      * @param {Number} id of the template
38955      * @param {Object} values to apply to template
38956      * @param {Object} parent (normaly the instance of this object)
38957      */
38958     applySubTemplate : function(id, values, parent)
38959     {
38960         
38961         
38962         var t = this.tpls[id];
38963         
38964         
38965         try { 
38966             if(t.test && !t.test.call(this, values, parent)){
38967                 return '';
38968             }
38969         } catch(e) {
38970             Roo.log("Xtemplate.applySubTemplate 'test': Exception thrown");
38971             Roo.log(e.toString());
38972             Roo.log(t.test);
38973             return ''
38974         }
38975         try { 
38976             
38977             if(t.exec && t.exec.call(this, values, parent)){
38978                 return '';
38979             }
38980         } catch(e) {
38981             Roo.log("Xtemplate.applySubTemplate 'exec': Exception thrown");
38982             Roo.log(e.toString());
38983             Roo.log(t.exec);
38984             return ''
38985         }
38986         try {
38987             var vs = t.target ? t.target.call(this, values, parent) : values;
38988             parent = t.target ? values : parent;
38989             if(t.target && vs instanceof Array){
38990                 var buf = [];
38991                 for(var i = 0, len = vs.length; i < len; i++){
38992                     buf[buf.length] = t.compiled.call(this, vs[i], parent);
38993                 }
38994                 return buf.join('');
38995             }
38996             return t.compiled.call(this, vs, parent);
38997         } catch (e) {
38998             Roo.log("Xtemplate.applySubTemplate : Exception thrown");
38999             Roo.log(e.toString());
39000             Roo.log(t.compiled);
39001             return '';
39002         }
39003     },
39004
39005     compileTpl : function(tpl)
39006     {
39007         var fm = Roo.util.Format;
39008         var useF = this.disableFormats !== true;
39009         var sep = Roo.isGecko ? "+" : ",";
39010         var undef = function(str) {
39011             Roo.log("Property not found :"  + str);
39012             return '';
39013         };
39014         
39015         var fn = function(m, name, format, args)
39016         {
39017             //Roo.log(arguments);
39018             args = args ? args.replace(/\\'/g,"'") : args;
39019             //["{TEST:(a,b,c)}", "TEST", "", "a,b,c", 0, "{TEST:(a,b,c)}"]
39020             if (typeof(format) == 'undefined') {
39021                 format= 'htmlEncode';
39022             }
39023             if (format == 'raw' ) {
39024                 format = false;
39025             }
39026             
39027             if(name.substr(0, 4) == 'xtpl'){
39028                 return "'"+ sep +'this.applySubTemplate('+name.substr(4)+', values, parent)'+sep+"'";
39029             }
39030             
39031             // build an array of options to determine if value is undefined..
39032             
39033             // basically get 'xxxx.yyyy' then do
39034             // (typeof(xxxx) == 'undefined' || typeof(xxx.yyyy) == 'undefined') ?
39035             //    (function () { Roo.log("Property not found"); return ''; })() :
39036             //    ......
39037             
39038             var udef_ar = [];
39039             var lookfor = '';
39040             Roo.each(name.split('.'), function(st) {
39041                 lookfor += (lookfor.length ? '.': '') + st;
39042                 udef_ar.push(  "(typeof(" + lookfor + ") == 'undefined')"  );
39043             });
39044             
39045             var udef_st = '((' + udef_ar.join(" || ") +") ? undef('" + name + "') : "; // .. needs )
39046             
39047             
39048             if(format && useF){
39049                 
39050                 args = args ? ',' + args : "";
39051                  
39052                 if(format.substr(0, 5) != "this."){
39053                     format = "fm." + format + '(';
39054                 }else{
39055                     format = 'this.call("'+ format.substr(5) + '", ';
39056                     args = ", values";
39057                 }
39058                 
39059                 return "'"+ sep +   udef_st   +    format + name + args + "))"+sep+"'";
39060             }
39061              
39062             if (args.length) {
39063                 // called with xxyx.yuu:(test,test)
39064                 // change to ()
39065                 return "'"+ sep + udef_st  + name + '(' +  args + "))"+sep+"'";
39066             }
39067             // raw.. - :raw modifier..
39068             return "'"+ sep + udef_st  + name + ")"+sep+"'";
39069             
39070         };
39071         var body;
39072         // branched to use + in gecko and [].join() in others
39073         if(Roo.isGecko){
39074             body = "tpl.compiled = function(values, parent){  with(values) { return '" +
39075                    tpl.body.replace(/(\r\n|\n)/g, '\\n').replace(/'/g, "\\'").replace(this.re, fn) +
39076                     "';};};";
39077         }else{
39078             body = ["tpl.compiled = function(values, parent){  with (values) { return ['"];
39079             body.push(tpl.body.replace(/(\r\n|\n)/g,
39080                             '\\n').replace(/'/g, "\\'").replace(this.re, fn));
39081             body.push("'].join('');};};");
39082             body = body.join('');
39083         }
39084         
39085         Roo.debug && Roo.log(body.replace(/\\n/,'\n'));
39086        
39087         /** eval:var:tpl eval:var:fm eval:var:useF eval:var:undef  */
39088         eval(body);
39089         
39090         return this;
39091     },
39092
39093     applyTemplate : function(values){
39094         return this.master.compiled.call(this, values, {});
39095         //var s = this.subs;
39096     },
39097
39098     apply : function(){
39099         return this.applyTemplate.apply(this, arguments);
39100     }
39101
39102  });
39103
39104 Roo.XTemplate.from = function(el){
39105     el = Roo.getDom(el);
39106     return new Roo.XTemplate(el.value || el.innerHTML);
39107 };