2038f9e59de3550339af0a4f5f7ca4829492f8c3
[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      * Gets the number of cached records.
790      * <p>
791      * <em>If using paging, this may not be the total size of the dataset. If the data object
792      * used by the Reader contains the dataset size, then the getTotalCount() function returns
793      * the data set size</em>
794      */
795     getCount : function(){
796         return this.data.length || 0;
797     },
798
799     /**
800      * Gets the total number of records in the dataset as returned by the server.
801      * <p>
802      * <em>If using paging, for this to be accurate, the data object used by the Reader must contain
803      * the dataset size</em>
804      */
805     getTotalCount : function(){
806         return this.totalLength || 0;
807     },
808
809     /**
810      * Returns the sort state of the Store as an object with two properties:
811      * <pre><code>
812  field {String} The name of the field by which the Records are sorted
813  direction {String} The sort order, "ASC" or "DESC"
814      * </code></pre>
815      */
816     getSortState : function(){
817         return this.sortInfo;
818     },
819
820     // private
821     applySort : function(){
822         if(this.sortInfo && !this.remoteSort){
823             var s = this.sortInfo, f = s.field;
824             var st = this.fields.get(f).sortType;
825             var fn = function(r1, r2){
826                 var v1 = st(r1.data[f]), v2 = st(r2.data[f]);
827                 return v1 > v2 ? 1 : (v1 < v2 ? -1 : 0);
828             };
829             this.data.sort(s.direction, fn);
830             if(this.snapshot && this.snapshot != this.data){
831                 this.snapshot.sort(s.direction, fn);
832             }
833         }
834     },
835
836     /**
837      * Sets the default sort column and order to be used by the next load operation.
838      * @param {String} fieldName The name of the field to sort by.
839      * @param {String} dir (optional) The sort order, "ASC" or "DESC" (defaults to "ASC")
840      */
841     setDefaultSort : function(field, dir){
842         this.sortInfo = {field: field, direction: dir ? dir.toUpperCase() : "ASC"};
843     },
844
845     /**
846      * Sort the Records.
847      * If remote sorting is used, the sort is performed on the server, and the cache is
848      * reloaded. If local sorting is used, the cache is sorted internally.
849      * @param {String} fieldName The name of the field to sort by.
850      * @param {String} dir (optional) The sort order, "ASC" or "DESC" (defaults to "ASC")
851      */
852     sort : function(fieldName, dir){
853         var f = this.fields.get(fieldName);
854         if(!dir){
855             this.sortToggle[f.name] = this.sortToggle[f.name] || f.sortDir;
856             
857             if(this.multiSort || (this.sortInfo && this.sortInfo.field == f.name) ){ // toggle sort dir
858                 dir = (this.sortToggle[f.name] || "ASC").toggle("ASC", "DESC");
859             }else{
860                 dir = f.sortDir;
861             }
862         }
863         this.sortToggle[f.name] = dir;
864         this.sortInfo = {field: f.name, direction: dir};
865         if(!this.remoteSort){
866             this.applySort();
867             this.fireEvent("datachanged", this);
868         }else{
869             this.load(this.lastOptions);
870         }
871     },
872
873     /**
874      * Calls the specified function for each of the Records in the cache.
875      * @param {Function} fn The function to call. The Record is passed as the first parameter.
876      * Returning <em>false</em> aborts and exits the iteration.
877      * @param {Object} scope (optional) The scope in which to call the function (defaults to the Record).
878      */
879     each : function(fn, scope){
880         this.data.each(fn, scope);
881     },
882
883     /**
884      * Gets all records modified since the last commit.  Modified records are persisted across load operations
885      * (e.g., during paging).
886      * @return {Roo.data.Record[]} An array of Records containing outstanding modifications.
887      */
888     getModifiedRecords : function(){
889         return this.modified;
890     },
891
892     // private
893     createFilterFn : function(property, value, anyMatch){
894         if(!value.exec){ // not a regex
895             value = String(value);
896             if(value.length == 0){
897                 return false;
898             }
899             value = new RegExp((anyMatch === true ? '' : '^') + Roo.escapeRe(value), "i");
900         }
901         return function(r){
902             return value.test(r.data[property]);
903         };
904     },
905
906     /**
907      * Sums the value of <i>property</i> for each record between start and end and returns the result.
908      * @param {String} property A field on your records
909      * @param {Number} start The record index to start at (defaults to 0)
910      * @param {Number} end The last record index to include (defaults to length - 1)
911      * @return {Number} The sum
912      */
913     sum : function(property, start, end){
914         var rs = this.data.items, v = 0;
915         start = start || 0;
916         end = (end || end === 0) ? end : rs.length-1;
917
918         for(var i = start; i <= end; i++){
919             v += (rs[i].data[property] || 0);
920         }
921         return v;
922     },
923
924     /**
925      * Filter the records by a specified property.
926      * @param {String} field A field on your records
927      * @param {String/RegExp} value Either a string that the field
928      * should start with or a RegExp to test against the field
929      * @param {Boolean} anyMatch True to match any part not just the beginning
930      */
931     filter : function(property, value, anyMatch){
932         var fn = this.createFilterFn(property, value, anyMatch);
933         return fn ? this.filterBy(fn) : this.clearFilter();
934     },
935
936     /**
937      * Filter by a function. The specified function will be called with each
938      * record in this data source. If the function returns true the record is included,
939      * otherwise it is filtered.
940      * @param {Function} fn The function to be called, it will receive 2 args (record, id)
941      * @param {Object} scope (optional) The scope of the function (defaults to this)
942      */
943     filterBy : function(fn, scope){
944         this.snapshot = this.snapshot || this.data;
945         this.data = this.queryBy(fn, scope||this);
946         this.fireEvent("datachanged", this);
947     },
948
949     /**
950      * Query the records by a specified property.
951      * @param {String} field A field on your records
952      * @param {String/RegExp} value Either a string that the field
953      * should start with or a RegExp to test against the field
954      * @param {Boolean} anyMatch True to match any part not just the beginning
955      * @return {MixedCollection} Returns an Roo.util.MixedCollection of the matched records
956      */
957     query : function(property, value, anyMatch){
958         var fn = this.createFilterFn(property, value, anyMatch);
959         return fn ? this.queryBy(fn) : this.data.clone();
960     },
961
962     /**
963      * Query by a function. The specified function will be called with each
964      * record in this data source. If the function returns true the record is included
965      * in the results.
966      * @param {Function} fn The function to be called, it will receive 2 args (record, id)
967      * @param {Object} scope (optional) The scope of the function (defaults to this)
968       @return {MixedCollection} Returns an Roo.util.MixedCollection of the matched records
969      **/
970     queryBy : function(fn, scope){
971         var data = this.snapshot || this.data;
972         return data.filterBy(fn, scope||this);
973     },
974
975     /**
976      * Collects unique values for a particular dataIndex from this store.
977      * @param {String} dataIndex The property to collect
978      * @param {Boolean} allowNull (optional) Pass true to allow null, undefined or empty string values
979      * @param {Boolean} bypassFilter (optional) Pass true to collect from all records, even ones which are filtered
980      * @return {Array} An array of the unique values
981      **/
982     collect : function(dataIndex, allowNull, bypassFilter){
983         var d = (bypassFilter === true && this.snapshot) ?
984                 this.snapshot.items : this.data.items;
985         var v, sv, r = [], l = {};
986         for(var i = 0, len = d.length; i < len; i++){
987             v = d[i].data[dataIndex];
988             sv = String(v);
989             if((allowNull || !Roo.isEmpty(v)) && !l[sv]){
990                 l[sv] = true;
991                 r[r.length] = v;
992             }
993         }
994         return r;
995     },
996
997     /**
998      * Revert to a view of the Record cache with no filtering applied.
999      * @param {Boolean} suppressEvent If true the filter is cleared silently without notifying listeners
1000      */
1001     clearFilter : function(suppressEvent){
1002         if(this.snapshot && this.snapshot != this.data){
1003             this.data = this.snapshot;
1004             delete this.snapshot;
1005             if(suppressEvent !== true){
1006                 this.fireEvent("datachanged", this);
1007             }
1008         }
1009     },
1010
1011     // private
1012     afterEdit : function(record){
1013         if(this.modified.indexOf(record) == -1){
1014             this.modified.push(record);
1015         }
1016         this.fireEvent("update", this, record, Roo.data.Record.EDIT);
1017     },
1018     
1019     // private
1020     afterReject : function(record){
1021         this.modified.remove(record);
1022         this.fireEvent("update", this, record, Roo.data.Record.REJECT);
1023     },
1024
1025     // private
1026     afterCommit : function(record){
1027         this.modified.remove(record);
1028         this.fireEvent("update", this, record, Roo.data.Record.COMMIT);
1029     },
1030
1031     /**
1032      * Commit all Records with outstanding changes. To handle updates for changes, subscribe to the
1033      * Store's "update" event, and perform updating when the third parameter is Roo.data.Record.COMMIT.
1034      */
1035     commitChanges : function(){
1036         var m = this.modified.slice(0);
1037         this.modified = [];
1038         for(var i = 0, len = m.length; i < len; i++){
1039             m[i].commit();
1040         }
1041     },
1042
1043     /**
1044      * Cancel outstanding changes on all changed records.
1045      */
1046     rejectChanges : function(){
1047         var m = this.modified.slice(0);
1048         this.modified = [];
1049         for(var i = 0, len = m.length; i < len; i++){
1050             m[i].reject();
1051         }
1052     },
1053
1054     onMetaChange : function(meta, rtype, o){
1055         this.recordType = rtype;
1056         this.fields = rtype.prototype.fields;
1057         delete this.snapshot;
1058         this.sortInfo = meta.sortInfo || this.sortInfo;
1059         this.modified = [];
1060         this.fireEvent('metachange', this, this.reader.meta);
1061     },
1062     
1063     moveIndex : function(data, type)
1064     {
1065         var index = this.indexOf(data);
1066         
1067         var newIndex = index + type;
1068         
1069         this.remove(data);
1070         
1071         this.insert(newIndex, data);
1072         
1073     }
1074 });/*
1075  * Based on:
1076  * Ext JS Library 1.1.1
1077  * Copyright(c) 2006-2007, Ext JS, LLC.
1078  *
1079  * Originally Released Under LGPL - original licence link has changed is not relivant.
1080  *
1081  * Fork - LGPL
1082  * <script type="text/javascript">
1083  */
1084
1085 /**
1086  * @class Roo.data.SimpleStore
1087  * @extends Roo.data.Store
1088  * Small helper class to make creating Stores from Array data easier.
1089  * @cfg {Number} id The array index of the record id. Leave blank to auto generate ids.
1090  * @cfg {Array} fields An array of field definition objects, or field name strings.
1091  * @cfg {Array} data The multi-dimensional array of data
1092  * @constructor
1093  * @param {Object} config
1094  */
1095 Roo.data.SimpleStore = function(config){
1096     Roo.data.SimpleStore.superclass.constructor.call(this, {
1097         isLocal : true,
1098         reader: new Roo.data.ArrayReader({
1099                 id: config.id
1100             },
1101             Roo.data.Record.create(config.fields)
1102         ),
1103         proxy : new Roo.data.MemoryProxy(config.data)
1104     });
1105     this.load();
1106 };
1107 Roo.extend(Roo.data.SimpleStore, Roo.data.Store);/*
1108  * Based on:
1109  * Ext JS Library 1.1.1
1110  * Copyright(c) 2006-2007, Ext JS, LLC.
1111  *
1112  * Originally Released Under LGPL - original licence link has changed is not relivant.
1113  *
1114  * Fork - LGPL
1115  * <script type="text/javascript">
1116  */
1117
1118 /**
1119 /**
1120  * @extends Roo.data.Store
1121  * @class Roo.data.JsonStore
1122  * Small helper class to make creating Stores for JSON data easier. <br/>
1123 <pre><code>
1124 var store = new Roo.data.JsonStore({
1125     url: 'get-images.php',
1126     root: 'images',
1127     fields: ['name', 'url', {name:'size', type: 'float'}, {name:'lastmod', type:'date'}]
1128 });
1129 </code></pre>
1130  * <b>Note: Although they are not listed, this class inherits all of the config options of Store,
1131  * JsonReader and HttpProxy (unless inline data is provided).</b>
1132  * @cfg {Array} fields An array of field definition objects, or field name strings.
1133  * @constructor
1134  * @param {Object} config
1135  */
1136 Roo.data.JsonStore = function(c){
1137     Roo.data.JsonStore.superclass.constructor.call(this, Roo.apply(c, {
1138         proxy: !c.data ? new Roo.data.HttpProxy({url: c.url}) : undefined,
1139         reader: new Roo.data.JsonReader(c, c.fields)
1140     }));
1141 };
1142 Roo.extend(Roo.data.JsonStore, Roo.data.Store);/*
1143  * Based on:
1144  * Ext JS Library 1.1.1
1145  * Copyright(c) 2006-2007, Ext JS, LLC.
1146  *
1147  * Originally Released Under LGPL - original licence link has changed is not relivant.
1148  *
1149  * Fork - LGPL
1150  * <script type="text/javascript">
1151  */
1152
1153  
1154 Roo.data.Field = function(config){
1155     if(typeof config == "string"){
1156         config = {name: config};
1157     }
1158     Roo.apply(this, config);
1159     
1160     if(!this.type){
1161         this.type = "auto";
1162     }
1163     
1164     var st = Roo.data.SortTypes;
1165     // named sortTypes are supported, here we look them up
1166     if(typeof this.sortType == "string"){
1167         this.sortType = st[this.sortType];
1168     }
1169     
1170     // set default sortType for strings and dates
1171     if(!this.sortType){
1172         switch(this.type){
1173             case "string":
1174                 this.sortType = st.asUCString;
1175                 break;
1176             case "date":
1177                 this.sortType = st.asDate;
1178                 break;
1179             default:
1180                 this.sortType = st.none;
1181         }
1182     }
1183
1184     // define once
1185     var stripRe = /[\$,%]/g;
1186
1187     // prebuilt conversion function for this field, instead of
1188     // switching every time we're reading a value
1189     if(!this.convert){
1190         var cv, dateFormat = this.dateFormat;
1191         switch(this.type){
1192             case "":
1193             case "auto":
1194             case undefined:
1195                 cv = function(v){ return v; };
1196                 break;
1197             case "string":
1198                 cv = function(v){ return (v === undefined || v === null) ? '' : String(v); };
1199                 break;
1200             case "int":
1201                 cv = function(v){
1202                     return v !== undefined && v !== null && v !== '' ?
1203                            parseInt(String(v).replace(stripRe, ""), 10) : '';
1204                     };
1205                 break;
1206             case "float":
1207                 cv = function(v){
1208                     return v !== undefined && v !== null && v !== '' ?
1209                            parseFloat(String(v).replace(stripRe, ""), 10) : ''; 
1210                     };
1211                 break;
1212             case "bool":
1213             case "boolean":
1214                 cv = function(v){ return v === true || v === "true" || v == 1; };
1215                 break;
1216             case "date":
1217                 cv = function(v){
1218                     if(!v){
1219                         return '';
1220                     }
1221                     if(v instanceof Date){
1222                         return v;
1223                     }
1224                     if(dateFormat){
1225                         if(dateFormat == "timestamp"){
1226                             return new Date(v*1000);
1227                         }
1228                         return Date.parseDate(v, dateFormat);
1229                     }
1230                     var parsed = Date.parse(v);
1231                     return parsed ? new Date(parsed) : null;
1232                 };
1233              break;
1234             
1235         }
1236         this.convert = cv;
1237     }
1238 };
1239
1240 Roo.data.Field.prototype = {
1241     dateFormat: null,
1242     defaultValue: "",
1243     mapping: null,
1244     sortType : null,
1245     sortDir : "ASC"
1246 };/*
1247  * Based on:
1248  * Ext JS Library 1.1.1
1249  * Copyright(c) 2006-2007, Ext JS, LLC.
1250  *
1251  * Originally Released Under LGPL - original licence link has changed is not relivant.
1252  *
1253  * Fork - LGPL
1254  * <script type="text/javascript">
1255  */
1256  
1257 // Base class for reading structured data from a data source.  This class is intended to be
1258 // extended (see ArrayReader, JsonReader and XmlReader) and should not be created directly.
1259
1260 /**
1261  * @class Roo.data.DataReader
1262  * Base class for reading structured data from a data source.  This class is intended to be
1263  * extended (see {Roo.data.ArrayReader}, {Roo.data.JsonReader} and {Roo.data.XmlReader}) and should not be created directly.
1264  */
1265
1266 Roo.data.DataReader = function(meta, recordType){
1267     
1268     this.meta = meta;
1269     
1270     this.recordType = recordType instanceof Array ? 
1271         Roo.data.Record.create(recordType) : recordType;
1272 };
1273
1274 Roo.data.DataReader.prototype = {
1275      /**
1276      * Create an empty record
1277      * @param {Object} data (optional) - overlay some values
1278      * @return {Roo.data.Record} record created.
1279      */
1280     newRow :  function(d) {
1281         var da =  {};
1282         this.recordType.prototype.fields.each(function(c) {
1283             switch( c.type) {
1284                 case 'int' : da[c.name] = 0; break;
1285                 case 'date' : da[c.name] = new Date(); break;
1286                 case 'float' : da[c.name] = 0.0; break;
1287                 case 'boolean' : da[c.name] = false; break;
1288                 default : da[c.name] = ""; break;
1289             }
1290             
1291         });
1292         return new this.recordType(Roo.apply(da, d));
1293     }
1294     
1295 };/*
1296  * Based on:
1297  * Ext JS Library 1.1.1
1298  * Copyright(c) 2006-2007, Ext JS, LLC.
1299  *
1300  * Originally Released Under LGPL - original licence link has changed is not relivant.
1301  *
1302  * Fork - LGPL
1303  * <script type="text/javascript">
1304  */
1305
1306 /**
1307  * @class Roo.data.DataProxy
1308  * @extends Roo.data.Observable
1309  * This class is an abstract base class for implementations which provide retrieval of
1310  * unformatted data objects.<br>
1311  * <p>
1312  * DataProxy implementations are usually used in conjunction with an implementation of Roo.data.DataReader
1313  * (of the appropriate type which knows how to parse the data object) to provide a block of
1314  * {@link Roo.data.Records} to an {@link Roo.data.Store}.<br>
1315  * <p>
1316  * Custom implementations must implement the load method as described in
1317  * {@link Roo.data.HttpProxy#load}.
1318  */
1319 Roo.data.DataProxy = function(){
1320     this.addEvents({
1321         /**
1322          * @event beforeload
1323          * Fires before a network request is made to retrieve a data object.
1324          * @param {Object} This DataProxy object.
1325          * @param {Object} params The params parameter to the load function.
1326          */
1327         beforeload : true,
1328         /**
1329          * @event load
1330          * Fires before the load method's callback is called.
1331          * @param {Object} This DataProxy object.
1332          * @param {Object} o The data object.
1333          * @param {Object} arg The callback argument object passed to the load function.
1334          */
1335         load : true,
1336         /**
1337          * @event loadexception
1338          * Fires if an Exception occurs during data retrieval.
1339          * @param {Object} This DataProxy object.
1340          * @param {Object} o The data object.
1341          * @param {Object} arg The callback argument object passed to the load function.
1342          * @param {Object} e The Exception.
1343          */
1344         loadexception : true
1345     });
1346     Roo.data.DataProxy.superclass.constructor.call(this);
1347 };
1348
1349 Roo.extend(Roo.data.DataProxy, Roo.util.Observable);
1350
1351     /**
1352      * @cfg {void} listeners (Not available) Constructor blocks listeners from being set
1353      */
1354 /*
1355  * Based on:
1356  * Ext JS Library 1.1.1
1357  * Copyright(c) 2006-2007, Ext JS, LLC.
1358  *
1359  * Originally Released Under LGPL - original licence link has changed is not relivant.
1360  *
1361  * Fork - LGPL
1362  * <script type="text/javascript">
1363  */
1364 /**
1365  * @class Roo.data.MemoryProxy
1366  * An implementation of Roo.data.DataProxy that simply passes the data specified in its constructor
1367  * to the Reader when its load method is called.
1368  * @constructor
1369  * @param {Object} data The data object which the Reader uses to construct a block of Roo.data.Records.
1370  */
1371 Roo.data.MemoryProxy = function(data){
1372     if (data.data) {
1373         data = data.data;
1374     }
1375     Roo.data.MemoryProxy.superclass.constructor.call(this);
1376     this.data = data;
1377 };
1378
1379 Roo.extend(Roo.data.MemoryProxy, Roo.data.DataProxy, {
1380     
1381     /**
1382      * Load data from the requested source (in this case an in-memory
1383      * data object passed to the constructor), read the data object into
1384      * a block of Roo.data.Records using the passed Roo.data.DataReader implementation, and
1385      * process that block using the passed callback.
1386      * @param {Object} params This parameter is not used by the MemoryProxy class.
1387      * @param {Roo.data.DataReader} reader The Reader object which converts the data
1388      * object into a block of Roo.data.Records.
1389      * @param {Function} callback The function into which to pass the block of Roo.data.records.
1390      * The function must be passed <ul>
1391      * <li>The Record block object</li>
1392      * <li>The "arg" argument from the load function</li>
1393      * <li>A boolean success indicator</li>
1394      * </ul>
1395      * @param {Object} scope The scope in which to call the callback
1396      * @param {Object} arg An optional argument which is passed to the callback as its second parameter.
1397      */
1398     load : function(params, reader, callback, scope, arg){
1399         params = params || {};
1400         var result;
1401         try {
1402             result = reader.readRecords(params.data ? params.data :this.data);
1403         }catch(e){
1404             this.fireEvent("loadexception", this, arg, null, e);
1405             callback.call(scope, null, arg, false);
1406             return;
1407         }
1408         callback.call(scope, result, arg, true);
1409     },
1410     
1411     // private
1412     update : function(params, records){
1413         
1414     }
1415 });/*
1416  * Based on:
1417  * Ext JS Library 1.1.1
1418  * Copyright(c) 2006-2007, Ext JS, LLC.
1419  *
1420  * Originally Released Under LGPL - original licence link has changed is not relivant.
1421  *
1422  * Fork - LGPL
1423  * <script type="text/javascript">
1424  */
1425 /**
1426  * @class Roo.data.HttpProxy
1427  * @extends Roo.data.DataProxy
1428  * An implementation of {@link Roo.data.DataProxy} that reads a data object from an {@link Roo.data.Connection} object
1429  * configured to reference a certain URL.<br><br>
1430  * <p>
1431  * <em>Note that this class cannot be used to retrieve data from a domain other than the domain
1432  * from which the running page was served.<br><br>
1433  * <p>
1434  * For cross-domain access to remote data, use an {@link Roo.data.ScriptTagProxy}.</em><br><br>
1435  * <p>
1436  * Be aware that to enable the browser to parse an XML document, the server must set
1437  * the Content-Type header in the HTTP response to "text/xml".
1438  * @constructor
1439  * @param {Object} conn Connection config options to add to each request (e.g. {url: 'foo.php'} or
1440  * an {@link Roo.data.Connection} object.  If a Connection config is passed, the singleton {@link Roo.Ajax} object
1441  * will be used to make the request.
1442  */
1443 Roo.data.HttpProxy = function(conn){
1444     Roo.data.HttpProxy.superclass.constructor.call(this);
1445     // is conn a conn config or a real conn?
1446     this.conn = conn;
1447     this.useAjax = !conn || !conn.events;
1448   
1449 };
1450
1451 Roo.extend(Roo.data.HttpProxy, Roo.data.DataProxy, {
1452     // thse are take from connection...
1453     
1454     /**
1455      * @cfg {String} url (Optional) The default URL to be used for requests to the server. (defaults to undefined)
1456      */
1457     /**
1458      * @cfg {Object} extraParams (Optional) An object containing properties which are used as
1459      * extra parameters to each request made by this object. (defaults to undefined)
1460      */
1461     /**
1462      * @cfg {Object} defaultHeaders (Optional) An object containing request headers which are added
1463      *  to each request made by this object. (defaults to undefined)
1464      */
1465     /**
1466      * @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)
1467      */
1468     /**
1469      * @cfg {Number} timeout (Optional) The timeout in milliseconds to be used for requests. (defaults to 30000)
1470      */
1471      /**
1472      * @cfg {Boolean} autoAbort (Optional) Whether this request should abort any pending requests. (defaults to false)
1473      * @type Boolean
1474      */
1475   
1476
1477     /**
1478      * @cfg {Boolean} disableCaching (Optional) True to add a unique cache-buster param to GET requests. (defaults to true)
1479      * @type Boolean
1480      */
1481     /**
1482      * Return the {@link Roo.data.Connection} object being used by this Proxy.
1483      * @return {Connection} The Connection object. This object may be used to subscribe to events on
1484      * a finer-grained basis than the DataProxy events.
1485      */
1486     getConnection : function(){
1487         return this.useAjax ? Roo.Ajax : this.conn;
1488     },
1489
1490     /**
1491      * Load data from the configured {@link Roo.data.Connection}, read the data object into
1492      * a block of Roo.data.Records using the passed {@link Roo.data.DataReader} implementation, and
1493      * process that block using the passed callback.
1494      * @param {Object} params An object containing properties which are to be used as HTTP parameters
1495      * for the request to the remote server.
1496      * @param {Roo.data.DataReader} reader The Reader object which converts the data
1497      * object into a block of Roo.data.Records.
1498      * @param {Function} callback The function into which to pass the block of Roo.data.Records.
1499      * The function must be passed <ul>
1500      * <li>The Record block object</li>
1501      * <li>The "arg" argument from the load function</li>
1502      * <li>A boolean success indicator</li>
1503      * </ul>
1504      * @param {Object} scope The scope in which to call the callback
1505      * @param {Object} arg An optional argument which is passed to the callback as its second parameter.
1506      */
1507     load : function(params, reader, callback, scope, arg){
1508         if(this.fireEvent("beforeload", this, params) !== false){
1509             var  o = {
1510                 params : params || {},
1511                 request: {
1512                     callback : callback,
1513                     scope : scope,
1514                     arg : arg
1515                 },
1516                 reader: reader,
1517                 callback : this.loadResponse,
1518                 scope: this
1519             };
1520             if(this.useAjax){
1521                 Roo.applyIf(o, this.conn);
1522                 if(this.activeRequest){
1523                     Roo.Ajax.abort(this.activeRequest);
1524                 }
1525                 this.activeRequest = Roo.Ajax.request(o);
1526             }else{
1527                 this.conn.request(o);
1528             }
1529         }else{
1530             callback.call(scope||this, null, arg, false);
1531         }
1532     },
1533
1534     // private
1535     loadResponse : function(o, success, response){
1536         delete this.activeRequest;
1537         if(!success){
1538             this.fireEvent("loadexception", this, o, response);
1539             o.request.callback.call(o.request.scope, null, o.request.arg, false);
1540             return;
1541         }
1542         var result;
1543         try {
1544             result = o.reader.read(response);
1545         }catch(e){
1546             this.fireEvent("loadexception", this, o, response, e);
1547             o.request.callback.call(o.request.scope, null, o.request.arg, false);
1548             return;
1549         }
1550         
1551         this.fireEvent("load", this, o, o.request.arg);
1552         o.request.callback.call(o.request.scope, result, o.request.arg, true);
1553     },
1554
1555     // private
1556     update : function(dataSet){
1557
1558     },
1559
1560     // private
1561     updateResponse : function(dataSet){
1562
1563     }
1564 });/*
1565  * Based on:
1566  * Ext JS Library 1.1.1
1567  * Copyright(c) 2006-2007, Ext JS, LLC.
1568  *
1569  * Originally Released Under LGPL - original licence link has changed is not relivant.
1570  *
1571  * Fork - LGPL
1572  * <script type="text/javascript">
1573  */
1574
1575 /**
1576  * @class Roo.data.ScriptTagProxy
1577  * An implementation of Roo.data.DataProxy that reads a data object from a URL which may be in a domain
1578  * other than the originating domain of the running page.<br><br>
1579  * <p>
1580  * <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
1581  * of the running page, you must use this class, rather than DataProxy.</em><br><br>
1582  * <p>
1583  * The content passed back from a server resource requested by a ScriptTagProxy is executable JavaScript
1584  * source code that is used as the source inside a &lt;script> tag.<br><br>
1585  * <p>
1586  * In order for the browser to process the returned data, the server must wrap the data object
1587  * with a call to a callback function, the name of which is passed as a parameter by the ScriptTagProxy.
1588  * Below is a Java example for a servlet which returns data for either a ScriptTagProxy, or an HttpProxy
1589  * depending on whether the callback name was passed:
1590  * <p>
1591  * <pre><code>
1592 boolean scriptTag = false;
1593 String cb = request.getParameter("callback");
1594 if (cb != null) {
1595     scriptTag = true;
1596     response.setContentType("text/javascript");
1597 } else {
1598     response.setContentType("application/x-json");
1599 }
1600 Writer out = response.getWriter();
1601 if (scriptTag) {
1602     out.write(cb + "(");
1603 }
1604 out.print(dataBlock.toJsonString());
1605 if (scriptTag) {
1606     out.write(");");
1607 }
1608 </pre></code>
1609  *
1610  * @constructor
1611  * @param {Object} config A configuration object.
1612  */
1613 Roo.data.ScriptTagProxy = function(config){
1614     Roo.data.ScriptTagProxy.superclass.constructor.call(this);
1615     Roo.apply(this, config);
1616     this.head = document.getElementsByTagName("head")[0];
1617 };
1618
1619 Roo.data.ScriptTagProxy.TRANS_ID = 1000;
1620
1621 Roo.extend(Roo.data.ScriptTagProxy, Roo.data.DataProxy, {
1622     /**
1623      * @cfg {String} url The URL from which to request the data object.
1624      */
1625     /**
1626      * @cfg {Number} timeout (Optional) The number of milliseconds to wait for a response. Defaults to 30 seconds.
1627      */
1628     timeout : 30000,
1629     /**
1630      * @cfg {String} callbackParam (Optional) The name of the parameter to pass to the server which tells
1631      * the server the name of the callback function set up by the load call to process the returned data object.
1632      * Defaults to "callback".<p>The server-side processing must read this parameter value, and generate
1633      * javascript output which calls this named function passing the data object as its only parameter.
1634      */
1635     callbackParam : "callback",
1636     /**
1637      *  @cfg {Boolean} nocache (Optional) Defaults to true. Disable cacheing by adding a unique parameter
1638      * name to the request.
1639      */
1640     nocache : true,
1641
1642     /**
1643      * Load data from the configured URL, read the data object into
1644      * a block of Roo.data.Records using the passed Roo.data.DataReader implementation, and
1645      * process that block using the passed callback.
1646      * @param {Object} params An object containing properties which are to be used as HTTP parameters
1647      * for the request to the remote server.
1648      * @param {Roo.data.DataReader} reader The Reader object which converts the data
1649      * object into a block of Roo.data.Records.
1650      * @param {Function} callback The function into which to pass the block of Roo.data.Records.
1651      * The function must be passed <ul>
1652      * <li>The Record block object</li>
1653      * <li>The "arg" argument from the load function</li>
1654      * <li>A boolean success indicator</li>
1655      * </ul>
1656      * @param {Object} scope The scope in which to call the callback
1657      * @param {Object} arg An optional argument which is passed to the callback as its second parameter.
1658      */
1659     load : function(params, reader, callback, scope, arg){
1660         if(this.fireEvent("beforeload", this, params) !== false){
1661
1662             var p = Roo.urlEncode(Roo.apply(params, this.extraParams));
1663
1664             var url = this.url;
1665             url += (url.indexOf("?") != -1 ? "&" : "?") + p;
1666             if(this.nocache){
1667                 url += "&_dc=" + (new Date().getTime());
1668             }
1669             var transId = ++Roo.data.ScriptTagProxy.TRANS_ID;
1670             var trans = {
1671                 id : transId,
1672                 cb : "stcCallback"+transId,
1673                 scriptId : "stcScript"+transId,
1674                 params : params,
1675                 arg : arg,
1676                 url : url,
1677                 callback : callback,
1678                 scope : scope,
1679                 reader : reader
1680             };
1681             var conn = this;
1682
1683             window[trans.cb] = function(o){
1684                 conn.handleResponse(o, trans);
1685             };
1686
1687             url += String.format("&{0}={1}", this.callbackParam, trans.cb);
1688
1689             if(this.autoAbort !== false){
1690                 this.abort();
1691             }
1692
1693             trans.timeoutId = this.handleFailure.defer(this.timeout, this, [trans]);
1694
1695             var script = document.createElement("script");
1696             script.setAttribute("src", url);
1697             script.setAttribute("type", "text/javascript");
1698             script.setAttribute("id", trans.scriptId);
1699             this.head.appendChild(script);
1700
1701             this.trans = trans;
1702         }else{
1703             callback.call(scope||this, null, arg, false);
1704         }
1705     },
1706
1707     // private
1708     isLoading : function(){
1709         return this.trans ? true : false;
1710     },
1711
1712     /**
1713      * Abort the current server request.
1714      */
1715     abort : function(){
1716         if(this.isLoading()){
1717             this.destroyTrans(this.trans);
1718         }
1719     },
1720
1721     // private
1722     destroyTrans : function(trans, isLoaded){
1723         this.head.removeChild(document.getElementById(trans.scriptId));
1724         clearTimeout(trans.timeoutId);
1725         if(isLoaded){
1726             window[trans.cb] = undefined;
1727             try{
1728                 delete window[trans.cb];
1729             }catch(e){}
1730         }else{
1731             // if hasn't been loaded, wait for load to remove it to prevent script error
1732             window[trans.cb] = function(){
1733                 window[trans.cb] = undefined;
1734                 try{
1735                     delete window[trans.cb];
1736                 }catch(e){}
1737             };
1738         }
1739     },
1740
1741     // private
1742     handleResponse : function(o, trans){
1743         this.trans = false;
1744         this.destroyTrans(trans, true);
1745         var result;
1746         try {
1747             result = trans.reader.readRecords(o);
1748         }catch(e){
1749             this.fireEvent("loadexception", this, o, trans.arg, e);
1750             trans.callback.call(trans.scope||window, null, trans.arg, false);
1751             return;
1752         }
1753         this.fireEvent("load", this, o, trans.arg);
1754         trans.callback.call(trans.scope||window, result, trans.arg, true);
1755     },
1756
1757     // private
1758     handleFailure : function(trans){
1759         this.trans = false;
1760         this.destroyTrans(trans, false);
1761         this.fireEvent("loadexception", this, null, trans.arg);
1762         trans.callback.call(trans.scope||window, null, trans.arg, false);
1763     }
1764 });/*
1765  * Based on:
1766  * Ext JS Library 1.1.1
1767  * Copyright(c) 2006-2007, Ext JS, LLC.
1768  *
1769  * Originally Released Under LGPL - original licence link has changed is not relivant.
1770  *
1771  * Fork - LGPL
1772  * <script type="text/javascript">
1773  */
1774
1775 /**
1776  * @class Roo.data.JsonReader
1777  * @extends Roo.data.DataReader
1778  * Data reader class to create an Array of Roo.data.Record objects from a JSON response
1779  * based on mappings in a provided Roo.data.Record constructor.
1780  * 
1781  * The default behaviour of a store is to send ?_requestMeta=1, unless the class has recieved 'metaData' property
1782  * in the reply previously. 
1783  * 
1784  * <p>
1785  * Example code:
1786  * <pre><code>
1787 var RecordDef = Roo.data.Record.create([
1788     {name: 'name', mapping: 'name'},     // "mapping" property not needed if it's the same as "name"
1789     {name: 'occupation'}                 // This field will use "occupation" as the mapping.
1790 ]);
1791 var myReader = new Roo.data.JsonReader({
1792     totalProperty: "results",    // The property which contains the total dataset size (optional)
1793     root: "rows",                // The property which contains an Array of row objects
1794     id: "id"                     // The property within each row object that provides an ID for the record (optional)
1795 }, RecordDef);
1796 </code></pre>
1797  * <p>
1798  * This would consume a JSON file like this:
1799  * <pre><code>
1800 { 'results': 2, 'rows': [
1801     { 'id': 1, 'name': 'Bill', occupation: 'Gardener' },
1802     { 'id': 2, 'name': 'Ben', occupation: 'Horticulturalist' } ]
1803 }
1804 </code></pre>
1805  * @cfg {String} totalProperty Name of the property from which to retrieve the total number of records
1806  * in the dataset. This is only needed if the whole dataset is not passed in one go, but is being
1807  * paged from the remote server.
1808  * @cfg {String} successProperty Name of the property from which to retrieve the success attribute used by forms.
1809  * @cfg {String} root name of the property which contains the Array of row objects.
1810  * @cfg {String} id Name of the property within a row object that contains a record identifier value.
1811  * @cfg {Array} fields Array of field definition objects
1812  * @constructor
1813  * Create a new JsonReader
1814  * @param {Object} meta Metadata configuration options
1815  * @param {Object} recordType Either an Array of field definition objects,
1816  * or an {@link Roo.data.Record} object created using {@link Roo.data.Record#create}.
1817  */
1818 Roo.data.JsonReader = function(meta, recordType){
1819     
1820     meta = meta || {};
1821     // set some defaults:
1822     Roo.applyIf(meta, {
1823         totalProperty: 'total',
1824         successProperty : 'success',
1825         root : 'data',
1826         id : 'id'
1827     });
1828     
1829     Roo.data.JsonReader.superclass.constructor.call(this, meta, recordType||meta.fields);
1830 };
1831 Roo.extend(Roo.data.JsonReader, Roo.data.DataReader, {
1832     
1833     /**
1834      * @prop {Boolean} metaFromRemote  - if the meta data was loaded from the remote source.
1835      * Used by Store query builder to append _requestMeta to params.
1836      * 
1837      */
1838     metaFromRemote : false,
1839     /**
1840      * This method is only used by a DataProxy which has retrieved data from a remote server.
1841      * @param {Object} response The XHR object which contains the JSON data in its responseText.
1842      * @return {Object} data A data block which is used by an Roo.data.Store object as
1843      * a cache of Roo.data.Records.
1844      */
1845     read : function(response){
1846         var json = response.responseText;
1847        
1848         var o = /* eval:var:o */ eval("("+json+")");
1849         if(!o) {
1850             throw {message: "JsonReader.read: Json object not found"};
1851         }
1852         
1853         if(o.metaData){
1854             
1855             delete this.ef;
1856             this.metaFromRemote = true;
1857             this.meta = o.metaData;
1858             this.recordType = Roo.data.Record.create(o.metaData.fields);
1859             this.onMetaChange(this.meta, this.recordType, o);
1860         }
1861         return this.readRecords(o);
1862     },
1863
1864     // private function a store will implement
1865     onMetaChange : function(meta, recordType, o){
1866
1867     },
1868
1869     /**
1870          * @ignore
1871          */
1872     simpleAccess: function(obj, subsc) {
1873         return obj[subsc];
1874     },
1875
1876         /**
1877          * @ignore
1878          */
1879     getJsonAccessor: function(){
1880         var re = /[\[\.]/;
1881         return function(expr) {
1882             try {
1883                 return(re.test(expr))
1884                     ? new Function("obj", "return obj." + expr)
1885                     : function(obj){
1886                         return obj[expr];
1887                     };
1888             } catch(e){}
1889             return Roo.emptyFn;
1890         };
1891     }(),
1892
1893     /**
1894      * Create a data block containing Roo.data.Records from an XML document.
1895      * @param {Object} o An object which contains an Array of row objects in the property specified
1896      * in the config as 'root, and optionally a property, specified in the config as 'totalProperty'
1897      * which contains the total size of the dataset.
1898      * @return {Object} data A data block which is used by an Roo.data.Store object as
1899      * a cache of Roo.data.Records.
1900      */
1901     readRecords : function(o){
1902         /**
1903          * After any data loads, the raw JSON data is available for further custom processing.
1904          * @type Object
1905          */
1906         this.o = o;
1907         var s = this.meta, Record = this.recordType,
1908             f = Record ? Record.prototype.fields : null, fi = f ? f.items : [], fl = f ? f.length : 0;
1909
1910 //      Generate extraction functions for the totalProperty, the root, the id, and for each field
1911         if (!this.ef) {
1912             if(s.totalProperty) {
1913                     this.getTotal = this.getJsonAccessor(s.totalProperty);
1914                 }
1915                 if(s.successProperty) {
1916                     this.getSuccess = this.getJsonAccessor(s.successProperty);
1917                 }
1918                 this.getRoot = s.root ? this.getJsonAccessor(s.root) : function(p){return p;};
1919                 if (s.id) {
1920                         var g = this.getJsonAccessor(s.id);
1921                         this.getId = function(rec) {
1922                                 var r = g(rec);  
1923                                 return (r === undefined || r === "") ? null : r;
1924                         };
1925                 } else {
1926                         this.getId = function(){return null;};
1927                 }
1928             this.ef = [];
1929             for(var jj = 0; jj < fl; jj++){
1930                 f = fi[jj];
1931                 var map = (f.mapping !== undefined && f.mapping !== null) ? f.mapping : f.name;
1932                 this.ef[jj] = this.getJsonAccessor(map);
1933             }
1934         }
1935
1936         var root = this.getRoot(o), c = root.length, totalRecords = c, success = true;
1937         if(s.totalProperty){
1938             var vt = parseInt(this.getTotal(o), 10);
1939             if(!isNaN(vt)){
1940                 totalRecords = vt;
1941             }
1942         }
1943         if(s.successProperty){
1944             var vs = this.getSuccess(o);
1945             if(vs === false || vs === 'false'){
1946                 success = false;
1947             }
1948         }
1949         var records = [];
1950         for(var i = 0; i < c; i++){
1951                 var n = root[i];
1952             var values = {};
1953             var id = this.getId(n);
1954             for(var j = 0; j < fl; j++){
1955                 f = fi[j];
1956             var v = this.ef[j](n);
1957             if (!f.convert) {
1958                 Roo.log('missing convert for ' + f.name);
1959                 Roo.log(f);
1960                 continue;
1961             }
1962             values[f.name] = f.convert((v !== undefined) ? v : f.defaultValue);
1963             }
1964             var record = new Record(values, id);
1965             record.json = n;
1966             records[i] = record;
1967         }
1968         return {
1969             raw : o,
1970             success : success,
1971             records : records,
1972             totalRecords : totalRecords
1973         };
1974     }
1975 });/*
1976  * Based on:
1977  * Ext JS Library 1.1.1
1978  * Copyright(c) 2006-2007, Ext JS, LLC.
1979  *
1980  * Originally Released Under LGPL - original licence link has changed is not relivant.
1981  *
1982  * Fork - LGPL
1983  * <script type="text/javascript">
1984  */
1985
1986 /**
1987  * @class Roo.data.XmlReader
1988  * @extends Roo.data.DataReader
1989  * Data reader class to create an Array of {@link Roo.data.Record} objects from an XML document
1990  * based on mappings in a provided Roo.data.Record constructor.<br><br>
1991  * <p>
1992  * <em>Note that in order for the browser to parse a returned XML document, the Content-Type
1993  * header in the HTTP response must be set to "text/xml".</em>
1994  * <p>
1995  * Example code:
1996  * <pre><code>
1997 var RecordDef = Roo.data.Record.create([
1998    {name: 'name', mapping: 'name'},     // "mapping" property not needed if it's the same as "name"
1999    {name: 'occupation'}                 // This field will use "occupation" as the mapping.
2000 ]);
2001 var myReader = new Roo.data.XmlReader({
2002    totalRecords: "results", // The element which contains the total dataset size (optional)
2003    record: "row",           // The repeated element which contains row information
2004    id: "id"                 // The element within the row that provides an ID for the record (optional)
2005 }, RecordDef);
2006 </code></pre>
2007  * <p>
2008  * This would consume an XML file like this:
2009  * <pre><code>
2010 &lt;?xml?>
2011 &lt;dataset>
2012  &lt;results>2&lt;/results>
2013  &lt;row>
2014    &lt;id>1&lt;/id>
2015    &lt;name>Bill&lt;/name>
2016    &lt;occupation>Gardener&lt;/occupation>
2017  &lt;/row>
2018  &lt;row>
2019    &lt;id>2&lt;/id>
2020    &lt;name>Ben&lt;/name>
2021    &lt;occupation>Horticulturalist&lt;/occupation>
2022  &lt;/row>
2023 &lt;/dataset>
2024 </code></pre>
2025  * @cfg {String} totalRecords The DomQuery path from which to retrieve the total number of records
2026  * in the dataset. This is only needed if the whole dataset is not passed in one go, but is being
2027  * paged from the remote server.
2028  * @cfg {String} record The DomQuery path to the repeated element which contains record information.
2029  * @cfg {String} success The DomQuery path to the success attribute used by forms.
2030  * @cfg {String} id The DomQuery path relative from the record element to the element that contains
2031  * a record identifier value.
2032  * @constructor
2033  * Create a new XmlReader
2034  * @param {Object} meta Metadata configuration options
2035  * @param {Mixed} recordType The definition of the data record type to produce.  This can be either a valid
2036  * Record subclass created with {@link Roo.data.Record#create}, or an array of objects with which to call
2037  * Roo.data.Record.create.  See the {@link Roo.data.Record} class for more details.
2038  */
2039 Roo.data.XmlReader = function(meta, recordType){
2040     meta = meta || {};
2041     Roo.data.XmlReader.superclass.constructor.call(this, meta, recordType||meta.fields);
2042 };
2043 Roo.extend(Roo.data.XmlReader, Roo.data.DataReader, {
2044     /**
2045      * This method is only used by a DataProxy which has retrieved data from a remote server.
2046          * @param {Object} response The XHR object which contains the parsed XML document.  The response is expected
2047          * to contain a method called 'responseXML' that returns an XML document object.
2048      * @return {Object} records A data block which is used by an {@link Roo.data.Store} as
2049      * a cache of Roo.data.Records.
2050      */
2051     read : function(response){
2052         var doc = response.responseXML;
2053         if(!doc) {
2054             throw {message: "XmlReader.read: XML Document not available"};
2055         }
2056         return this.readRecords(doc);
2057     },
2058
2059     /**
2060      * Create a data block containing Roo.data.Records from an XML document.
2061          * @param {Object} doc A parsed XML document.
2062      * @return {Object} records A data block which is used by an {@link Roo.data.Store} as
2063      * a cache of Roo.data.Records.
2064      */
2065     readRecords : function(doc){
2066         /**
2067          * After any data loads/reads, the raw XML Document is available for further custom processing.
2068          * @type XMLDocument
2069          */
2070         this.xmlData = doc;
2071         var root = doc.documentElement || doc;
2072         var q = Roo.DomQuery;
2073         var recordType = this.recordType, fields = recordType.prototype.fields;
2074         var sid = this.meta.id;
2075         var totalRecords = 0, success = true;
2076         if(this.meta.totalRecords){
2077             totalRecords = q.selectNumber(this.meta.totalRecords, root, 0);
2078         }
2079         
2080         if(this.meta.success){
2081             var sv = q.selectValue(this.meta.success, root, true);
2082             success = sv !== false && sv !== 'false';
2083         }
2084         var records = [];
2085         var ns = q.select(this.meta.record, root);
2086         for(var i = 0, len = ns.length; i < len; i++) {
2087                 var n = ns[i];
2088                 var values = {};
2089                 var id = sid ? q.selectValue(sid, n) : undefined;
2090                 for(var j = 0, jlen = fields.length; j < jlen; j++){
2091                     var f = fields.items[j];
2092                 var v = q.selectValue(f.mapping || f.name, n, f.defaultValue);
2093                     v = f.convert(v);
2094                     values[f.name] = v;
2095                 }
2096                 var record = new recordType(values, id);
2097                 record.node = n;
2098                 records[records.length] = record;
2099             }
2100
2101             return {
2102                 success : success,
2103                 records : records,
2104                 totalRecords : totalRecords || records.length
2105             };
2106     }
2107 });/*
2108  * Based on:
2109  * Ext JS Library 1.1.1
2110  * Copyright(c) 2006-2007, Ext JS, LLC.
2111  *
2112  * Originally Released Under LGPL - original licence link has changed is not relivant.
2113  *
2114  * Fork - LGPL
2115  * <script type="text/javascript">
2116  */
2117
2118 /**
2119  * @class Roo.data.ArrayReader
2120  * @extends Roo.data.DataReader
2121  * Data reader class to create an Array of Roo.data.Record objects from an Array.
2122  * Each element of that Array represents a row of data fields. The
2123  * fields are pulled into a Record object using as a subscript, the <em>mapping</em> property
2124  * of the field definition if it exists, or the field's ordinal position in the definition.<br>
2125  * <p>
2126  * Example code:.
2127  * <pre><code>
2128 var RecordDef = Roo.data.Record.create([
2129     {name: 'name', mapping: 1},         // "mapping" only needed if an "id" field is present which
2130     {name: 'occupation', mapping: 2}    // precludes using the ordinal position as the index.
2131 ]);
2132 var myReader = new Roo.data.ArrayReader({
2133     id: 0                     // The subscript within row Array that provides an ID for the Record (optional)
2134 }, RecordDef);
2135 </code></pre>
2136  * <p>
2137  * This would consume an Array like this:
2138  * <pre><code>
2139 [ [1, 'Bill', 'Gardener'], [2, 'Ben', 'Horticulturalist'] ]
2140   </code></pre>
2141  
2142  * @constructor
2143  * Create a new JsonReader
2144  * @param {Object} meta Metadata configuration options.
2145  * @param {Object|Array} recordType Either an Array of field definition objects
2146  * 
2147  * @cfg {Array} fields Array of field definition objects
2148  * @cfg {String} id Name of the property within a row object that contains a record identifier value.
2149  * as specified to {@link Roo.data.Record#create},
2150  * or an {@link Roo.data.Record} object
2151  *
2152  * 
2153  * created using {@link Roo.data.Record#create}.
2154  */
2155 Roo.data.ArrayReader = function(meta, recordType){
2156     
2157      
2158     Roo.data.ArrayReader.superclass.constructor.call(this, meta, recordType||meta.fields);
2159 };
2160
2161 Roo.extend(Roo.data.ArrayReader, Roo.data.JsonReader, {
2162     /**
2163      * Create a data block containing Roo.data.Records from an XML document.
2164      * @param {Object} o An Array of row objects which represents the dataset.
2165      * @return {Object} A data block which is used by an {@link Roo.data.Store} object as
2166      * a cache of Roo.data.Records.
2167      */
2168     readRecords : function(o){
2169         var sid = this.meta ? this.meta.id : null;
2170         var recordType = this.recordType, fields = recordType.prototype.fields;
2171         var records = [];
2172         var root = o;
2173             for(var i = 0; i < root.length; i++){
2174                     var n = root[i];
2175                 var values = {};
2176                 var id = ((sid || sid === 0) && n[sid] !== undefined && n[sid] !== "" ? n[sid] : null);
2177                 for(var j = 0, jlen = fields.length; j < jlen; j++){
2178                 var f = fields.items[j];
2179                 var k = f.mapping !== undefined && f.mapping !== null ? f.mapping : j;
2180                 var v = n[k] !== undefined ? n[k] : f.defaultValue;
2181                 v = f.convert(v);
2182                 values[f.name] = v;
2183             }
2184                 var record = new recordType(values, id);
2185                 record.json = n;
2186                 records[records.length] = record;
2187             }
2188             return {
2189                 records : records,
2190                 totalRecords : records.length
2191             };
2192     }
2193 });/*
2194  * Based on:
2195  * Ext JS Library 1.1.1
2196  * Copyright(c) 2006-2007, Ext JS, LLC.
2197  *
2198  * Originally Released Under LGPL - original licence link has changed is not relivant.
2199  *
2200  * Fork - LGPL
2201  * <script type="text/javascript">
2202  */
2203
2204
2205 /**
2206  * @class Roo.data.Tree
2207  * @extends Roo.util.Observable
2208  * Represents a tree data structure and bubbles all the events for its nodes. The nodes
2209  * in the tree have most standard DOM functionality.
2210  * @constructor
2211  * @param {Node} root (optional) The root node
2212  */
2213 Roo.data.Tree = function(root){
2214    this.nodeHash = {};
2215    /**
2216     * The root node for this tree
2217     * @type Node
2218     */
2219    this.root = null;
2220    if(root){
2221        this.setRootNode(root);
2222    }
2223    this.addEvents({
2224        /**
2225         * @event append
2226         * Fires when a new child node is appended to a node in this tree.
2227         * @param {Tree} tree The owner tree
2228         * @param {Node} parent The parent node
2229         * @param {Node} node The newly appended node
2230         * @param {Number} index The index of the newly appended node
2231         */
2232        "append" : true,
2233        /**
2234         * @event remove
2235         * Fires when a child node is removed from a node in this tree.
2236         * @param {Tree} tree The owner tree
2237         * @param {Node} parent The parent node
2238         * @param {Node} node The child node removed
2239         */
2240        "remove" : true,
2241        /**
2242         * @event move
2243         * Fires when a node is moved to a new location in the tree
2244         * @param {Tree} tree The owner tree
2245         * @param {Node} node The node moved
2246         * @param {Node} oldParent The old parent of this node
2247         * @param {Node} newParent The new parent of this node
2248         * @param {Number} index The index it was moved to
2249         */
2250        "move" : true,
2251        /**
2252         * @event insert
2253         * Fires when a new child node is inserted in a node in this tree.
2254         * @param {Tree} tree The owner tree
2255         * @param {Node} parent The parent node
2256         * @param {Node} node The child node inserted
2257         * @param {Node} refNode The child node the node was inserted before
2258         */
2259        "insert" : true,
2260        /**
2261         * @event beforeappend
2262         * Fires before a new child is appended to a node in this tree, return false to cancel the append.
2263         * @param {Tree} tree The owner tree
2264         * @param {Node} parent The parent node
2265         * @param {Node} node The child node to be appended
2266         */
2267        "beforeappend" : true,
2268        /**
2269         * @event beforeremove
2270         * Fires before a child is removed from a node in this tree, return false to cancel the remove.
2271         * @param {Tree} tree The owner tree
2272         * @param {Node} parent The parent node
2273         * @param {Node} node The child node to be removed
2274         */
2275        "beforeremove" : true,
2276        /**
2277         * @event beforemove
2278         * Fires before a node is moved to a new location in the tree. Return false to cancel the move.
2279         * @param {Tree} tree The owner tree
2280         * @param {Node} node The node being moved
2281         * @param {Node} oldParent The parent of the node
2282         * @param {Node} newParent The new parent the node is moving to
2283         * @param {Number} index The index it is being moved to
2284         */
2285        "beforemove" : true,
2286        /**
2287         * @event beforeinsert
2288         * Fires before a new child is inserted in a node in this tree, return false to cancel the insert.
2289         * @param {Tree} tree The owner tree
2290         * @param {Node} parent The parent node
2291         * @param {Node} node The child node to be inserted
2292         * @param {Node} refNode The child node the node is being inserted before
2293         */
2294        "beforeinsert" : true
2295    });
2296
2297     Roo.data.Tree.superclass.constructor.call(this);
2298 };
2299
2300 Roo.extend(Roo.data.Tree, Roo.util.Observable, {
2301     pathSeparator: "/",
2302
2303     proxyNodeEvent : function(){
2304         return this.fireEvent.apply(this, arguments);
2305     },
2306
2307     /**
2308      * Returns the root node for this tree.
2309      * @return {Node}
2310      */
2311     getRootNode : function(){
2312         return this.root;
2313     },
2314
2315     /**
2316      * Sets the root node for this tree.
2317      * @param {Node} node
2318      * @return {Node}
2319      */
2320     setRootNode : function(node){
2321         this.root = node;
2322         node.ownerTree = this;
2323         node.isRoot = true;
2324         this.registerNode(node);
2325         return node;
2326     },
2327
2328     /**
2329      * Gets a node in this tree by its id.
2330      * @param {String} id
2331      * @return {Node}
2332      */
2333     getNodeById : function(id){
2334         return this.nodeHash[id];
2335     },
2336
2337     registerNode : function(node){
2338         this.nodeHash[node.id] = node;
2339     },
2340
2341     unregisterNode : function(node){
2342         delete this.nodeHash[node.id];
2343     },
2344
2345     toString : function(){
2346         return "[Tree"+(this.id?" "+this.id:"")+"]";
2347     }
2348 });
2349
2350 /**
2351  * @class Roo.data.Node
2352  * @extends Roo.util.Observable
2353  * @cfg {Boolean} leaf true if this node is a leaf and does not have children
2354  * @cfg {String} id The id for this node. If one is not specified, one is generated.
2355  * @constructor
2356  * @param {Object} attributes The attributes/config for the node
2357  */
2358 Roo.data.Node = function(attributes){
2359     /**
2360      * The attributes supplied for the node. You can use this property to access any custom attributes you supplied.
2361      * @type {Object}
2362      */
2363     this.attributes = attributes || {};
2364     this.leaf = this.attributes.leaf;
2365     /**
2366      * The node id. @type String
2367      */
2368     this.id = this.attributes.id;
2369     if(!this.id){
2370         this.id = Roo.id(null, "ynode-");
2371         this.attributes.id = this.id;
2372     }
2373      
2374     
2375     /**
2376      * All child nodes of this node. @type Array
2377      */
2378     this.childNodes = [];
2379     if(!this.childNodes.indexOf){ // indexOf is a must
2380         this.childNodes.indexOf = function(o){
2381             for(var i = 0, len = this.length; i < len; i++){
2382                 if(this[i] == o) {
2383                     return i;
2384                 }
2385             }
2386             return -1;
2387         };
2388     }
2389     /**
2390      * The parent node for this node. @type Node
2391      */
2392     this.parentNode = null;
2393     /**
2394      * The first direct child node of this node, or null if this node has no child nodes. @type Node
2395      */
2396     this.firstChild = null;
2397     /**
2398      * The last direct child node of this node, or null if this node has no child nodes. @type Node
2399      */
2400     this.lastChild = null;
2401     /**
2402      * The node immediately preceding this node in the tree, or null if there is no sibling node. @type Node
2403      */
2404     this.previousSibling = null;
2405     /**
2406      * The node immediately following this node in the tree, or null if there is no sibling node. @type Node
2407      */
2408     this.nextSibling = null;
2409
2410     this.addEvents({
2411        /**
2412         * @event append
2413         * Fires when a new child node is appended
2414         * @param {Tree} tree The owner tree
2415         * @param {Node} this This node
2416         * @param {Node} node The newly appended node
2417         * @param {Number} index The index of the newly appended node
2418         */
2419        "append" : true,
2420        /**
2421         * @event remove
2422         * Fires when a child node is removed
2423         * @param {Tree} tree The owner tree
2424         * @param {Node} this This node
2425         * @param {Node} node The removed node
2426         */
2427        "remove" : true,
2428        /**
2429         * @event move
2430         * Fires when this node is moved to a new location in the tree
2431         * @param {Tree} tree The owner tree
2432         * @param {Node} this This node
2433         * @param {Node} oldParent The old parent of this node
2434         * @param {Node} newParent The new parent of this node
2435         * @param {Number} index The index it was moved to
2436         */
2437        "move" : true,
2438        /**
2439         * @event insert
2440         * Fires when a new child node is inserted.
2441         * @param {Tree} tree The owner tree
2442         * @param {Node} this This node
2443         * @param {Node} node The child node inserted
2444         * @param {Node} refNode The child node the node was inserted before
2445         */
2446        "insert" : true,
2447        /**
2448         * @event beforeappend
2449         * Fires before a new child is appended, return false to cancel the append.
2450         * @param {Tree} tree The owner tree
2451         * @param {Node} this This node
2452         * @param {Node} node The child node to be appended
2453         */
2454        "beforeappend" : true,
2455        /**
2456         * @event beforeremove
2457         * Fires before a child is removed, return false to cancel the remove.
2458         * @param {Tree} tree The owner tree
2459         * @param {Node} this This node
2460         * @param {Node} node The child node to be removed
2461         */
2462        "beforeremove" : true,
2463        /**
2464         * @event beforemove
2465         * Fires before this node is moved to a new location in the tree. Return false to cancel the move.
2466         * @param {Tree} tree The owner tree
2467         * @param {Node} this This node
2468         * @param {Node} oldParent The parent of this node
2469         * @param {Node} newParent The new parent this node is moving to
2470         * @param {Number} index The index it is being moved to
2471         */
2472        "beforemove" : true,
2473        /**
2474         * @event beforeinsert
2475         * Fires before a new child is inserted, return false to cancel the insert.
2476         * @param {Tree} tree The owner tree
2477         * @param {Node} this This node
2478         * @param {Node} node The child node to be inserted
2479         * @param {Node} refNode The child node the node is being inserted before
2480         */
2481        "beforeinsert" : true
2482    });
2483     this.listeners = this.attributes.listeners;
2484     Roo.data.Node.superclass.constructor.call(this);
2485 };
2486
2487 Roo.extend(Roo.data.Node, Roo.util.Observable, {
2488     fireEvent : function(evtName){
2489         // first do standard event for this node
2490         if(Roo.data.Node.superclass.fireEvent.apply(this, arguments) === false){
2491             return false;
2492         }
2493         // then bubble it up to the tree if the event wasn't cancelled
2494         var ot = this.getOwnerTree();
2495         if(ot){
2496             if(ot.proxyNodeEvent.apply(ot, arguments) === false){
2497                 return false;
2498             }
2499         }
2500         return true;
2501     },
2502
2503     /**
2504      * Returns true if this node is a leaf
2505      * @return {Boolean}
2506      */
2507     isLeaf : function(){
2508         return this.leaf === true;
2509     },
2510
2511     // private
2512     setFirstChild : function(node){
2513         this.firstChild = node;
2514     },
2515
2516     //private
2517     setLastChild : function(node){
2518         this.lastChild = node;
2519     },
2520
2521
2522     /**
2523      * Returns true if this node is the last child of its parent
2524      * @return {Boolean}
2525      */
2526     isLast : function(){
2527        return (!this.parentNode ? true : this.parentNode.lastChild == this);
2528     },
2529
2530     /**
2531      * Returns true if this node is the first child of its parent
2532      * @return {Boolean}
2533      */
2534     isFirst : function(){
2535        return (!this.parentNode ? true : this.parentNode.firstChild == this);
2536     },
2537
2538     hasChildNodes : function(){
2539         return !this.isLeaf() && this.childNodes.length > 0;
2540     },
2541
2542     /**
2543      * Insert node(s) as the last child node of this node.
2544      * @param {Node/Array} node The node or Array of nodes to append
2545      * @return {Node} The appended node if single append, or null if an array was passed
2546      */
2547     appendChild : function(node){
2548         var multi = false;
2549         if(node instanceof Array){
2550             multi = node;
2551         }else if(arguments.length > 1){
2552             multi = arguments;
2553         }
2554         
2555         // if passed an array or multiple args do them one by one
2556         if(multi){
2557             for(var i = 0, len = multi.length; i < len; i++) {
2558                 this.appendChild(multi[i]);
2559             }
2560         }else{
2561             if(this.fireEvent("beforeappend", this.ownerTree, this, node) === false){
2562                 return false;
2563             }
2564             var index = this.childNodes.length;
2565             var oldParent = node.parentNode;
2566             // it's a move, make sure we move it cleanly
2567             if(oldParent){
2568                 if(node.fireEvent("beforemove", node.getOwnerTree(), node, oldParent, this, index) === false){
2569                     return false;
2570                 }
2571                 oldParent.removeChild(node);
2572             }
2573             
2574             index = this.childNodes.length;
2575             if(index == 0){
2576                 this.setFirstChild(node);
2577             }
2578             this.childNodes.push(node);
2579             node.parentNode = this;
2580             var ps = this.childNodes[index-1];
2581             if(ps){
2582                 node.previousSibling = ps;
2583                 ps.nextSibling = node;
2584             }else{
2585                 node.previousSibling = null;
2586             }
2587             node.nextSibling = null;
2588             this.setLastChild(node);
2589             node.setOwnerTree(this.getOwnerTree());
2590             this.fireEvent("append", this.ownerTree, this, node, index);
2591             if(this.ownerTree) {
2592                 this.ownerTree.fireEvent("appendnode", this, node, index);
2593             }
2594             if(oldParent){
2595                 node.fireEvent("move", this.ownerTree, node, oldParent, this, index);
2596             }
2597             return node;
2598         }
2599     },
2600
2601     /**
2602      * Removes a child node from this node.
2603      * @param {Node} node The node to remove
2604      * @return {Node} The removed node
2605      */
2606     removeChild : function(node){
2607         var index = this.childNodes.indexOf(node);
2608         if(index == -1){
2609             return false;
2610         }
2611         if(this.fireEvent("beforeremove", this.ownerTree, this, node) === false){
2612             return false;
2613         }
2614
2615         // remove it from childNodes collection
2616         this.childNodes.splice(index, 1);
2617
2618         // update siblings
2619         if(node.previousSibling){
2620             node.previousSibling.nextSibling = node.nextSibling;
2621         }
2622         if(node.nextSibling){
2623             node.nextSibling.previousSibling = node.previousSibling;
2624         }
2625
2626         // update child refs
2627         if(this.firstChild == node){
2628             this.setFirstChild(node.nextSibling);
2629         }
2630         if(this.lastChild == node){
2631             this.setLastChild(node.previousSibling);
2632         }
2633
2634         node.setOwnerTree(null);
2635         // clear any references from the node
2636         node.parentNode = null;
2637         node.previousSibling = null;
2638         node.nextSibling = null;
2639         this.fireEvent("remove", this.ownerTree, this, node);
2640         return node;
2641     },
2642
2643     /**
2644      * Inserts the first node before the second node in this nodes childNodes collection.
2645      * @param {Node} node The node to insert
2646      * @param {Node} refNode The node to insert before (if null the node is appended)
2647      * @return {Node} The inserted node
2648      */
2649     insertBefore : function(node, refNode){
2650         if(!refNode){ // like standard Dom, refNode can be null for append
2651             return this.appendChild(node);
2652         }
2653         // nothing to do
2654         if(node == refNode){
2655             return false;
2656         }
2657
2658         if(this.fireEvent("beforeinsert", this.ownerTree, this, node, refNode) === false){
2659             return false;
2660         }
2661         var index = this.childNodes.indexOf(refNode);
2662         var oldParent = node.parentNode;
2663         var refIndex = index;
2664
2665         // when moving internally, indexes will change after remove
2666         if(oldParent == this && this.childNodes.indexOf(node) < index){
2667             refIndex--;
2668         }
2669
2670         // it's a move, make sure we move it cleanly
2671         if(oldParent){
2672             if(node.fireEvent("beforemove", node.getOwnerTree(), node, oldParent, this, index, refNode) === false){
2673                 return false;
2674             }
2675             oldParent.removeChild(node);
2676         }
2677         if(refIndex == 0){
2678             this.setFirstChild(node);
2679         }
2680         this.childNodes.splice(refIndex, 0, node);
2681         node.parentNode = this;
2682         var ps = this.childNodes[refIndex-1];
2683         if(ps){
2684             node.previousSibling = ps;
2685             ps.nextSibling = node;
2686         }else{
2687             node.previousSibling = null;
2688         }
2689         node.nextSibling = refNode;
2690         refNode.previousSibling = node;
2691         node.setOwnerTree(this.getOwnerTree());
2692         this.fireEvent("insert", this.ownerTree, this, node, refNode);
2693         if(oldParent){
2694             node.fireEvent("move", this.ownerTree, node, oldParent, this, refIndex, refNode);
2695         }
2696         return node;
2697     },
2698
2699     /**
2700      * Returns the child node at the specified index.
2701      * @param {Number} index
2702      * @return {Node}
2703      */
2704     item : function(index){
2705         return this.childNodes[index];
2706     },
2707
2708     /**
2709      * Replaces one child node in this node with another.
2710      * @param {Node} newChild The replacement node
2711      * @param {Node} oldChild The node to replace
2712      * @return {Node} The replaced node
2713      */
2714     replaceChild : function(newChild, oldChild){
2715         this.insertBefore(newChild, oldChild);
2716         this.removeChild(oldChild);
2717         return oldChild;
2718     },
2719
2720     /**
2721      * Returns the index of a child node
2722      * @param {Node} node
2723      * @return {Number} The index of the node or -1 if it was not found
2724      */
2725     indexOf : function(child){
2726         return this.childNodes.indexOf(child);
2727     },
2728
2729     /**
2730      * Returns the tree this node is in.
2731      * @return {Tree}
2732      */
2733     getOwnerTree : function(){
2734         // if it doesn't have one, look for one
2735         if(!this.ownerTree){
2736             var p = this;
2737             while(p){
2738                 if(p.ownerTree){
2739                     this.ownerTree = p.ownerTree;
2740                     break;
2741                 }
2742                 p = p.parentNode;
2743             }
2744         }
2745         return this.ownerTree;
2746     },
2747
2748     /**
2749      * Returns depth of this node (the root node has a depth of 0)
2750      * @return {Number}
2751      */
2752     getDepth : function(){
2753         var depth = 0;
2754         var p = this;
2755         while(p.parentNode){
2756             ++depth;
2757             p = p.parentNode;
2758         }
2759         return depth;
2760     },
2761
2762     // private
2763     setOwnerTree : function(tree){
2764         // if it's move, we need to update everyone
2765         if(tree != this.ownerTree){
2766             if(this.ownerTree){
2767                 this.ownerTree.unregisterNode(this);
2768             }
2769             this.ownerTree = tree;
2770             var cs = this.childNodes;
2771             for(var i = 0, len = cs.length; i < len; i++) {
2772                 cs[i].setOwnerTree(tree);
2773             }
2774             if(tree){
2775                 tree.registerNode(this);
2776             }
2777         }
2778     },
2779
2780     /**
2781      * Returns the path for this node. The path can be used to expand or select this node programmatically.
2782      * @param {String} attr (optional) The attr to use for the path (defaults to the node's id)
2783      * @return {String} The path
2784      */
2785     getPath : function(attr){
2786         attr = attr || "id";
2787         var p = this.parentNode;
2788         var b = [this.attributes[attr]];
2789         while(p){
2790             b.unshift(p.attributes[attr]);
2791             p = p.parentNode;
2792         }
2793         var sep = this.getOwnerTree().pathSeparator;
2794         return sep + b.join(sep);
2795     },
2796
2797     /**
2798      * Bubbles up the tree from this node, calling the specified function with each node. The scope (<i>this</i>) of
2799      * function call will be the scope provided or the current node. The arguments to the function
2800      * will be the args provided or the current node. If the function returns false at any point,
2801      * the bubble is stopped.
2802      * @param {Function} fn The function to call
2803      * @param {Object} scope (optional) The scope of the function (defaults to current node)
2804      * @param {Array} args (optional) The args to call the function with (default to passing the current node)
2805      */
2806     bubble : function(fn, scope, args){
2807         var p = this;
2808         while(p){
2809             if(fn.call(scope || p, args || p) === false){
2810                 break;
2811             }
2812             p = p.parentNode;
2813         }
2814     },
2815
2816     /**
2817      * Cascades down the tree from this node, calling the specified function with each node. The scope (<i>this</i>) of
2818      * function call will be the scope provided or the current node. The arguments to the function
2819      * will be the args provided or the current node. If the function returns false at any point,
2820      * the cascade is stopped on that branch.
2821      * @param {Function} fn The function to call
2822      * @param {Object} scope (optional) The scope of the function (defaults to current node)
2823      * @param {Array} args (optional) The args to call the function with (default to passing the current node)
2824      */
2825     cascade : function(fn, scope, args){
2826         if(fn.call(scope || this, args || this) !== false){
2827             var cs = this.childNodes;
2828             for(var i = 0, len = cs.length; i < len; i++) {
2829                 cs[i].cascade(fn, scope, args);
2830             }
2831         }
2832     },
2833
2834     /**
2835      * Interates the child nodes of this node, calling the specified function with each node. The scope (<i>this</i>) of
2836      * function call will be the scope provided or the current node. The arguments to the function
2837      * will be the args provided or the current node. If the function returns false at any point,
2838      * the iteration stops.
2839      * @param {Function} fn The function to call
2840      * @param {Object} scope (optional) The scope of the function (defaults to current node)
2841      * @param {Array} args (optional) The args to call the function with (default to passing the current node)
2842      */
2843     eachChild : function(fn, scope, args){
2844         var cs = this.childNodes;
2845         for(var i = 0, len = cs.length; i < len; i++) {
2846                 if(fn.call(scope || this, args || cs[i]) === false){
2847                     break;
2848                 }
2849         }
2850     },
2851
2852     /**
2853      * Finds the first child that has the attribute with the specified value.
2854      * @param {String} attribute The attribute name
2855      * @param {Mixed} value The value to search for
2856      * @return {Node} The found child or null if none was found
2857      */
2858     findChild : function(attribute, value){
2859         var cs = this.childNodes;
2860         for(var i = 0, len = cs.length; i < len; i++) {
2861                 if(cs[i].attributes[attribute] == value){
2862                     return cs[i];
2863                 }
2864         }
2865         return null;
2866     },
2867
2868     /**
2869      * Finds the first child by a custom function. The child matches if the function passed
2870      * returns true.
2871      * @param {Function} fn
2872      * @param {Object} scope (optional)
2873      * @return {Node} The found child or null if none was found
2874      */
2875     findChildBy : function(fn, scope){
2876         var cs = this.childNodes;
2877         for(var i = 0, len = cs.length; i < len; i++) {
2878                 if(fn.call(scope||cs[i], cs[i]) === true){
2879                     return cs[i];
2880                 }
2881         }
2882         return null;
2883     },
2884
2885     /**
2886      * Sorts this nodes children using the supplied sort function
2887      * @param {Function} fn
2888      * @param {Object} scope (optional)
2889      */
2890     sort : function(fn, scope){
2891         var cs = this.childNodes;
2892         var len = cs.length;
2893         if(len > 0){
2894             var sortFn = scope ? function(){fn.apply(scope, arguments);} : fn;
2895             cs.sort(sortFn);
2896             for(var i = 0; i < len; i++){
2897                 var n = cs[i];
2898                 n.previousSibling = cs[i-1];
2899                 n.nextSibling = cs[i+1];
2900                 if(i == 0){
2901                     this.setFirstChild(n);
2902                 }
2903                 if(i == len-1){
2904                     this.setLastChild(n);
2905                 }
2906             }
2907         }
2908     },
2909
2910     /**
2911      * Returns true if this node is an ancestor (at any point) of the passed node.
2912      * @param {Node} node
2913      * @return {Boolean}
2914      */
2915     contains : function(node){
2916         return node.isAncestor(this);
2917     },
2918
2919     /**
2920      * Returns true if the passed node is an ancestor (at any point) of this node.
2921      * @param {Node} node
2922      * @return {Boolean}
2923      */
2924     isAncestor : function(node){
2925         var p = this.parentNode;
2926         while(p){
2927             if(p == node){
2928                 return true;
2929             }
2930             p = p.parentNode;
2931         }
2932         return false;
2933     },
2934
2935     toString : function(){
2936         return "[Node"+(this.id?" "+this.id:"")+"]";
2937     }
2938 });/*
2939  * Based on:
2940  * Ext JS Library 1.1.1
2941  * Copyright(c) 2006-2007, Ext JS, LLC.
2942  *
2943  * Originally Released Under LGPL - original licence link has changed is not relivant.
2944  *
2945  * Fork - LGPL
2946  * <script type="text/javascript">
2947  */
2948  (function(){ 
2949 /**
2950  * @class Roo.Layer
2951  * @extends Roo.Element
2952  * An extended {@link Roo.Element} object that supports a shadow and shim, constrain to viewport and
2953  * automatic maintaining of shadow/shim positions.
2954  * @cfg {Boolean} shim False to disable the iframe shim in browsers which need one (defaults to true)
2955  * @cfg {String/Boolean} shadow True to create a shadow element with default class "x-layer-shadow", or
2956  * you can pass a string with a CSS class name. False turns off the shadow.
2957  * @cfg {Object} dh DomHelper object config to create element with (defaults to {tag: "div", cls: "x-layer"}).
2958  * @cfg {Boolean} constrain False to disable constrain to viewport (defaults to true)
2959  * @cfg {String} cls CSS class to add to the element
2960  * @cfg {Number} zindex Starting z-index (defaults to 11000)
2961  * @cfg {Number} shadowOffset Number of pixels to offset the shadow (defaults to 3)
2962  * @constructor
2963  * @param {Object} config An object with config options.
2964  * @param {String/HTMLElement} existingEl (optional) Uses an existing DOM element. If the element is not found it creates it.
2965  */
2966
2967 Roo.Layer = function(config, existingEl){
2968     config = config || {};
2969     var dh = Roo.DomHelper;
2970     var cp = config.parentEl, pel = cp ? Roo.getDom(cp) : document.body;
2971     if(existingEl){
2972         this.dom = Roo.getDom(existingEl);
2973     }
2974     if(!this.dom){
2975         var o = config.dh || {tag: "div", cls: "x-layer"};
2976         this.dom = dh.append(pel, o);
2977     }
2978     if(config.cls){
2979         this.addClass(config.cls);
2980     }
2981     this.constrain = config.constrain !== false;
2982     this.visibilityMode = Roo.Element.VISIBILITY;
2983     if(config.id){
2984         this.id = this.dom.id = config.id;
2985     }else{
2986         this.id = Roo.id(this.dom);
2987     }
2988     this.zindex = config.zindex || this.getZIndex();
2989     this.position("absolute", this.zindex);
2990     if(config.shadow){
2991         this.shadowOffset = config.shadowOffset || 4;
2992         this.shadow = new Roo.Shadow({
2993             offset : this.shadowOffset,
2994             mode : config.shadow
2995         });
2996     }else{
2997         this.shadowOffset = 0;
2998     }
2999     this.useShim = config.shim !== false && Roo.useShims;
3000     this.useDisplay = config.useDisplay;
3001     this.hide();
3002 };
3003
3004 var supr = Roo.Element.prototype;
3005
3006 // shims are shared among layer to keep from having 100 iframes
3007 var shims = [];
3008
3009 Roo.extend(Roo.Layer, Roo.Element, {
3010
3011     getZIndex : function(){
3012         return this.zindex || parseInt(this.getStyle("z-index"), 10) || 11000;
3013     },
3014
3015     getShim : function(){
3016         if(!this.useShim){
3017             return null;
3018         }
3019         if(this.shim){
3020             return this.shim;
3021         }
3022         var shim = shims.shift();
3023         if(!shim){
3024             shim = this.createShim();
3025             shim.enableDisplayMode('block');
3026             shim.dom.style.display = 'none';
3027             shim.dom.style.visibility = 'visible';
3028         }
3029         var pn = this.dom.parentNode;
3030         if(shim.dom.parentNode != pn){
3031             pn.insertBefore(shim.dom, this.dom);
3032         }
3033         shim.setStyle('z-index', this.getZIndex()-2);
3034         this.shim = shim;
3035         return shim;
3036     },
3037
3038     hideShim : function(){
3039         if(this.shim){
3040             this.shim.setDisplayed(false);
3041             shims.push(this.shim);
3042             delete this.shim;
3043         }
3044     },
3045
3046     disableShadow : function(){
3047         if(this.shadow){
3048             this.shadowDisabled = true;
3049             this.shadow.hide();
3050             this.lastShadowOffset = this.shadowOffset;
3051             this.shadowOffset = 0;
3052         }
3053     },
3054
3055     enableShadow : function(show){
3056         if(this.shadow){
3057             this.shadowDisabled = false;
3058             this.shadowOffset = this.lastShadowOffset;
3059             delete this.lastShadowOffset;
3060             if(show){
3061                 this.sync(true);
3062             }
3063         }
3064     },
3065
3066     // private
3067     // this code can execute repeatedly in milliseconds (i.e. during a drag) so
3068     // code size was sacrificed for effeciency (e.g. no getBox/setBox, no XY calls)
3069     sync : function(doShow){
3070         var sw = this.shadow;
3071         if(!this.updating && this.isVisible() && (sw || this.useShim)){
3072             var sh = this.getShim();
3073
3074             var w = this.getWidth(),
3075                 h = this.getHeight();
3076
3077             var l = this.getLeft(true),
3078                 t = this.getTop(true);
3079
3080             if(sw && !this.shadowDisabled){
3081                 if(doShow && !sw.isVisible()){
3082                     sw.show(this);
3083                 }else{
3084                     sw.realign(l, t, w, h);
3085                 }
3086                 if(sh){
3087                     if(doShow){
3088                        sh.show();
3089                     }
3090                     // fit the shim behind the shadow, so it is shimmed too
3091                     var a = sw.adjusts, s = sh.dom.style;
3092                     s.left = (Math.min(l, l+a.l))+"px";
3093                     s.top = (Math.min(t, t+a.t))+"px";
3094                     s.width = (w+a.w)+"px";
3095                     s.height = (h+a.h)+"px";
3096                 }
3097             }else if(sh){
3098                 if(doShow){
3099                    sh.show();
3100                 }
3101                 sh.setSize(w, h);
3102                 sh.setLeftTop(l, t);
3103             }
3104             
3105         }
3106     },
3107
3108     // private
3109     destroy : function(){
3110         this.hideShim();
3111         if(this.shadow){
3112             this.shadow.hide();
3113         }
3114         this.removeAllListeners();
3115         var pn = this.dom.parentNode;
3116         if(pn){
3117             pn.removeChild(this.dom);
3118         }
3119         Roo.Element.uncache(this.id);
3120     },
3121
3122     remove : function(){
3123         this.destroy();
3124     },
3125
3126     // private
3127     beginUpdate : function(){
3128         this.updating = true;
3129     },
3130
3131     // private
3132     endUpdate : function(){
3133         this.updating = false;
3134         this.sync(true);
3135     },
3136
3137     // private
3138     hideUnders : function(negOffset){
3139         if(this.shadow){
3140             this.shadow.hide();
3141         }
3142         this.hideShim();
3143     },
3144
3145     // private
3146     constrainXY : function(){
3147         if(this.constrain){
3148             var vw = Roo.lib.Dom.getViewWidth(),
3149                 vh = Roo.lib.Dom.getViewHeight();
3150             var s = Roo.get(document).getScroll();
3151
3152             var xy = this.getXY();
3153             var x = xy[0], y = xy[1];   
3154             var w = this.dom.offsetWidth+this.shadowOffset, h = this.dom.offsetHeight+this.shadowOffset;
3155             // only move it if it needs it
3156             var moved = false;
3157             // first validate right/bottom
3158             if((x + w) > vw+s.left){
3159                 x = vw - w - this.shadowOffset;
3160                 moved = true;
3161             }
3162             if((y + h) > vh+s.top){
3163                 y = vh - h - this.shadowOffset;
3164                 moved = true;
3165             }
3166             // then make sure top/left isn't negative
3167             if(x < s.left){
3168                 x = s.left;
3169                 moved = true;
3170             }
3171             if(y < s.top){
3172                 y = s.top;
3173                 moved = true;
3174             }
3175             if(moved){
3176                 if(this.avoidY){
3177                     var ay = this.avoidY;
3178                     if(y <= ay && (y+h) >= ay){
3179                         y = ay-h-5;   
3180                     }
3181                 }
3182                 xy = [x, y];
3183                 this.storeXY(xy);
3184                 supr.setXY.call(this, xy);
3185                 this.sync();
3186             }
3187         }
3188     },
3189
3190     isVisible : function(){
3191         return this.visible;    
3192     },
3193
3194     // private
3195     showAction : function(){
3196         this.visible = true; // track visibility to prevent getStyle calls
3197         if(this.useDisplay === true){
3198             this.setDisplayed("");
3199         }else if(this.lastXY){
3200             supr.setXY.call(this, this.lastXY);
3201         }else if(this.lastLT){
3202             supr.setLeftTop.call(this, this.lastLT[0], this.lastLT[1]);
3203         }
3204     },
3205
3206     // private
3207     hideAction : function(){
3208         this.visible = false;
3209         if(this.useDisplay === true){
3210             this.setDisplayed(false);
3211         }else{
3212             this.setLeftTop(-10000,-10000);
3213         }
3214     },
3215
3216     // overridden Element method
3217     setVisible : function(v, a, d, c, e){
3218         if(v){
3219             this.showAction();
3220         }
3221         if(a && v){
3222             var cb = function(){
3223                 this.sync(true);
3224                 if(c){
3225                     c();
3226                 }
3227             }.createDelegate(this);
3228             supr.setVisible.call(this, true, true, d, cb, e);
3229         }else{
3230             if(!v){
3231                 this.hideUnders(true);
3232             }
3233             var cb = c;
3234             if(a){
3235                 cb = function(){
3236                     this.hideAction();
3237                     if(c){
3238                         c();
3239                     }
3240                 }.createDelegate(this);
3241             }
3242             supr.setVisible.call(this, v, a, d, cb, e);
3243             if(v){
3244                 this.sync(true);
3245             }else if(!a){
3246                 this.hideAction();
3247             }
3248         }
3249     },
3250
3251     storeXY : function(xy){
3252         delete this.lastLT;
3253         this.lastXY = xy;
3254     },
3255
3256     storeLeftTop : function(left, top){
3257         delete this.lastXY;
3258         this.lastLT = [left, top];
3259     },
3260
3261     // private
3262     beforeFx : function(){
3263         this.beforeAction();
3264         return Roo.Layer.superclass.beforeFx.apply(this, arguments);
3265     },
3266
3267     // private
3268     afterFx : function(){
3269         Roo.Layer.superclass.afterFx.apply(this, arguments);
3270         this.sync(this.isVisible());
3271     },
3272
3273     // private
3274     beforeAction : function(){
3275         if(!this.updating && this.shadow){
3276             this.shadow.hide();
3277         }
3278     },
3279
3280     // overridden Element method
3281     setLeft : function(left){
3282         this.storeLeftTop(left, this.getTop(true));
3283         supr.setLeft.apply(this, arguments);
3284         this.sync();
3285     },
3286
3287     setTop : function(top){
3288         this.storeLeftTop(this.getLeft(true), top);
3289         supr.setTop.apply(this, arguments);
3290         this.sync();
3291     },
3292
3293     setLeftTop : function(left, top){
3294         this.storeLeftTop(left, top);
3295         supr.setLeftTop.apply(this, arguments);
3296         this.sync();
3297     },
3298
3299     setXY : function(xy, a, d, c, e){
3300         this.fixDisplay();
3301         this.beforeAction();
3302         this.storeXY(xy);
3303         var cb = this.createCB(c);
3304         supr.setXY.call(this, xy, a, d, cb, e);
3305         if(!a){
3306             cb();
3307         }
3308     },
3309
3310     // private
3311     createCB : function(c){
3312         var el = this;
3313         return function(){
3314             el.constrainXY();
3315             el.sync(true);
3316             if(c){
3317                 c();
3318             }
3319         };
3320     },
3321
3322     // overridden Element method
3323     setX : function(x, a, d, c, e){
3324         this.setXY([x, this.getY()], a, d, c, e);
3325     },
3326
3327     // overridden Element method
3328     setY : function(y, a, d, c, e){
3329         this.setXY([this.getX(), y], a, d, c, e);
3330     },
3331
3332     // overridden Element method
3333     setSize : function(w, h, a, d, c, e){
3334         this.beforeAction();
3335         var cb = this.createCB(c);
3336         supr.setSize.call(this, w, h, a, d, cb, e);
3337         if(!a){
3338             cb();
3339         }
3340     },
3341
3342     // overridden Element method
3343     setWidth : function(w, a, d, c, e){
3344         this.beforeAction();
3345         var cb = this.createCB(c);
3346         supr.setWidth.call(this, w, a, d, cb, e);
3347         if(!a){
3348             cb();
3349         }
3350     },
3351
3352     // overridden Element method
3353     setHeight : function(h, a, d, c, e){
3354         this.beforeAction();
3355         var cb = this.createCB(c);
3356         supr.setHeight.call(this, h, a, d, cb, e);
3357         if(!a){
3358             cb();
3359         }
3360     },
3361
3362     // overridden Element method
3363     setBounds : function(x, y, w, h, a, d, c, e){
3364         this.beforeAction();
3365         var cb = this.createCB(c);
3366         if(!a){
3367             this.storeXY([x, y]);
3368             supr.setXY.call(this, [x, y]);
3369             supr.setSize.call(this, w, h, a, d, cb, e);
3370             cb();
3371         }else{
3372             supr.setBounds.call(this, x, y, w, h, a, d, cb, e);
3373         }
3374         return this;
3375     },
3376     
3377     /**
3378      * Sets the z-index of this layer and adjusts any shadow and shim z-indexes. The layer z-index is automatically
3379      * incremented by two more than the value passed in so that it always shows above any shadow or shim (the shadow
3380      * element, if any, will be assigned z-index + 1, and the shim element, if any, will be assigned the unmodified z-index).
3381      * @param {Number} zindex The new z-index to set
3382      * @return {this} The Layer
3383      */
3384     setZIndex : function(zindex){
3385         this.zindex = zindex;
3386         this.setStyle("z-index", zindex + 2);
3387         if(this.shadow){
3388             this.shadow.setZIndex(zindex + 1);
3389         }
3390         if(this.shim){
3391             this.shim.setStyle("z-index", zindex);
3392         }
3393     }
3394 });
3395 })();/*
3396  * Based on:
3397  * Ext JS Library 1.1.1
3398  * Copyright(c) 2006-2007, Ext JS, LLC.
3399  *
3400  * Originally Released Under LGPL - original licence link has changed is not relivant.
3401  *
3402  * Fork - LGPL
3403  * <script type="text/javascript">
3404  */
3405
3406
3407 /**
3408  * @class Roo.Shadow
3409  * Simple class that can provide a shadow effect for any element.  Note that the element MUST be absolutely positioned,
3410  * and the shadow does not provide any shimming.  This should be used only in simple cases -- for more advanced
3411  * functionality that can also provide the same shadow effect, see the {@link Roo.Layer} class.
3412  * @constructor
3413  * Create a new Shadow
3414  * @param {Object} config The config object
3415  */
3416 Roo.Shadow = function(config){
3417     Roo.apply(this, config);
3418     if(typeof this.mode != "string"){
3419         this.mode = this.defaultMode;
3420     }
3421     var o = this.offset, a = {h: 0};
3422     var rad = Math.floor(this.offset/2);
3423     switch(this.mode.toLowerCase()){ // all this hideous nonsense calculates the various offsets for shadows
3424         case "drop":
3425             a.w = 0;
3426             a.l = a.t = o;
3427             a.t -= 1;
3428             if(Roo.isIE){
3429                 a.l -= this.offset + rad;
3430                 a.t -= this.offset + rad;
3431                 a.w -= rad;
3432                 a.h -= rad;
3433                 a.t += 1;
3434             }
3435         break;
3436         case "sides":
3437             a.w = (o*2);
3438             a.l = -o;
3439             a.t = o-1;
3440             if(Roo.isIE){
3441                 a.l -= (this.offset - rad);
3442                 a.t -= this.offset + rad;
3443                 a.l += 1;
3444                 a.w -= (this.offset - rad)*2;
3445                 a.w -= rad + 1;
3446                 a.h -= 1;
3447             }
3448         break;
3449         case "frame":
3450             a.w = a.h = (o*2);
3451             a.l = a.t = -o;
3452             a.t += 1;
3453             a.h -= 2;
3454             if(Roo.isIE){
3455                 a.l -= (this.offset - rad);
3456                 a.t -= (this.offset - rad);
3457                 a.l += 1;
3458                 a.w -= (this.offset + rad + 1);
3459                 a.h -= (this.offset + rad);
3460                 a.h += 1;
3461             }
3462         break;
3463     };
3464
3465     this.adjusts = a;
3466 };
3467
3468 Roo.Shadow.prototype = {
3469     /**
3470      * @cfg {String} mode
3471      * The shadow display mode.  Supports the following options:<br />
3472      * sides: Shadow displays on both sides and bottom only<br />
3473      * frame: Shadow displays equally on all four sides<br />
3474      * drop: Traditional bottom-right drop shadow (default)
3475      */
3476     /**
3477      * @cfg {String} offset
3478      * The number of pixels to offset the shadow from the element (defaults to 4)
3479      */
3480     offset: 4,
3481
3482     // private
3483     defaultMode: "drop",
3484
3485     /**
3486      * Displays the shadow under the target element
3487      * @param {String/HTMLElement/Element} targetEl The id or element under which the shadow should display
3488      */
3489     show : function(target){
3490         target = Roo.get(target);
3491         if(!this.el){
3492             this.el = Roo.Shadow.Pool.pull();
3493             if(this.el.dom.nextSibling != target.dom){
3494                 this.el.insertBefore(target);
3495             }
3496         }
3497         this.el.setStyle("z-index", this.zIndex || parseInt(target.getStyle("z-index"), 10)-1);
3498         if(Roo.isIE){
3499             this.el.dom.style.filter="progid:DXImageTransform.Microsoft.alpha(opacity=50) progid:DXImageTransform.Microsoft.Blur(pixelradius="+(this.offset)+")";
3500         }
3501         this.realign(
3502             target.getLeft(true),
3503             target.getTop(true),
3504             target.getWidth(),
3505             target.getHeight()
3506         );
3507         this.el.dom.style.display = "block";
3508     },
3509
3510     /**
3511      * Returns true if the shadow is visible, else false
3512      */
3513     isVisible : function(){
3514         return this.el ? true : false;  
3515     },
3516
3517     /**
3518      * Direct alignment when values are already available. Show must be called at least once before
3519      * calling this method to ensure it is initialized.
3520      * @param {Number} left The target element left position
3521      * @param {Number} top The target element top position
3522      * @param {Number} width The target element width
3523      * @param {Number} height The target element height
3524      */
3525     realign : function(l, t, w, h){
3526         if(!this.el){
3527             return;
3528         }
3529         var a = this.adjusts, d = this.el.dom, s = d.style;
3530         var iea = 0;
3531         s.left = (l+a.l)+"px";
3532         s.top = (t+a.t)+"px";
3533         var sw = (w+a.w), sh = (h+a.h), sws = sw +"px", shs = sh + "px";
3534  
3535         if(s.width != sws || s.height != shs){
3536             s.width = sws;
3537             s.height = shs;
3538             if(!Roo.isIE){
3539                 var cn = d.childNodes;
3540                 var sww = Math.max(0, (sw-12))+"px";
3541                 cn[0].childNodes[1].style.width = sww;
3542                 cn[1].childNodes[1].style.width = sww;
3543                 cn[2].childNodes[1].style.width = sww;
3544                 cn[1].style.height = Math.max(0, (sh-12))+"px";
3545             }
3546         }
3547     },
3548
3549     /**
3550      * Hides this shadow
3551      */
3552     hide : function(){
3553         if(this.el){
3554             this.el.dom.style.display = "none";
3555             Roo.Shadow.Pool.push(this.el);
3556             delete this.el;
3557         }
3558     },
3559
3560     /**
3561      * Adjust the z-index of this shadow
3562      * @param {Number} zindex The new z-index
3563      */
3564     setZIndex : function(z){
3565         this.zIndex = z;
3566         if(this.el){
3567             this.el.setStyle("z-index", z);
3568         }
3569     }
3570 };
3571
3572 // Private utility class that manages the internal Shadow cache
3573 Roo.Shadow.Pool = function(){
3574     var p = [];
3575     var markup = Roo.isIE ?
3576                  '<div class="x-ie-shadow"></div>' :
3577                  '<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>';
3578     return {
3579         pull : function(){
3580             var sh = p.shift();
3581             if(!sh){
3582                 sh = Roo.get(Roo.DomHelper.insertHtml("beforeBegin", document.body.firstChild, markup));
3583                 sh.autoBoxAdjust = false;
3584             }
3585             return sh;
3586         },
3587
3588         push : function(sh){
3589             p.push(sh);
3590         }
3591     };
3592 }();/*
3593  * Based on:
3594  * Ext JS Library 1.1.1
3595  * Copyright(c) 2006-2007, Ext JS, LLC.
3596  *
3597  * Originally Released Under LGPL - original licence link has changed is not relivant.
3598  *
3599  * Fork - LGPL
3600  * <script type="text/javascript">
3601  */
3602
3603
3604 /**
3605  * @class Roo.SplitBar
3606  * @extends Roo.util.Observable
3607  * Creates draggable splitter bar functionality from two elements (element to be dragged and element to be resized).
3608  * <br><br>
3609  * Usage:
3610  * <pre><code>
3611 var split = new Roo.SplitBar("elementToDrag", "elementToSize",
3612                    Roo.SplitBar.HORIZONTAL, Roo.SplitBar.LEFT);
3613 split.setAdapter(new Roo.SplitBar.AbsoluteLayoutAdapter("container"));
3614 split.minSize = 100;
3615 split.maxSize = 600;
3616 split.animate = true;
3617 split.on('moved', splitterMoved);
3618 </code></pre>
3619  * @constructor
3620  * Create a new SplitBar
3621  * @param {String/HTMLElement/Roo.Element} dragElement The element to be dragged and act as the SplitBar. 
3622  * @param {String/HTMLElement/Roo.Element} resizingElement The element to be resized based on where the SplitBar element is dragged 
3623  * @param {Number} orientation (optional) Either Roo.SplitBar.HORIZONTAL or Roo.SplitBar.VERTICAL. (Defaults to HORIZONTAL)
3624  * @param {Number} placement (optional) Either Roo.SplitBar.LEFT or Roo.SplitBar.RIGHT for horizontal or  
3625                         Roo.SplitBar.TOP or Roo.SplitBar.BOTTOM for vertical. (By default, this is determined automatically by the initial
3626                         position of the SplitBar).
3627  */
3628 Roo.SplitBar = function(dragElement, resizingElement, orientation, placement, existingProxy){
3629     
3630     /** @private */
3631     this.el = Roo.get(dragElement, true);
3632     this.el.dom.unselectable = "on";
3633     /** @private */
3634     this.resizingEl = Roo.get(resizingElement, true);
3635
3636     /**
3637      * @private
3638      * The orientation of the split. Either Roo.SplitBar.HORIZONTAL or Roo.SplitBar.VERTICAL. (Defaults to HORIZONTAL)
3639      * Note: If this is changed after creating the SplitBar, the placement property must be manually updated
3640      * @type Number
3641      */
3642     this.orientation = orientation || Roo.SplitBar.HORIZONTAL;
3643     
3644     /**
3645      * The minimum size of the resizing element. (Defaults to 0)
3646      * @type Number
3647      */
3648     this.minSize = 0;
3649     
3650     /**
3651      * The maximum size of the resizing element. (Defaults to 2000)
3652      * @type Number
3653      */
3654     this.maxSize = 2000;
3655     
3656     /**
3657      * Whether to animate the transition to the new size
3658      * @type Boolean
3659      */
3660     this.animate = false;
3661     
3662     /**
3663      * Whether to create a transparent shim that overlays the page when dragging, enables dragging across iframes.
3664      * @type Boolean
3665      */
3666     this.useShim = false;
3667     
3668     /** @private */
3669     this.shim = null;
3670     
3671     if(!existingProxy){
3672         /** @private */
3673         this.proxy = Roo.SplitBar.createProxy(this.orientation);
3674     }else{
3675         this.proxy = Roo.get(existingProxy).dom;
3676     }
3677     /** @private */
3678     this.dd = new Roo.dd.DDProxy(this.el.dom.id, "XSplitBars", {dragElId : this.proxy.id});
3679     
3680     /** @private */
3681     this.dd.b4StartDrag = this.onStartProxyDrag.createDelegate(this);
3682     
3683     /** @private */
3684     this.dd.endDrag = this.onEndProxyDrag.createDelegate(this);
3685     
3686     /** @private */
3687     this.dragSpecs = {};
3688     
3689     /**
3690      * @private The adapter to use to positon and resize elements
3691      */
3692     this.adapter = new Roo.SplitBar.BasicLayoutAdapter();
3693     this.adapter.init(this);
3694     
3695     if(this.orientation == Roo.SplitBar.HORIZONTAL){
3696         /** @private */
3697         this.placement = placement || (this.el.getX() > this.resizingEl.getX() ? Roo.SplitBar.LEFT : Roo.SplitBar.RIGHT);
3698         this.el.addClass("x-splitbar-h");
3699     }else{
3700         /** @private */
3701         this.placement = placement || (this.el.getY() > this.resizingEl.getY() ? Roo.SplitBar.TOP : Roo.SplitBar.BOTTOM);
3702         this.el.addClass("x-splitbar-v");
3703     }
3704     
3705     this.addEvents({
3706         /**
3707          * @event resize
3708          * Fires when the splitter is moved (alias for {@link #event-moved})
3709          * @param {Roo.SplitBar} this
3710          * @param {Number} newSize the new width or height
3711          */
3712         "resize" : true,
3713         /**
3714          * @event moved
3715          * Fires when the splitter is moved
3716          * @param {Roo.SplitBar} this
3717          * @param {Number} newSize the new width or height
3718          */
3719         "moved" : true,
3720         /**
3721          * @event beforeresize
3722          * Fires before the splitter is dragged
3723          * @param {Roo.SplitBar} this
3724          */
3725         "beforeresize" : true,
3726
3727         "beforeapply" : true
3728     });
3729
3730     Roo.util.Observable.call(this);
3731 };
3732
3733 Roo.extend(Roo.SplitBar, Roo.util.Observable, {
3734     onStartProxyDrag : function(x, y){
3735         this.fireEvent("beforeresize", this);
3736         if(!this.overlay){
3737             var o = Roo.DomHelper.insertFirst(document.body,  {cls: "x-drag-overlay", html: "&#160;"}, true);
3738             o.unselectable();
3739             o.enableDisplayMode("block");
3740             // all splitbars share the same overlay
3741             Roo.SplitBar.prototype.overlay = o;
3742         }
3743         this.overlay.setSize(Roo.lib.Dom.getViewWidth(true), Roo.lib.Dom.getViewHeight(true));
3744         this.overlay.show();
3745         Roo.get(this.proxy).setDisplayed("block");
3746         var size = this.adapter.getElementSize(this);
3747         this.activeMinSize = this.getMinimumSize();;
3748         this.activeMaxSize = this.getMaximumSize();;
3749         var c1 = size - this.activeMinSize;
3750         var c2 = Math.max(this.activeMaxSize - size, 0);
3751         if(this.orientation == Roo.SplitBar.HORIZONTAL){
3752             this.dd.resetConstraints();
3753             this.dd.setXConstraint(
3754                 this.placement == Roo.SplitBar.LEFT ? c1 : c2, 
3755                 this.placement == Roo.SplitBar.LEFT ? c2 : c1
3756             );
3757             this.dd.setYConstraint(0, 0);
3758         }else{
3759             this.dd.resetConstraints();
3760             this.dd.setXConstraint(0, 0);
3761             this.dd.setYConstraint(
3762                 this.placement == Roo.SplitBar.TOP ? c1 : c2, 
3763                 this.placement == Roo.SplitBar.TOP ? c2 : c1
3764             );
3765          }
3766         this.dragSpecs.startSize = size;
3767         this.dragSpecs.startPoint = [x, y];
3768         Roo.dd.DDProxy.prototype.b4StartDrag.call(this.dd, x, y);
3769     },
3770     
3771     /** 
3772      * @private Called after the drag operation by the DDProxy
3773      */
3774     onEndProxyDrag : function(e){
3775         Roo.get(this.proxy).setDisplayed(false);
3776         var endPoint = Roo.lib.Event.getXY(e);
3777         if(this.overlay){
3778             this.overlay.hide();
3779         }
3780         var newSize;
3781         if(this.orientation == Roo.SplitBar.HORIZONTAL){
3782             newSize = this.dragSpecs.startSize + 
3783                 (this.placement == Roo.SplitBar.LEFT ?
3784                     endPoint[0] - this.dragSpecs.startPoint[0] :
3785                     this.dragSpecs.startPoint[0] - endPoint[0]
3786                 );
3787         }else{
3788             newSize = this.dragSpecs.startSize + 
3789                 (this.placement == Roo.SplitBar.TOP ?
3790                     endPoint[1] - this.dragSpecs.startPoint[1] :
3791                     this.dragSpecs.startPoint[1] - endPoint[1]
3792                 );
3793         }
3794         newSize = Math.min(Math.max(newSize, this.activeMinSize), this.activeMaxSize);
3795         if(newSize != this.dragSpecs.startSize){
3796             if(this.fireEvent('beforeapply', this, newSize) !== false){
3797                 this.adapter.setElementSize(this, newSize);
3798                 this.fireEvent("moved", this, newSize);
3799                 this.fireEvent("resize", this, newSize);
3800             }
3801         }
3802     },
3803     
3804     /**
3805      * Get the adapter this SplitBar uses
3806      * @return The adapter object
3807      */
3808     getAdapter : function(){
3809         return this.adapter;
3810     },
3811     
3812     /**
3813      * Set the adapter this SplitBar uses
3814      * @param {Object} adapter A SplitBar adapter object
3815      */
3816     setAdapter : function(adapter){
3817         this.adapter = adapter;
3818         this.adapter.init(this);
3819     },
3820     
3821     /**
3822      * Gets the minimum size for the resizing element
3823      * @return {Number} The minimum size
3824      */
3825     getMinimumSize : function(){
3826         return this.minSize;
3827     },
3828     
3829     /**
3830      * Sets the minimum size for the resizing element
3831      * @param {Number} minSize The minimum size
3832      */
3833     setMinimumSize : function(minSize){
3834         this.minSize = minSize;
3835     },
3836     
3837     /**
3838      * Gets the maximum size for the resizing element
3839      * @return {Number} The maximum size
3840      */
3841     getMaximumSize : function(){
3842         return this.maxSize;
3843     },
3844     
3845     /**
3846      * Sets the maximum size for the resizing element
3847      * @param {Number} maxSize The maximum size
3848      */
3849     setMaximumSize : function(maxSize){
3850         this.maxSize = maxSize;
3851     },
3852     
3853     /**
3854      * Sets the initialize size for the resizing element
3855      * @param {Number} size The initial size
3856      */
3857     setCurrentSize : function(size){
3858         var oldAnimate = this.animate;
3859         this.animate = false;
3860         this.adapter.setElementSize(this, size);
3861         this.animate = oldAnimate;
3862     },
3863     
3864     /**
3865      * Destroy this splitbar. 
3866      * @param {Boolean} removeEl True to remove the element
3867      */
3868     destroy : function(removeEl){
3869         if(this.shim){
3870             this.shim.remove();
3871         }
3872         this.dd.unreg();
3873         this.proxy.parentNode.removeChild(this.proxy);
3874         if(removeEl){
3875             this.el.remove();
3876         }
3877     }
3878 });
3879
3880 /**
3881  * @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.
3882  */
3883 Roo.SplitBar.createProxy = function(dir){
3884     var proxy = new Roo.Element(document.createElement("div"));
3885     proxy.unselectable();
3886     var cls = 'x-splitbar-proxy';
3887     proxy.addClass(cls + ' ' + (dir == Roo.SplitBar.HORIZONTAL ? cls +'-h' : cls + '-v'));
3888     document.body.appendChild(proxy.dom);
3889     return proxy.dom;
3890 };
3891
3892 /** 
3893  * @class Roo.SplitBar.BasicLayoutAdapter
3894  * Default Adapter. It assumes the splitter and resizing element are not positioned
3895  * elements and only gets/sets the width of the element. Generally used for table based layouts.
3896  */
3897 Roo.SplitBar.BasicLayoutAdapter = function(){
3898 };
3899
3900 Roo.SplitBar.BasicLayoutAdapter.prototype = {
3901     // do nothing for now
3902     init : function(s){
3903     
3904     },
3905     /**
3906      * Called before drag operations to get the current size of the resizing element. 
3907      * @param {Roo.SplitBar} s The SplitBar using this adapter
3908      */
3909      getElementSize : function(s){
3910         if(s.orientation == Roo.SplitBar.HORIZONTAL){
3911             return s.resizingEl.getWidth();
3912         }else{
3913             return s.resizingEl.getHeight();
3914         }
3915     },
3916     
3917     /**
3918      * Called after drag operations to set the size of the resizing element.
3919      * @param {Roo.SplitBar} s The SplitBar using this adapter
3920      * @param {Number} newSize The new size to set
3921      * @param {Function} onComplete A function to be invoked when resizing is complete
3922      */
3923     setElementSize : function(s, newSize, onComplete){
3924         if(s.orientation == Roo.SplitBar.HORIZONTAL){
3925             if(!s.animate){
3926                 s.resizingEl.setWidth(newSize);
3927                 if(onComplete){
3928                     onComplete(s, newSize);
3929                 }
3930             }else{
3931                 s.resizingEl.setWidth(newSize, true, .1, onComplete, 'easeOut');
3932             }
3933         }else{
3934             
3935             if(!s.animate){
3936                 s.resizingEl.setHeight(newSize);
3937                 if(onComplete){
3938                     onComplete(s, newSize);
3939                 }
3940             }else{
3941                 s.resizingEl.setHeight(newSize, true, .1, onComplete, 'easeOut');
3942             }
3943         }
3944     }
3945 };
3946
3947 /** 
3948  *@class Roo.SplitBar.AbsoluteLayoutAdapter
3949  * @extends Roo.SplitBar.BasicLayoutAdapter
3950  * Adapter that  moves the splitter element to align with the resized sizing element. 
3951  * Used with an absolute positioned SplitBar.
3952  * @param {String/HTMLElement/Roo.Element} container The container that wraps around the absolute positioned content. If it's
3953  * document.body, make sure you assign an id to the body element.
3954  */
3955 Roo.SplitBar.AbsoluteLayoutAdapter = function(container){
3956     this.basic = new Roo.SplitBar.BasicLayoutAdapter();
3957     this.container = Roo.get(container);
3958 };
3959
3960 Roo.SplitBar.AbsoluteLayoutAdapter.prototype = {
3961     init : function(s){
3962         this.basic.init(s);
3963     },
3964     
3965     getElementSize : function(s){
3966         return this.basic.getElementSize(s);
3967     },
3968     
3969     setElementSize : function(s, newSize, onComplete){
3970         this.basic.setElementSize(s, newSize, this.moveSplitter.createDelegate(this, [s]));
3971     },
3972     
3973     moveSplitter : function(s){
3974         var yes = Roo.SplitBar;
3975         switch(s.placement){
3976             case yes.LEFT:
3977                 s.el.setX(s.resizingEl.getRight());
3978                 break;
3979             case yes.RIGHT:
3980                 s.el.setStyle("right", (this.container.getWidth() - s.resizingEl.getLeft()) + "px");
3981                 break;
3982             case yes.TOP:
3983                 s.el.setY(s.resizingEl.getBottom());
3984                 break;
3985             case yes.BOTTOM:
3986                 s.el.setY(s.resizingEl.getTop() - s.el.getHeight());
3987                 break;
3988         }
3989     }
3990 };
3991
3992 /**
3993  * Orientation constant - Create a vertical SplitBar
3994  * @static
3995  * @type Number
3996  */
3997 Roo.SplitBar.VERTICAL = 1;
3998
3999 /**
4000  * Orientation constant - Create a horizontal SplitBar
4001  * @static
4002  * @type Number
4003  */
4004 Roo.SplitBar.HORIZONTAL = 2;
4005
4006 /**
4007  * Placement constant - The resizing element is to the left of the splitter element
4008  * @static
4009  * @type Number
4010  */
4011 Roo.SplitBar.LEFT = 1;
4012
4013 /**
4014  * Placement constant - The resizing element is to the right of the splitter element
4015  * @static
4016  * @type Number
4017  */
4018 Roo.SplitBar.RIGHT = 2;
4019
4020 /**
4021  * Placement constant - The resizing element is positioned above the splitter element
4022  * @static
4023  * @type Number
4024  */
4025 Roo.SplitBar.TOP = 3;
4026
4027 /**
4028  * Placement constant - The resizing element is positioned under splitter element
4029  * @static
4030  * @type Number
4031  */
4032 Roo.SplitBar.BOTTOM = 4;
4033 /*
4034  * Based on:
4035  * Ext JS Library 1.1.1
4036  * Copyright(c) 2006-2007, Ext JS, LLC.
4037  *
4038  * Originally Released Under LGPL - original licence link has changed is not relivant.
4039  *
4040  * Fork - LGPL
4041  * <script type="text/javascript">
4042  */
4043
4044 /**
4045  * @class Roo.View
4046  * @extends Roo.util.Observable
4047  * Create a "View" for an element based on a data model or UpdateManager and the supplied DomHelper template. 
4048  * This class also supports single and multi selection modes. <br>
4049  * Create a data model bound view:
4050  <pre><code>
4051  var store = new Roo.data.Store(...);
4052
4053  var view = new Roo.View({
4054     el : "my-element",
4055     tpl : '&lt;div id="{0}"&gt;{2} - {1}&lt;/div&gt;', // auto create template
4056  
4057     singleSelect: true,
4058     selectedClass: "ydataview-selected",
4059     store: store
4060  });
4061
4062  // listen for node click?
4063  view.on("click", function(vw, index, node, e){
4064  alert('Node "' + node.id + '" at index: ' + index + " was clicked.");
4065  });
4066
4067  // load XML data
4068  dataModel.load("foobar.xml");
4069  </code></pre>
4070  For an example of creating a JSON/UpdateManager view, see {@link Roo.JsonView}.
4071  * <br><br>
4072  * <b>Note: The root of your template must be a single node. Table/row implementations may work but are not supported due to
4073  * IE"s limited insertion support with tables and Opera"s faulty event bubbling.</b>
4074  * 
4075  * Note: old style constructor is still suported (container, template, config)
4076  * 
4077  * @constructor
4078  * Create a new View
4079  * @param {Object} config The config object
4080  * 
4081  */
4082 Roo.View = function(config, depreciated_tpl, depreciated_config){
4083     
4084     this.parent = false;
4085     
4086     if (typeof(depreciated_tpl) == 'undefined') {
4087         // new way.. - universal constructor.
4088         Roo.apply(this, config);
4089         this.el  = Roo.get(this.el);
4090     } else {
4091         // old format..
4092         this.el  = Roo.get(config);
4093         this.tpl = depreciated_tpl;
4094         Roo.apply(this, depreciated_config);
4095     }
4096     this.wrapEl  = this.el.wrap().wrap();
4097     ///this.el = this.wrapEla.appendChild(document.createElement("div"));
4098     
4099     
4100     if(typeof(this.tpl) == "string"){
4101         this.tpl = new Roo.Template(this.tpl);
4102     } else {
4103         // support xtype ctors..
4104         this.tpl = new Roo.factory(this.tpl, Roo);
4105     }
4106     
4107     
4108     this.tpl.compile();
4109     
4110     /** @private */
4111     this.addEvents({
4112         /**
4113          * @event beforeclick
4114          * Fires before a click is processed. Returns false to cancel the default action.
4115          * @param {Roo.View} this
4116          * @param {Number} index The index of the target node
4117          * @param {HTMLElement} node The target node
4118          * @param {Roo.EventObject} e The raw event object
4119          */
4120             "beforeclick" : true,
4121         /**
4122          * @event click
4123          * Fires when a template node is clicked.
4124          * @param {Roo.View} this
4125          * @param {Number} index The index of the target node
4126          * @param {HTMLElement} node The target node
4127          * @param {Roo.EventObject} e The raw event object
4128          */
4129             "click" : true,
4130         /**
4131          * @event dblclick
4132          * Fires when a template node is double clicked.
4133          * @param {Roo.View} this
4134          * @param {Number} index The index of the target node
4135          * @param {HTMLElement} node The target node
4136          * @param {Roo.EventObject} e The raw event object
4137          */
4138             "dblclick" : true,
4139         /**
4140          * @event contextmenu
4141          * Fires when a template node is right clicked.
4142          * @param {Roo.View} this
4143          * @param {Number} index The index of the target node
4144          * @param {HTMLElement} node The target node
4145          * @param {Roo.EventObject} e The raw event object
4146          */
4147             "contextmenu" : true,
4148         /**
4149          * @event selectionchange
4150          * Fires when the selected nodes change.
4151          * @param {Roo.View} this
4152          * @param {Array} selections Array of the selected nodes
4153          */
4154             "selectionchange" : true,
4155     
4156         /**
4157          * @event beforeselect
4158          * Fires before a selection is made. If any handlers return false, the selection is cancelled.
4159          * @param {Roo.View} this
4160          * @param {HTMLElement} node The node to be selected
4161          * @param {Array} selections Array of currently selected nodes
4162          */
4163             "beforeselect" : true,
4164         /**
4165          * @event preparedata
4166          * Fires on every row to render, to allow you to change the data.
4167          * @param {Roo.View} this
4168          * @param {Object} data to be rendered (change this)
4169          */
4170           "preparedata" : true
4171           
4172           
4173         });
4174
4175
4176
4177     this.el.on({
4178         "click": this.onClick,
4179         "dblclick": this.onDblClick,
4180         "contextmenu": this.onContextMenu,
4181         scope:this
4182     });
4183
4184     this.selections = [];
4185     this.nodes = [];
4186     this.cmp = new Roo.CompositeElementLite([]);
4187     if(this.store){
4188         this.store = Roo.factory(this.store, Roo.data);
4189         this.setStore(this.store, true);
4190     }
4191     
4192     if ( this.footer && this.footer.xtype) {
4193            
4194          var fctr = this.wrapEl.appendChild(document.createElement("div"));
4195         
4196         this.footer.dataSource = this.store;
4197         this.footer.container = fctr;
4198         this.footer = Roo.factory(this.footer, Roo);
4199         fctr.insertFirst(this.el);
4200         
4201         // this is a bit insane - as the paging toolbar seems to detach the el..
4202 //        dom.parentNode.parentNode.parentNode
4203          // they get detached?
4204     }
4205     
4206     
4207     Roo.View.superclass.constructor.call(this);
4208     
4209     
4210 };
4211
4212 Roo.extend(Roo.View, Roo.util.Observable, {
4213     
4214      /**
4215      * @cfg {Roo.data.Store} store Data store to load data from.
4216      */
4217     store : false,
4218     
4219     /**
4220      * @cfg {String|Roo.Element} el The container element.
4221      */
4222     el : '',
4223     
4224     /**
4225      * @cfg {String|Roo.Template} tpl The template used by this View 
4226      */
4227     tpl : false,
4228     /**
4229      * @cfg {String} dataName the named area of the template to use as the data area
4230      *                          Works with domtemplates roo-name="name"
4231      */
4232     dataName: false,
4233     /**
4234      * @cfg {String} selectedClass The css class to add to selected nodes
4235      */
4236     selectedClass : "x-view-selected",
4237      /**
4238      * @cfg {String} emptyText The empty text to show when nothing is loaded.
4239      */
4240     emptyText : "",
4241     
4242     /**
4243      * @cfg {String} text to display on mask (default Loading)
4244      */
4245     mask : false,
4246     /**
4247      * @cfg {Boolean} multiSelect Allow multiple selection
4248      */
4249     multiSelect : false,
4250     /**
4251      * @cfg {Boolean} singleSelect Allow single selection
4252      */
4253     singleSelect:  false,
4254     
4255     /**
4256      * @cfg {Boolean} toggleSelect - selecting 
4257      */
4258     toggleSelect : false,
4259     
4260     /**
4261      * @cfg {Boolean} tickable - selecting 
4262      */
4263     tickable : false,
4264     
4265     /**
4266      * Returns the element this view is bound to.
4267      * @return {Roo.Element}
4268      */
4269     getEl : function(){
4270         return this.wrapEl;
4271     },
4272     
4273     
4274
4275     /**
4276      * Refreshes the view. - called by datachanged on the store. - do not call directly.
4277      */
4278     refresh : function(){
4279         //Roo.log('refresh');
4280         var t = this.tpl;
4281         
4282         // if we are using something like 'domtemplate', then
4283         // the what gets used is:
4284         // t.applySubtemplate(NAME, data, wrapping data..)
4285         // the outer template then get' applied with
4286         //     the store 'extra data'
4287         // and the body get's added to the
4288         //      roo-name="data" node?
4289         //      <span class='roo-tpl-{name}'></span> ?????
4290         
4291         
4292         
4293         this.clearSelections();
4294         this.el.update("");
4295         var html = [];
4296         var records = this.store.getRange();
4297         if(records.length < 1) {
4298             
4299             // is this valid??  = should it render a template??
4300             
4301             this.el.update(this.emptyText);
4302             return;
4303         }
4304         var el = this.el;
4305         if (this.dataName) {
4306             this.el.update(t.apply(this.store.meta)); //????
4307             el = this.el.child('.roo-tpl-' + this.dataName);
4308         }
4309         
4310         for(var i = 0, len = records.length; i < len; i++){
4311             var data = this.prepareData(records[i].data, i, records[i]);
4312             this.fireEvent("preparedata", this, data, i, records[i]);
4313             
4314             var d = Roo.apply({}, data);
4315             
4316             if(this.tickable){
4317                 Roo.apply(d, {'roo-id' : Roo.id()});
4318                 
4319                 var _this = this;
4320             
4321                 Roo.each(this.parent.item, function(item){
4322                     if(item[_this.parent.valueField] != data[_this.parent.valueField]){
4323                         return;
4324                     }
4325                     Roo.apply(d, {'roo-data-checked' : 'checked'});
4326                 });
4327             }
4328             
4329             html[html.length] = Roo.util.Format.trim(
4330                 this.dataName ?
4331                     t.applySubtemplate(this.dataName, d, this.store.meta) :
4332                     t.apply(d)
4333             );
4334         }
4335         
4336         
4337         
4338         el.update(html.join(""));
4339         this.nodes = el.dom.childNodes;
4340         this.updateIndexes(0);
4341     },
4342     
4343
4344     /**
4345      * Function to override to reformat the data that is sent to
4346      * the template for each node.
4347      * DEPRICATED - use the preparedata event handler.
4348      * @param {Array/Object} data The raw data (array of colData for a data model bound view or
4349      * a JSON object for an UpdateManager bound view).
4350      */
4351     prepareData : function(data, index, record)
4352     {
4353         this.fireEvent("preparedata", this, data, index, record);
4354         return data;
4355     },
4356
4357     onUpdate : function(ds, record){
4358         // Roo.log('on update');   
4359         this.clearSelections();
4360         var index = this.store.indexOf(record);
4361         var n = this.nodes[index];
4362         this.tpl.insertBefore(n, this.prepareData(record.data, index, record));
4363         n.parentNode.removeChild(n);
4364         this.updateIndexes(index, index);
4365     },
4366
4367     
4368     
4369 // --------- FIXME     
4370     onAdd : function(ds, records, index)
4371     {
4372         //Roo.log(['on Add', ds, records, index] );        
4373         this.clearSelections();
4374         if(this.nodes.length == 0){
4375             this.refresh();
4376             return;
4377         }
4378         var n = this.nodes[index];
4379         for(var i = 0, len = records.length; i < len; i++){
4380             var d = this.prepareData(records[i].data, i, records[i]);
4381             if(n){
4382                 this.tpl.insertBefore(n, d);
4383             }else{
4384                 
4385                 this.tpl.append(this.el, d);
4386             }
4387         }
4388         this.updateIndexes(index);
4389     },
4390
4391     onRemove : function(ds, record, index){
4392        // Roo.log('onRemove');
4393         this.clearSelections();
4394         var el = this.dataName  ?
4395             this.el.child('.roo-tpl-' + this.dataName) :
4396             this.el; 
4397         
4398         el.dom.removeChild(this.nodes[index]);
4399         this.updateIndexes(index);
4400     },
4401
4402     /**
4403      * Refresh an individual node.
4404      * @param {Number} index
4405      */
4406     refreshNode : function(index){
4407         this.onUpdate(this.store, this.store.getAt(index));
4408     },
4409
4410     updateIndexes : function(startIndex, endIndex){
4411         var ns = this.nodes;
4412         startIndex = startIndex || 0;
4413         endIndex = endIndex || ns.length - 1;
4414         for(var i = startIndex; i <= endIndex; i++){
4415             ns[i].nodeIndex = i;
4416         }
4417     },
4418
4419     /**
4420      * Changes the data store this view uses and refresh the view.
4421      * @param {Store} store
4422      */
4423     setStore : function(store, initial){
4424         if(!initial && this.store){
4425             this.store.un("datachanged", this.refresh);
4426             this.store.un("add", this.onAdd);
4427             this.store.un("remove", this.onRemove);
4428             this.store.un("update", this.onUpdate);
4429             this.store.un("clear", this.refresh);
4430             this.store.un("beforeload", this.onBeforeLoad);
4431             this.store.un("load", this.onLoad);
4432             this.store.un("loadexception", this.onLoad);
4433         }
4434         if(store){
4435           
4436             store.on("datachanged", this.refresh, this);
4437             store.on("add", this.onAdd, this);
4438             store.on("remove", this.onRemove, this);
4439             store.on("update", this.onUpdate, this);
4440             store.on("clear", this.refresh, this);
4441             store.on("beforeload", this.onBeforeLoad, this);
4442             store.on("load", this.onLoad, this);
4443             store.on("loadexception", this.onLoad, this);
4444         }
4445         
4446         if(store){
4447             this.refresh();
4448         }
4449     },
4450     /**
4451      * onbeforeLoad - masks the loading area.
4452      *
4453      */
4454     onBeforeLoad : function(store,opts)
4455     {
4456          //Roo.log('onBeforeLoad');   
4457         if (!opts.add) {
4458             this.el.update("");
4459         }
4460         this.el.mask(this.mask ? this.mask : "Loading" ); 
4461     },
4462     onLoad : function ()
4463     {
4464         this.el.unmask();
4465     },
4466     
4467
4468     /**
4469      * Returns the template node the passed child belongs to or null if it doesn't belong to one.
4470      * @param {HTMLElement} node
4471      * @return {HTMLElement} The template node
4472      */
4473     findItemFromChild : function(node){
4474         var el = this.dataName  ?
4475             this.el.child('.roo-tpl-' + this.dataName,true) :
4476             this.el.dom; 
4477         
4478         if(!node || node.parentNode == el){
4479                     return node;
4480             }
4481             var p = node.parentNode;
4482             while(p && p != el){
4483             if(p.parentNode == el){
4484                 return p;
4485             }
4486             p = p.parentNode;
4487         }
4488             return null;
4489     },
4490
4491     /** @ignore */
4492     onClick : function(e){
4493         var item = this.findItemFromChild(e.getTarget());
4494         if(item){
4495             var index = this.indexOf(item);
4496             if(this.onItemClick(item, index, e) !== false){
4497                 this.fireEvent("click", this, index, item, e);
4498             }
4499         }else{
4500             this.clearSelections();
4501         }
4502     },
4503
4504     /** @ignore */
4505     onContextMenu : function(e){
4506         var item = this.findItemFromChild(e.getTarget());
4507         if(item){
4508             this.fireEvent("contextmenu", this, this.indexOf(item), item, e);
4509         }
4510     },
4511
4512     /** @ignore */
4513     onDblClick : function(e){
4514         var item = this.findItemFromChild(e.getTarget());
4515         if(item){
4516             this.fireEvent("dblclick", this, this.indexOf(item), item, e);
4517         }
4518     },
4519
4520     onItemClick : function(item, index, e)
4521     {
4522         if(this.fireEvent("beforeclick", this, index, item, e) === false){
4523             return false;
4524         }
4525         if (this.toggleSelect) {
4526             var m = this.isSelected(item) ? 'unselect' : 'select';
4527             //Roo.log(m);
4528             var _t = this;
4529             _t[m](item, true, false);
4530             return true;
4531         }
4532         if(this.multiSelect || this.singleSelect){
4533             if(this.multiSelect && e.shiftKey && this.lastSelection){
4534                 this.select(this.getNodes(this.indexOf(this.lastSelection), index), false);
4535             }else{
4536                 this.select(item, this.multiSelect && e.ctrlKey);
4537                 this.lastSelection = item;
4538             }
4539             
4540             if(!this.tickable){
4541                 e.preventDefault();
4542             }
4543             
4544         }
4545         return true;
4546     },
4547
4548     /**
4549      * Get the number of selected nodes.
4550      * @return {Number}
4551      */
4552     getSelectionCount : function(){
4553         return this.selections.length;
4554     },
4555
4556     /**
4557      * Get the currently selected nodes.
4558      * @return {Array} An array of HTMLElements
4559      */
4560     getSelectedNodes : function(){
4561         return this.selections;
4562     },
4563
4564     /**
4565      * Get the indexes of the selected nodes.
4566      * @return {Array}
4567      */
4568     getSelectedIndexes : function(){
4569         var indexes = [], s = this.selections;
4570         for(var i = 0, len = s.length; i < len; i++){
4571             indexes.push(s[i].nodeIndex);
4572         }
4573         return indexes;
4574     },
4575
4576     /**
4577      * Clear all selections
4578      * @param {Boolean} suppressEvent (optional) true to skip firing of the selectionchange event
4579      */
4580     clearSelections : function(suppressEvent){
4581         if(this.nodes && (this.multiSelect || this.singleSelect) && this.selections.length > 0){
4582             this.cmp.elements = this.selections;
4583             this.cmp.removeClass(this.selectedClass);
4584             this.selections = [];
4585             if(!suppressEvent){
4586                 this.fireEvent("selectionchange", this, this.selections);
4587             }
4588         }
4589     },
4590
4591     /**
4592      * Returns true if the passed node is selected
4593      * @param {HTMLElement/Number} node The node or node index
4594      * @return {Boolean}
4595      */
4596     isSelected : function(node){
4597         var s = this.selections;
4598         if(s.length < 1){
4599             return false;
4600         }
4601         node = this.getNode(node);
4602         return s.indexOf(node) !== -1;
4603     },
4604
4605     /**
4606      * Selects nodes.
4607      * @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
4608      * @param {Boolean} keepExisting (optional) true to keep existing selections
4609      * @param {Boolean} suppressEvent (optional) true to skip firing of the selectionchange vent
4610      */
4611     select : function(nodeInfo, keepExisting, suppressEvent){
4612         if(nodeInfo instanceof Array){
4613             if(!keepExisting){
4614                 this.clearSelections(true);
4615             }
4616             for(var i = 0, len = nodeInfo.length; i < len; i++){
4617                 this.select(nodeInfo[i], true, true);
4618             }
4619             return;
4620         } 
4621         var node = this.getNode(nodeInfo);
4622         if(!node || this.isSelected(node)){
4623             return; // already selected.
4624         }
4625         if(!keepExisting){
4626             this.clearSelections(true);
4627         }
4628         
4629         if(this.fireEvent("beforeselect", this, node, this.selections) !== false){
4630             Roo.fly(node).addClass(this.selectedClass);
4631             this.selections.push(node);
4632             if(!suppressEvent){
4633                 this.fireEvent("selectionchange", this, this.selections);
4634             }
4635         }
4636         
4637         
4638     },
4639       /**
4640      * Unselects nodes.
4641      * @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
4642      * @param {Boolean} keepExisting (optional) true IGNORED (for campatibility with select)
4643      * @param {Boolean} suppressEvent (optional) true to skip firing of the selectionchange vent
4644      */
4645     unselect : function(nodeInfo, keepExisting, suppressEvent)
4646     {
4647         if(nodeInfo instanceof Array){
4648             Roo.each(this.selections, function(s) {
4649                 this.unselect(s, nodeInfo);
4650             }, this);
4651             return;
4652         }
4653         var node = this.getNode(nodeInfo);
4654         if(!node || !this.isSelected(node)){
4655             //Roo.log("not selected");
4656             return; // not selected.
4657         }
4658         // fireevent???
4659         var ns = [];
4660         Roo.each(this.selections, function(s) {
4661             if (s == node ) {
4662                 Roo.fly(node).removeClass(this.selectedClass);
4663
4664                 return;
4665             }
4666             ns.push(s);
4667         },this);
4668         
4669         this.selections= ns;
4670         this.fireEvent("selectionchange", this, this.selections);
4671     },
4672
4673     /**
4674      * Gets a template node.
4675      * @param {HTMLElement/String/Number} nodeInfo An HTMLElement template node, index of a template node or the id of a template node
4676      * @return {HTMLElement} The node or null if it wasn't found
4677      */
4678     getNode : function(nodeInfo){
4679         if(typeof nodeInfo == "string"){
4680             return document.getElementById(nodeInfo);
4681         }else if(typeof nodeInfo == "number"){
4682             return this.nodes[nodeInfo];
4683         }
4684         return nodeInfo;
4685     },
4686
4687     /**
4688      * Gets a range template nodes.
4689      * @param {Number} startIndex
4690      * @param {Number} endIndex
4691      * @return {Array} An array of nodes
4692      */
4693     getNodes : function(start, end){
4694         var ns = this.nodes;
4695         start = start || 0;
4696         end = typeof end == "undefined" ? ns.length - 1 : end;
4697         var nodes = [];
4698         if(start <= end){
4699             for(var i = start; i <= end; i++){
4700                 nodes.push(ns[i]);
4701             }
4702         } else{
4703             for(var i = start; i >= end; i--){
4704                 nodes.push(ns[i]);
4705             }
4706         }
4707         return nodes;
4708     },
4709
4710     /**
4711      * Finds the index of the passed node
4712      * @param {HTMLElement/String/Number} nodeInfo An HTMLElement template node, index of a template node or the id of a template node
4713      * @return {Number} The index of the node or -1
4714      */
4715     indexOf : function(node){
4716         node = this.getNode(node);
4717         if(typeof node.nodeIndex == "number"){
4718             return node.nodeIndex;
4719         }
4720         var ns = this.nodes;
4721         for(var i = 0, len = ns.length; i < len; i++){
4722             if(ns[i] == node){
4723                 return i;
4724             }
4725         }
4726         return -1;
4727     }
4728 });
4729 /*
4730  * Based on:
4731  * Ext JS Library 1.1.1
4732  * Copyright(c) 2006-2007, Ext JS, LLC.
4733  *
4734  * Originally Released Under LGPL - original licence link has changed is not relivant.
4735  *
4736  * Fork - LGPL
4737  * <script type="text/javascript">
4738  */
4739
4740 /**
4741  * @class Roo.JsonView
4742  * @extends Roo.View
4743  * Shortcut class to create a JSON + {@link Roo.UpdateManager} template view. Usage:
4744 <pre><code>
4745 var view = new Roo.JsonView({
4746     container: "my-element",
4747     tpl: '&lt;div id="{id}"&gt;{foo} - {bar}&lt;/div&gt;', // auto create template
4748     multiSelect: true, 
4749     jsonRoot: "data" 
4750 });
4751
4752 // listen for node click?
4753 view.on("click", function(vw, index, node, e){
4754     alert('Node "' + node.id + '" at index: ' + index + " was clicked.");
4755 });
4756
4757 // direct load of JSON data
4758 view.load("foobar.php");
4759
4760 // Example from my blog list
4761 var tpl = new Roo.Template(
4762     '&lt;div class="entry"&gt;' +
4763     '&lt;a class="entry-title" href="{link}"&gt;{title}&lt;/a&gt;' +
4764     "&lt;h4&gt;{date} by {author} | {comments} Comments&lt;/h4&gt;{description}" +
4765     "&lt;/div&gt;&lt;hr /&gt;"
4766 );
4767
4768 var moreView = new Roo.JsonView({
4769     container :  "entry-list", 
4770     template : tpl,
4771     jsonRoot: "posts"
4772 });
4773 moreView.on("beforerender", this.sortEntries, this);
4774 moreView.load({
4775     url: "/blog/get-posts.php",
4776     params: "allposts=true",
4777     text: "Loading Blog Entries..."
4778 });
4779 </code></pre>
4780
4781 * Note: old code is supported with arguments : (container, template, config)
4782
4783
4784  * @constructor
4785  * Create a new JsonView
4786  * 
4787  * @param {Object} config The config object
4788  * 
4789  */
4790 Roo.JsonView = function(config, depreciated_tpl, depreciated_config){
4791     
4792     
4793     Roo.JsonView.superclass.constructor.call(this, config, depreciated_tpl, depreciated_config);
4794
4795     var um = this.el.getUpdateManager();
4796     um.setRenderer(this);
4797     um.on("update", this.onLoad, this);
4798     um.on("failure", this.onLoadException, this);
4799
4800     /**
4801      * @event beforerender
4802      * Fires before rendering of the downloaded JSON data.
4803      * @param {Roo.JsonView} this
4804      * @param {Object} data The JSON data loaded
4805      */
4806     /**
4807      * @event load
4808      * Fires when data is loaded.
4809      * @param {Roo.JsonView} this
4810      * @param {Object} data The JSON data loaded
4811      * @param {Object} response The raw Connect response object
4812      */
4813     /**
4814      * @event loadexception
4815      * Fires when loading fails.
4816      * @param {Roo.JsonView} this
4817      * @param {Object} response The raw Connect response object
4818      */
4819     this.addEvents({
4820         'beforerender' : true,
4821         'load' : true,
4822         'loadexception' : true
4823     });
4824 };
4825 Roo.extend(Roo.JsonView, Roo.View, {
4826     /**
4827      * @type {String} The root property in the loaded JSON object that contains the data
4828      */
4829     jsonRoot : "",
4830
4831     /**
4832      * Refreshes the view.
4833      */
4834     refresh : function(){
4835         this.clearSelections();
4836         this.el.update("");
4837         var html = [];
4838         var o = this.jsonData;
4839         if(o && o.length > 0){
4840             for(var i = 0, len = o.length; i < len; i++){
4841                 var data = this.prepareData(o[i], i, o);
4842                 html[html.length] = this.tpl.apply(data);
4843             }
4844         }else{
4845             html.push(this.emptyText);
4846         }
4847         this.el.update(html.join(""));
4848         this.nodes = this.el.dom.childNodes;
4849         this.updateIndexes(0);
4850     },
4851
4852     /**
4853      * 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.
4854      * @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:
4855      <pre><code>
4856      view.load({
4857          url: "your-url.php",
4858          params: {param1: "foo", param2: "bar"}, // or a URL encoded string
4859          callback: yourFunction,
4860          scope: yourObject, //(optional scope)
4861          discardUrl: false,
4862          nocache: false,
4863          text: "Loading...",
4864          timeout: 30,
4865          scripts: false
4866      });
4867      </code></pre>
4868      * The only required property is <i>url</i>. The optional properties <i>nocache</i>, <i>text</i> and <i>scripts</i>
4869      * 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.
4870      * @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}
4871      * @param {Function} callback (optional) Callback when transaction is complete - called with signature (oElement, bSuccess)
4872      * @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.
4873      */
4874     load : function(){
4875         var um = this.el.getUpdateManager();
4876         um.update.apply(um, arguments);
4877     },
4878
4879     // note - render is a standard framework call...
4880     // using it for the response is really flaky... - it's called by UpdateManager normally, except when called by the XComponent/addXtype.
4881     render : function(el, response){
4882         
4883         this.clearSelections();
4884         this.el.update("");
4885         var o;
4886         try{
4887             if (response != '') {
4888                 o = Roo.util.JSON.decode(response.responseText);
4889                 if(this.jsonRoot){
4890                     
4891                     o = o[this.jsonRoot];
4892                 }
4893             }
4894         } catch(e){
4895         }
4896         /**
4897          * The current JSON data or null
4898          */
4899         this.jsonData = o;
4900         this.beforeRender();
4901         this.refresh();
4902     },
4903
4904 /**
4905  * Get the number of records in the current JSON dataset
4906  * @return {Number}
4907  */
4908     getCount : function(){
4909         return this.jsonData ? this.jsonData.length : 0;
4910     },
4911
4912 /**
4913  * Returns the JSON object for the specified node(s)
4914  * @param {HTMLElement/Array} node The node or an array of nodes
4915  * @return {Object/Array} If you pass in an array, you get an array back, otherwise
4916  * you get the JSON object for the node
4917  */
4918     getNodeData : function(node){
4919         if(node instanceof Array){
4920             var data = [];
4921             for(var i = 0, len = node.length; i < len; i++){
4922                 data.push(this.getNodeData(node[i]));
4923             }
4924             return data;
4925         }
4926         return this.jsonData[this.indexOf(node)] || null;
4927     },
4928
4929     beforeRender : function(){
4930         this.snapshot = this.jsonData;
4931         if(this.sortInfo){
4932             this.sort.apply(this, this.sortInfo);
4933         }
4934         this.fireEvent("beforerender", this, this.jsonData);
4935     },
4936
4937     onLoad : function(el, o){
4938         this.fireEvent("load", this, this.jsonData, o);
4939     },
4940
4941     onLoadException : function(el, o){
4942         this.fireEvent("loadexception", this, o);
4943     },
4944
4945 /**
4946  * Filter the data by a specific property.
4947  * @param {String} property A property on your JSON objects
4948  * @param {String/RegExp} value Either string that the property values
4949  * should start with, or a RegExp to test against the property
4950  */
4951     filter : function(property, value){
4952         if(this.jsonData){
4953             var data = [];
4954             var ss = this.snapshot;
4955             if(typeof value == "string"){
4956                 var vlen = value.length;
4957                 if(vlen == 0){
4958                     this.clearFilter();
4959                     return;
4960                 }
4961                 value = value.toLowerCase();
4962                 for(var i = 0, len = ss.length; i < len; i++){
4963                     var o = ss[i];
4964                     if(o[property].substr(0, vlen).toLowerCase() == value){
4965                         data.push(o);
4966                     }
4967                 }
4968             } else if(value.exec){ // regex?
4969                 for(var i = 0, len = ss.length; i < len; i++){
4970                     var o = ss[i];
4971                     if(value.test(o[property])){
4972                         data.push(o);
4973                     }
4974                 }
4975             } else{
4976                 return;
4977             }
4978             this.jsonData = data;
4979             this.refresh();
4980         }
4981     },
4982
4983 /**
4984  * Filter by a function. The passed function will be called with each
4985  * object in the current dataset. If the function returns true the value is kept,
4986  * otherwise it is filtered.
4987  * @param {Function} fn
4988  * @param {Object} scope (optional) The scope of the function (defaults to this JsonView)
4989  */
4990     filterBy : function(fn, scope){
4991         if(this.jsonData){
4992             var data = [];
4993             var ss = this.snapshot;
4994             for(var i = 0, len = ss.length; i < len; i++){
4995                 var o = ss[i];
4996                 if(fn.call(scope || this, o)){
4997                     data.push(o);
4998                 }
4999             }
5000             this.jsonData = data;
5001             this.refresh();
5002         }
5003     },
5004
5005 /**
5006  * Clears the current filter.
5007  */
5008     clearFilter : function(){
5009         if(this.snapshot && this.jsonData != this.snapshot){
5010             this.jsonData = this.snapshot;
5011             this.refresh();
5012         }
5013     },
5014
5015
5016 /**
5017  * Sorts the data for this view and refreshes it.
5018  * @param {String} property A property on your JSON objects to sort on
5019  * @param {String} direction (optional) "desc" or "asc" (defaults to "asc")
5020  * @param {Function} sortType (optional) A function to call to convert the data to a sortable value.
5021  */
5022     sort : function(property, dir, sortType){
5023         this.sortInfo = Array.prototype.slice.call(arguments, 0);
5024         if(this.jsonData){
5025             var p = property;
5026             var dsc = dir && dir.toLowerCase() == "desc";
5027             var f = function(o1, o2){
5028                 var v1 = sortType ? sortType(o1[p]) : o1[p];
5029                 var v2 = sortType ? sortType(o2[p]) : o2[p];
5030                 ;
5031                 if(v1 < v2){
5032                     return dsc ? +1 : -1;
5033                 } else if(v1 > v2){
5034                     return dsc ? -1 : +1;
5035                 } else{
5036                     return 0;
5037                 }
5038             };
5039             this.jsonData.sort(f);
5040             this.refresh();
5041             if(this.jsonData != this.snapshot){
5042                 this.snapshot.sort(f);
5043             }
5044         }
5045     }
5046 });/*
5047  * Based on:
5048  * Ext JS Library 1.1.1
5049  * Copyright(c) 2006-2007, Ext JS, LLC.
5050  *
5051  * Originally Released Under LGPL - original licence link has changed is not relivant.
5052  *
5053  * Fork - LGPL
5054  * <script type="text/javascript">
5055  */
5056  
5057
5058 /**
5059  * @class Roo.ColorPalette
5060  * @extends Roo.Component
5061  * Simple color palette class for choosing colors.  The palette can be rendered to any container.<br />
5062  * Here's an example of typical usage:
5063  * <pre><code>
5064 var cp = new Roo.ColorPalette({value:'993300'});  // initial selected color
5065 cp.render('my-div');
5066
5067 cp.on('select', function(palette, selColor){
5068     // do something with selColor
5069 });
5070 </code></pre>
5071  * @constructor
5072  * Create a new ColorPalette
5073  * @param {Object} config The config object
5074  */
5075 Roo.ColorPalette = function(config){
5076     Roo.ColorPalette.superclass.constructor.call(this, config);
5077     this.addEvents({
5078         /**
5079              * @event select
5080              * Fires when a color is selected
5081              * @param {ColorPalette} this
5082              * @param {String} color The 6-digit color hex code (without the # symbol)
5083              */
5084         select: true
5085     });
5086
5087     if(this.handler){
5088         this.on("select", this.handler, this.scope, true);
5089     }
5090 };
5091 Roo.extend(Roo.ColorPalette, Roo.Component, {
5092     /**
5093      * @cfg {String} itemCls
5094      * The CSS class to apply to the containing element (defaults to "x-color-palette")
5095      */
5096     itemCls : "x-color-palette",
5097     /**
5098      * @cfg {String} value
5099      * The initial color to highlight (should be a valid 6-digit color hex code without the # symbol).  Note that
5100      * the hex codes are case-sensitive.
5101      */
5102     value : null,
5103     clickEvent:'click',
5104     // private
5105     ctype: "Roo.ColorPalette",
5106
5107     /**
5108      * @cfg {Boolean} allowReselect If set to true then reselecting a color that is already selected fires the selection event
5109      */
5110     allowReselect : false,
5111
5112     /**
5113      * <p>An array of 6-digit color hex code strings (without the # symbol).  This array can contain any number
5114      * of colors, and each hex code should be unique.  The width of the palette is controlled via CSS by adjusting
5115      * the width property of the 'x-color-palette' class (or assigning a custom class), so you can balance the number
5116      * of colors with the width setting until the box is symmetrical.</p>
5117      * <p>You can override individual colors if needed:</p>
5118      * <pre><code>
5119 var cp = new Roo.ColorPalette();
5120 cp.colors[0] = "FF0000";  // change the first box to red
5121 </code></pre>
5122
5123 Or you can provide a custom array of your own for complete control:
5124 <pre><code>
5125 var cp = new Roo.ColorPalette();
5126 cp.colors = ["000000", "993300", "333300"];
5127 </code></pre>
5128      * @type Array
5129      */
5130     colors : [
5131         "000000", "993300", "333300", "003300", "003366", "000080", "333399", "333333",
5132         "800000", "FF6600", "808000", "008000", "008080", "0000FF", "666699", "808080",
5133         "FF0000", "FF9900", "99CC00", "339966", "33CCCC", "3366FF", "800080", "969696",
5134         "FF00FF", "FFCC00", "FFFF00", "00FF00", "00FFFF", "00CCFF", "993366", "C0C0C0",
5135         "FF99CC", "FFCC99", "FFFF99", "CCFFCC", "CCFFFF", "99CCFF", "CC99FF", "FFFFFF"
5136     ],
5137
5138     // private
5139     onRender : function(container, position){
5140         var t = new Roo.MasterTemplate(
5141             '<tpl><a href="#" class="color-{0}" hidefocus="on"><em><span style="background:#{0}" unselectable="on">&#160;</span></em></a></tpl>'
5142         );
5143         var c = this.colors;
5144         for(var i = 0, len = c.length; i < len; i++){
5145             t.add([c[i]]);
5146         }
5147         var el = document.createElement("div");
5148         el.className = this.itemCls;
5149         t.overwrite(el);
5150         container.dom.insertBefore(el, position);
5151         this.el = Roo.get(el);
5152         this.el.on(this.clickEvent, this.handleClick,  this, {delegate: "a"});
5153         if(this.clickEvent != 'click'){
5154             this.el.on('click', Roo.emptyFn,  this, {delegate: "a", preventDefault:true});
5155         }
5156     },
5157
5158     // private
5159     afterRender : function(){
5160         Roo.ColorPalette.superclass.afterRender.call(this);
5161         if(this.value){
5162             var s = this.value;
5163             this.value = null;
5164             this.select(s);
5165         }
5166     },
5167
5168     // private
5169     handleClick : function(e, t){
5170         e.preventDefault();
5171         if(!this.disabled){
5172             var c = t.className.match(/(?:^|\s)color-(.{6})(?:\s|$)/)[1];
5173             this.select(c.toUpperCase());
5174         }
5175     },
5176
5177     /**
5178      * Selects the specified color in the palette (fires the select event)
5179      * @param {String} color A valid 6-digit color hex code (# will be stripped if included)
5180      */
5181     select : function(color){
5182         color = color.replace("#", "");
5183         if(color != this.value || this.allowReselect){
5184             var el = this.el;
5185             if(this.value){
5186                 el.child("a.color-"+this.value).removeClass("x-color-palette-sel");
5187             }
5188             el.child("a.color-"+color).addClass("x-color-palette-sel");
5189             this.value = color;
5190             this.fireEvent("select", this, color);
5191         }
5192     }
5193 });/*
5194  * Based on:
5195  * Ext JS Library 1.1.1
5196  * Copyright(c) 2006-2007, Ext JS, LLC.
5197  *
5198  * Originally Released Under LGPL - original licence link has changed is not relivant.
5199  *
5200  * Fork - LGPL
5201  * <script type="text/javascript">
5202  */
5203  
5204 /**
5205  * @class Roo.DatePicker
5206  * @extends Roo.Component
5207  * Simple date picker class.
5208  * @constructor
5209  * Create a new DatePicker
5210  * @param {Object} config The config object
5211  */
5212 Roo.DatePicker = function(config){
5213     Roo.DatePicker.superclass.constructor.call(this, config);
5214
5215     this.value = config && config.value ?
5216                  config.value.clearTime() : new Date().clearTime();
5217
5218     this.addEvents({
5219         /**
5220              * @event select
5221              * Fires when a date is selected
5222              * @param {DatePicker} this
5223              * @param {Date} date The selected date
5224              */
5225         'select': true,
5226         /**
5227              * @event monthchange
5228              * Fires when the displayed month changes 
5229              * @param {DatePicker} this
5230              * @param {Date} date The selected month
5231              */
5232         'monthchange': true
5233     });
5234
5235     if(this.handler){
5236         this.on("select", this.handler,  this.scope || this);
5237     }
5238     // build the disabledDatesRE
5239     if(!this.disabledDatesRE && this.disabledDates){
5240         var dd = this.disabledDates;
5241         var re = "(?:";
5242         for(var i = 0; i < dd.length; i++){
5243             re += dd[i];
5244             if(i != dd.length-1) {
5245                 re += "|";
5246             }
5247         }
5248         this.disabledDatesRE = new RegExp(re + ")");
5249     }
5250 };
5251
5252 Roo.extend(Roo.DatePicker, Roo.Component, {
5253     /**
5254      * @cfg {String} todayText
5255      * The text to display on the button that selects the current date (defaults to "Today")
5256      */
5257     todayText : "Today",
5258     /**
5259      * @cfg {String} okText
5260      * The text to display on the ok button
5261      */
5262     okText : "&#160;OK&#160;", // &#160; to give the user extra clicking room
5263     /**
5264      * @cfg {String} cancelText
5265      * The text to display on the cancel button
5266      */
5267     cancelText : "Cancel",
5268     /**
5269      * @cfg {String} todayTip
5270      * The tooltip to display for the button that selects the current date (defaults to "{current date} (Spacebar)")
5271      */
5272     todayTip : "{0} (Spacebar)",
5273     /**
5274      * @cfg {Date} minDate
5275      * Minimum allowable date (JavaScript date object, defaults to null)
5276      */
5277     minDate : null,
5278     /**
5279      * @cfg {Date} maxDate
5280      * Maximum allowable date (JavaScript date object, defaults to null)
5281      */
5282     maxDate : null,
5283     /**
5284      * @cfg {String} minText
5285      * The error text to display if the minDate validation fails (defaults to "This date is before the minimum date")
5286      */
5287     minText : "This date is before the minimum date",
5288     /**
5289      * @cfg {String} maxText
5290      * The error text to display if the maxDate validation fails (defaults to "This date is after the maximum date")
5291      */
5292     maxText : "This date is after the maximum date",
5293     /**
5294      * @cfg {String} format
5295      * The default date format string which can be overriden for localization support.  The format must be
5296      * valid according to {@link Date#parseDate} (defaults to 'm/d/y').
5297      */
5298     format : "m/d/y",
5299     /**
5300      * @cfg {Array} disabledDays
5301      * An array of days to disable, 0-based. For example, [0, 6] disables Sunday and Saturday (defaults to null).
5302      */
5303     disabledDays : null,
5304     /**
5305      * @cfg {String} disabledDaysText
5306      * The tooltip to display when the date falls on a disabled day (defaults to "")
5307      */
5308     disabledDaysText : "",
5309     /**
5310      * @cfg {RegExp} disabledDatesRE
5311      * JavaScript regular expression used to disable a pattern of dates (defaults to null)
5312      */
5313     disabledDatesRE : null,
5314     /**
5315      * @cfg {String} disabledDatesText
5316      * The tooltip text to display when the date falls on a disabled date (defaults to "")
5317      */
5318     disabledDatesText : "",
5319     /**
5320      * @cfg {Boolean} constrainToViewport
5321      * True to constrain the date picker to the viewport (defaults to true)
5322      */
5323     constrainToViewport : true,
5324     /**
5325      * @cfg {Array} monthNames
5326      * An array of textual month names which can be overriden for localization support (defaults to Date.monthNames)
5327      */
5328     monthNames : Date.monthNames,
5329     /**
5330      * @cfg {Array} dayNames
5331      * An array of textual day names which can be overriden for localization support (defaults to Date.dayNames)
5332      */
5333     dayNames : Date.dayNames,
5334     /**
5335      * @cfg {String} nextText
5336      * The next month navigation button tooltip (defaults to 'Next Month (Control+Right)')
5337      */
5338     nextText: 'Next Month (Control+Right)',
5339     /**
5340      * @cfg {String} prevText
5341      * The previous month navigation button tooltip (defaults to 'Previous Month (Control+Left)')
5342      */
5343     prevText: 'Previous Month (Control+Left)',
5344     /**
5345      * @cfg {String} monthYearText
5346      * The header month selector tooltip (defaults to 'Choose a month (Control+Up/Down to move years)')
5347      */
5348     monthYearText: 'Choose a month (Control+Up/Down to move years)',
5349     /**
5350      * @cfg {Number} startDay
5351      * Day index at which the week should begin, 0-based (defaults to 0, which is Sunday)
5352      */
5353     startDay : 0,
5354     /**
5355      * @cfg {Bool} showClear
5356      * Show a clear button (usefull for date form elements that can be blank.)
5357      */
5358     
5359     showClear: false,
5360     
5361     /**
5362      * Sets the value of the date field
5363      * @param {Date} value The date to set
5364      */
5365     setValue : function(value){
5366         var old = this.value;
5367         
5368         if (typeof(value) == 'string') {
5369          
5370             value = Date.parseDate(value, this.format);
5371         }
5372         if (!value) {
5373             value = new Date();
5374         }
5375         
5376         this.value = value.clearTime(true);
5377         if(this.el){
5378             this.update(this.value);
5379         }
5380     },
5381
5382     /**
5383      * Gets the current selected value of the date field
5384      * @return {Date} The selected date
5385      */
5386     getValue : function(){
5387         return this.value;
5388     },
5389
5390     // private
5391     focus : function(){
5392         if(this.el){
5393             this.update(this.activeDate);
5394         }
5395     },
5396
5397     // privateval
5398     onRender : function(container, position){
5399         
5400         var m = [
5401              '<table cellspacing="0">',
5402                 '<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>',
5403                 '<tr><td colspan="3"><table class="x-date-inner" cellspacing="0"><thead><tr>'];
5404         var dn = this.dayNames;
5405         for(var i = 0; i < 7; i++){
5406             var d = this.startDay+i;
5407             if(d > 6){
5408                 d = d-7;
5409             }
5410             m.push("<th><span>", dn[d].substr(0,1), "</span></th>");
5411         }
5412         m[m.length] = "</tr></thead><tbody><tr>";
5413         for(var i = 0; i < 42; i++) {
5414             if(i % 7 == 0 && i != 0){
5415                 m[m.length] = "</tr><tr>";
5416             }
5417             m[m.length] = '<td><a href="#" hidefocus="on" class="x-date-date" tabIndex="1"><em><span></span></em></a></td>';
5418         }
5419         m[m.length] = '</tr></tbody></table></td></tr><tr>'+
5420             '<td colspan="3" class="x-date-bottom" align="center"></td></tr></table><div class="x-date-mp"></div>';
5421
5422         var el = document.createElement("div");
5423         el.className = "x-date-picker";
5424         el.innerHTML = m.join("");
5425
5426         container.dom.insertBefore(el, position);
5427
5428         this.el = Roo.get(el);
5429         this.eventEl = Roo.get(el.firstChild);
5430
5431         new Roo.util.ClickRepeater(this.el.child("td.x-date-left a"), {
5432             handler: this.showPrevMonth,
5433             scope: this,
5434             preventDefault:true,
5435             stopDefault:true
5436         });
5437
5438         new Roo.util.ClickRepeater(this.el.child("td.x-date-right a"), {
5439             handler: this.showNextMonth,
5440             scope: this,
5441             preventDefault:true,
5442             stopDefault:true
5443         });
5444
5445         this.eventEl.on("mousewheel", this.handleMouseWheel,  this);
5446
5447         this.monthPicker = this.el.down('div.x-date-mp');
5448         this.monthPicker.enableDisplayMode('block');
5449         
5450         var kn = new Roo.KeyNav(this.eventEl, {
5451             "left" : function(e){
5452                 e.ctrlKey ?
5453                     this.showPrevMonth() :
5454                     this.update(this.activeDate.add("d", -1));
5455             },
5456
5457             "right" : function(e){
5458                 e.ctrlKey ?
5459                     this.showNextMonth() :
5460                     this.update(this.activeDate.add("d", 1));
5461             },
5462
5463             "up" : function(e){
5464                 e.ctrlKey ?
5465                     this.showNextYear() :
5466                     this.update(this.activeDate.add("d", -7));
5467             },
5468
5469             "down" : function(e){
5470                 e.ctrlKey ?
5471                     this.showPrevYear() :
5472                     this.update(this.activeDate.add("d", 7));
5473             },
5474
5475             "pageUp" : function(e){
5476                 this.showNextMonth();
5477             },
5478
5479             "pageDown" : function(e){
5480                 this.showPrevMonth();
5481             },
5482
5483             "enter" : function(e){
5484                 e.stopPropagation();
5485                 return true;
5486             },
5487
5488             scope : this
5489         });
5490
5491         this.eventEl.on("click", this.handleDateClick,  this, {delegate: "a.x-date-date"});
5492
5493         this.eventEl.addKeyListener(Roo.EventObject.SPACE, this.selectToday,  this);
5494
5495         this.el.unselectable();
5496         
5497         this.cells = this.el.select("table.x-date-inner tbody td");
5498         this.textNodes = this.el.query("table.x-date-inner tbody span");
5499
5500         this.mbtn = new Roo.Button(this.el.child("td.x-date-middle", true), {
5501             text: "&#160;",
5502             tooltip: this.monthYearText
5503         });
5504
5505         this.mbtn.on('click', this.showMonthPicker, this);
5506         this.mbtn.el.child(this.mbtn.menuClassTarget).addClass("x-btn-with-menu");
5507
5508
5509         var today = (new Date()).dateFormat(this.format);
5510         
5511         var baseTb = new Roo.Toolbar(this.el.child("td.x-date-bottom", true));
5512         if (this.showClear) {
5513             baseTb.add( new Roo.Toolbar.Fill());
5514         }
5515         baseTb.add({
5516             text: String.format(this.todayText, today),
5517             tooltip: String.format(this.todayTip, today),
5518             handler: this.selectToday,
5519             scope: this
5520         });
5521         
5522         //var todayBtn = new Roo.Button(this.el.child("td.x-date-bottom", true), {
5523             
5524         //});
5525         if (this.showClear) {
5526             
5527             baseTb.add( new Roo.Toolbar.Fill());
5528             baseTb.add({
5529                 text: '&#160;',
5530                 cls: 'x-btn-icon x-btn-clear',
5531                 handler: function() {
5532                     //this.value = '';
5533                     this.fireEvent("select", this, '');
5534                 },
5535                 scope: this
5536             });
5537         }
5538         
5539         
5540         if(Roo.isIE){
5541             this.el.repaint();
5542         }
5543         this.update(this.value);
5544     },
5545
5546     createMonthPicker : function(){
5547         if(!this.monthPicker.dom.firstChild){
5548             var buf = ['<table border="0" cellspacing="0">'];
5549             for(var i = 0; i < 6; i++){
5550                 buf.push(
5551                     '<tr><td class="x-date-mp-month"><a href="#">', this.monthNames[i].substr(0, 3), '</a></td>',
5552                     '<td class="x-date-mp-month x-date-mp-sep"><a href="#">', this.monthNames[i+6].substr(0, 3), '</a></td>',
5553                     i == 0 ?
5554                     '<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>' :
5555                     '<td class="x-date-mp-year"><a href="#"></a></td><td class="x-date-mp-year"><a href="#"></a></td></tr>'
5556                 );
5557             }
5558             buf.push(
5559                 '<tr class="x-date-mp-btns"><td colspan="4"><button type="button" class="x-date-mp-ok">',
5560                     this.okText,
5561                     '</button><button type="button" class="x-date-mp-cancel">',
5562                     this.cancelText,
5563                     '</button></td></tr>',
5564                 '</table>'
5565             );
5566             this.monthPicker.update(buf.join(''));
5567             this.monthPicker.on('click', this.onMonthClick, this);
5568             this.monthPicker.on('dblclick', this.onMonthDblClick, this);
5569
5570             this.mpMonths = this.monthPicker.select('td.x-date-mp-month');
5571             this.mpYears = this.monthPicker.select('td.x-date-mp-year');
5572
5573             this.mpMonths.each(function(m, a, i){
5574                 i += 1;
5575                 if((i%2) == 0){
5576                     m.dom.xmonth = 5 + Math.round(i * .5);
5577                 }else{
5578                     m.dom.xmonth = Math.round((i-1) * .5);
5579                 }
5580             });
5581         }
5582     },
5583
5584     showMonthPicker : function(){
5585         this.createMonthPicker();
5586         var size = this.el.getSize();
5587         this.monthPicker.setSize(size);
5588         this.monthPicker.child('table').setSize(size);
5589
5590         this.mpSelMonth = (this.activeDate || this.value).getMonth();
5591         this.updateMPMonth(this.mpSelMonth);
5592         this.mpSelYear = (this.activeDate || this.value).getFullYear();
5593         this.updateMPYear(this.mpSelYear);
5594
5595         this.monthPicker.slideIn('t', {duration:.2});
5596     },
5597
5598     updateMPYear : function(y){
5599         this.mpyear = y;
5600         var ys = this.mpYears.elements;
5601         for(var i = 1; i <= 10; i++){
5602             var td = ys[i-1], y2;
5603             if((i%2) == 0){
5604                 y2 = y + Math.round(i * .5);
5605                 td.firstChild.innerHTML = y2;
5606                 td.xyear = y2;
5607             }else{
5608                 y2 = y - (5-Math.round(i * .5));
5609                 td.firstChild.innerHTML = y2;
5610                 td.xyear = y2;
5611             }
5612             this.mpYears.item(i-1)[y2 == this.mpSelYear ? 'addClass' : 'removeClass']('x-date-mp-sel');
5613         }
5614     },
5615
5616     updateMPMonth : function(sm){
5617         this.mpMonths.each(function(m, a, i){
5618             m[m.dom.xmonth == sm ? 'addClass' : 'removeClass']('x-date-mp-sel');
5619         });
5620     },
5621
5622     selectMPMonth: function(m){
5623         
5624     },
5625
5626     onMonthClick : function(e, t){
5627         e.stopEvent();
5628         var el = new Roo.Element(t), pn;
5629         if(el.is('button.x-date-mp-cancel')){
5630             this.hideMonthPicker();
5631         }
5632         else if(el.is('button.x-date-mp-ok')){
5633             this.update(new Date(this.mpSelYear, this.mpSelMonth, (this.activeDate || this.value).getDate()));
5634             this.hideMonthPicker();
5635         }
5636         else if(pn = el.up('td.x-date-mp-month', 2)){
5637             this.mpMonths.removeClass('x-date-mp-sel');
5638             pn.addClass('x-date-mp-sel');
5639             this.mpSelMonth = pn.dom.xmonth;
5640         }
5641         else if(pn = el.up('td.x-date-mp-year', 2)){
5642             this.mpYears.removeClass('x-date-mp-sel');
5643             pn.addClass('x-date-mp-sel');
5644             this.mpSelYear = pn.dom.xyear;
5645         }
5646         else if(el.is('a.x-date-mp-prev')){
5647             this.updateMPYear(this.mpyear-10);
5648         }
5649         else if(el.is('a.x-date-mp-next')){
5650             this.updateMPYear(this.mpyear+10);
5651         }
5652     },
5653
5654     onMonthDblClick : function(e, t){
5655         e.stopEvent();
5656         var el = new Roo.Element(t), pn;
5657         if(pn = el.up('td.x-date-mp-month', 2)){
5658             this.update(new Date(this.mpSelYear, pn.dom.xmonth, (this.activeDate || this.value).getDate()));
5659             this.hideMonthPicker();
5660         }
5661         else if(pn = el.up('td.x-date-mp-year', 2)){
5662             this.update(new Date(pn.dom.xyear, this.mpSelMonth, (this.activeDate || this.value).getDate()));
5663             this.hideMonthPicker();
5664         }
5665     },
5666
5667     hideMonthPicker : function(disableAnim){
5668         if(this.monthPicker){
5669             if(disableAnim === true){
5670                 this.monthPicker.hide();
5671             }else{
5672                 this.monthPicker.slideOut('t', {duration:.2});
5673             }
5674         }
5675     },
5676
5677     // private
5678     showPrevMonth : function(e){
5679         this.update(this.activeDate.add("mo", -1));
5680     },
5681
5682     // private
5683     showNextMonth : function(e){
5684         this.update(this.activeDate.add("mo", 1));
5685     },
5686
5687     // private
5688     showPrevYear : function(){
5689         this.update(this.activeDate.add("y", -1));
5690     },
5691
5692     // private
5693     showNextYear : function(){
5694         this.update(this.activeDate.add("y", 1));
5695     },
5696
5697     // private
5698     handleMouseWheel : function(e){
5699         var delta = e.getWheelDelta();
5700         if(delta > 0){
5701             this.showPrevMonth();
5702             e.stopEvent();
5703         } else if(delta < 0){
5704             this.showNextMonth();
5705             e.stopEvent();
5706         }
5707     },
5708
5709     // private
5710     handleDateClick : function(e, t){
5711         e.stopEvent();
5712         if(t.dateValue && !Roo.fly(t.parentNode).hasClass("x-date-disabled")){
5713             this.setValue(new Date(t.dateValue));
5714             this.fireEvent("select", this, this.value);
5715         }
5716     },
5717
5718     // private
5719     selectToday : function(){
5720         this.setValue(new Date().clearTime());
5721         this.fireEvent("select", this, this.value);
5722     },
5723
5724     // private
5725     update : function(date)
5726     {
5727         var vd = this.activeDate;
5728         this.activeDate = date;
5729         if(vd && this.el){
5730             var t = date.getTime();
5731             if(vd.getMonth() == date.getMonth() && vd.getFullYear() == date.getFullYear()){
5732                 this.cells.removeClass("x-date-selected");
5733                 this.cells.each(function(c){
5734                    if(c.dom.firstChild.dateValue == t){
5735                        c.addClass("x-date-selected");
5736                        setTimeout(function(){
5737                             try{c.dom.firstChild.focus();}catch(e){}
5738                        }, 50);
5739                        return false;
5740                    }
5741                 });
5742                 return;
5743             }
5744         }
5745         
5746         var days = date.getDaysInMonth();
5747         var firstOfMonth = date.getFirstDateOfMonth();
5748         var startingPos = firstOfMonth.getDay()-this.startDay;
5749
5750         if(startingPos <= this.startDay){
5751             startingPos += 7;
5752         }
5753
5754         var pm = date.add("mo", -1);
5755         var prevStart = pm.getDaysInMonth()-startingPos;
5756
5757         var cells = this.cells.elements;
5758         var textEls = this.textNodes;
5759         days += startingPos;
5760
5761         // convert everything to numbers so it's fast
5762         var day = 86400000;
5763         var d = (new Date(pm.getFullYear(), pm.getMonth(), prevStart)).clearTime();
5764         var today = new Date().clearTime().getTime();
5765         var sel = date.clearTime().getTime();
5766         var min = this.minDate ? this.minDate.clearTime() : Number.NEGATIVE_INFINITY;
5767         var max = this.maxDate ? this.maxDate.clearTime() : Number.POSITIVE_INFINITY;
5768         var ddMatch = this.disabledDatesRE;
5769         var ddText = this.disabledDatesText;
5770         var ddays = this.disabledDays ? this.disabledDays.join("") : false;
5771         var ddaysText = this.disabledDaysText;
5772         var format = this.format;
5773
5774         var setCellClass = function(cal, cell){
5775             cell.title = "";
5776             var t = d.getTime();
5777             cell.firstChild.dateValue = t;
5778             if(t == today){
5779                 cell.className += " x-date-today";
5780                 cell.title = cal.todayText;
5781             }
5782             if(t == sel){
5783                 cell.className += " x-date-selected";
5784                 setTimeout(function(){
5785                     try{cell.firstChild.focus();}catch(e){}
5786                 }, 50);
5787             }
5788             // disabling
5789             if(t < min) {
5790                 cell.className = " x-date-disabled";
5791                 cell.title = cal.minText;
5792                 return;
5793             }
5794             if(t > max) {
5795                 cell.className = " x-date-disabled";
5796                 cell.title = cal.maxText;
5797                 return;
5798             }
5799             if(ddays){
5800                 if(ddays.indexOf(d.getDay()) != -1){
5801                     cell.title = ddaysText;
5802                     cell.className = " x-date-disabled";
5803                 }
5804             }
5805             if(ddMatch && format){
5806                 var fvalue = d.dateFormat(format);
5807                 if(ddMatch.test(fvalue)){
5808                     cell.title = ddText.replace("%0", fvalue);
5809                     cell.className = " x-date-disabled";
5810                 }
5811             }
5812         };
5813
5814         var i = 0;
5815         for(; i < startingPos; i++) {
5816             textEls[i].innerHTML = (++prevStart);
5817             d.setDate(d.getDate()+1);
5818             cells[i].className = "x-date-prevday";
5819             setCellClass(this, cells[i]);
5820         }
5821         for(; i < days; i++){
5822             intDay = i - startingPos + 1;
5823             textEls[i].innerHTML = (intDay);
5824             d.setDate(d.getDate()+1);
5825             cells[i].className = "x-date-active";
5826             setCellClass(this, cells[i]);
5827         }
5828         var extraDays = 0;
5829         for(; i < 42; i++) {
5830              textEls[i].innerHTML = (++extraDays);
5831              d.setDate(d.getDate()+1);
5832              cells[i].className = "x-date-nextday";
5833              setCellClass(this, cells[i]);
5834         }
5835
5836         this.mbtn.setText(this.monthNames[date.getMonth()] + " " + date.getFullYear());
5837         this.fireEvent('monthchange', this, date);
5838         
5839         if(!this.internalRender){
5840             var main = this.el.dom.firstChild;
5841             var w = main.offsetWidth;
5842             this.el.setWidth(w + this.el.getBorderWidth("lr"));
5843             Roo.fly(main).setWidth(w);
5844             this.internalRender = true;
5845             // opera does not respect the auto grow header center column
5846             // then, after it gets a width opera refuses to recalculate
5847             // without a second pass
5848             if(Roo.isOpera && !this.secondPass){
5849                 main.rows[0].cells[1].style.width = (w - (main.rows[0].cells[0].offsetWidth+main.rows[0].cells[2].offsetWidth)) + "px";
5850                 this.secondPass = true;
5851                 this.update.defer(10, this, [date]);
5852             }
5853         }
5854         
5855         
5856     }
5857 });        /*
5858  * Based on:
5859  * Ext JS Library 1.1.1
5860  * Copyright(c) 2006-2007, Ext JS, LLC.
5861  *
5862  * Originally Released Under LGPL - original licence link has changed is not relivant.
5863  *
5864  * Fork - LGPL
5865  * <script type="text/javascript">
5866  */
5867 /**
5868  * @class Roo.TabPanel
5869  * @extends Roo.util.Observable
5870  * A lightweight tab container.
5871  * <br><br>
5872  * Usage:
5873  * <pre><code>
5874 // basic tabs 1, built from existing content
5875 var tabs = new Roo.TabPanel("tabs1");
5876 tabs.addTab("script", "View Script");
5877 tabs.addTab("markup", "View Markup");
5878 tabs.activate("script");
5879
5880 // more advanced tabs, built from javascript
5881 var jtabs = new Roo.TabPanel("jtabs");
5882 jtabs.addTab("jtabs-1", "Normal Tab", "My content was added during construction.");
5883
5884 // set up the UpdateManager
5885 var tab2 = jtabs.addTab("jtabs-2", "Ajax Tab 1");
5886 var updater = tab2.getUpdateManager();
5887 updater.setDefaultUrl("ajax1.htm");
5888 tab2.on('activate', updater.refresh, updater, true);
5889
5890 // Use setUrl for Ajax loading
5891 var tab3 = jtabs.addTab("jtabs-3", "Ajax Tab 2");
5892 tab3.setUrl("ajax2.htm", null, true);
5893
5894 // Disabled tab
5895 var tab4 = jtabs.addTab("tabs1-5", "Disabled Tab", "Can't see me cause I'm disabled");
5896 tab4.disable();
5897
5898 jtabs.activate("jtabs-1");
5899  * </code></pre>
5900  * @constructor
5901  * Create a new TabPanel.
5902  * @param {String/HTMLElement/Roo.Element} container The id, DOM element or Roo.Element container where this TabPanel is to be rendered.
5903  * @param {Object/Boolean} config Config object to set any properties for this TabPanel, or true to render the tabs on the bottom.
5904  */
5905 Roo.TabPanel = function(container, config){
5906     /**
5907     * The container element for this TabPanel.
5908     * @type Roo.Element
5909     */
5910     this.el = Roo.get(container, true);
5911     if(config){
5912         if(typeof config == "boolean"){
5913             this.tabPosition = config ? "bottom" : "top";
5914         }else{
5915             Roo.apply(this, config);
5916         }
5917     }
5918     if(this.tabPosition == "bottom"){
5919         this.bodyEl = Roo.get(this.createBody(this.el.dom));
5920         this.el.addClass("x-tabs-bottom");
5921     }
5922     this.stripWrap = Roo.get(this.createStrip(this.el.dom), true);
5923     this.stripEl = Roo.get(this.createStripList(this.stripWrap.dom), true);
5924     this.stripBody = Roo.get(this.stripWrap.dom.firstChild.firstChild, true);
5925     if(Roo.isIE){
5926         Roo.fly(this.stripWrap.dom.firstChild).setStyle("overflow-x", "hidden");
5927     }
5928     if(this.tabPosition != "bottom"){
5929         /** The body element that contains {@link Roo.TabPanelItem} bodies. +
5930          * @type Roo.Element
5931          */
5932         this.bodyEl = Roo.get(this.createBody(this.el.dom));
5933         this.el.addClass("x-tabs-top");
5934     }
5935     this.items = [];
5936
5937     this.bodyEl.setStyle("position", "relative");
5938
5939     this.active = null;
5940     this.activateDelegate = this.activate.createDelegate(this);
5941
5942     this.addEvents({
5943         /**
5944          * @event tabchange
5945          * Fires when the active tab changes
5946          * @param {Roo.TabPanel} this
5947          * @param {Roo.TabPanelItem} activePanel The new active tab
5948          */
5949         "tabchange": true,
5950         /**
5951          * @event beforetabchange
5952          * Fires before the active tab changes, set cancel to true on the "e" parameter to cancel the change
5953          * @param {Roo.TabPanel} this
5954          * @param {Object} e Set cancel to true on this object to cancel the tab change
5955          * @param {Roo.TabPanelItem} tab The tab being changed to
5956          */
5957         "beforetabchange" : true
5958     });
5959
5960     Roo.EventManager.onWindowResize(this.onResize, this);
5961     this.cpad = this.el.getPadding("lr");
5962     this.hiddenCount = 0;
5963
5964
5965     // toolbar on the tabbar support...
5966     if (this.toolbar) {
5967         var tcfg = this.toolbar;
5968         tcfg.container = this.stripEl.child('td.x-tab-strip-toolbar');  
5969         this.toolbar = new Roo.Toolbar(tcfg);
5970         if (Roo.isSafari) {
5971             var tbl = tcfg.container.child('table', true);
5972             tbl.setAttribute('width', '100%');
5973         }
5974         
5975     }
5976    
5977
5978
5979     Roo.TabPanel.superclass.constructor.call(this);
5980 };
5981
5982 Roo.extend(Roo.TabPanel, Roo.util.Observable, {
5983     /*
5984      *@cfg {String} tabPosition "top" or "bottom" (defaults to "top")
5985      */
5986     tabPosition : "top",
5987     /*
5988      *@cfg {Number} currentTabWidth The width of the current tab (defaults to 0)
5989      */
5990     currentTabWidth : 0,
5991     /*
5992      *@cfg {Number} minTabWidth The minimum width of a tab (defaults to 40) (ignored if {@link #resizeTabs} is not true)
5993      */
5994     minTabWidth : 40,
5995     /*
5996      *@cfg {Number} maxTabWidth The maximum width of a tab (defaults to 250) (ignored if {@link #resizeTabs} is not true)
5997      */
5998     maxTabWidth : 250,
5999     /*
6000      *@cfg {Number} preferredTabWidth The preferred (default) width of a tab (defaults to 175) (ignored if {@link #resizeTabs} is not true)
6001      */
6002     preferredTabWidth : 175,
6003     /*
6004      *@cfg {Boolean} resizeTabs True to enable dynamic tab resizing (defaults to false)
6005      */
6006     resizeTabs : false,
6007     /*
6008      *@cfg {Boolean} monitorResize Set this to true to turn on window resize monitoring (ignored if {@link #resizeTabs} is not true) (defaults to true)
6009      */
6010     monitorResize : true,
6011     /*
6012      *@cfg {Object} toolbar xtype description of toolbar to show at the right of the tab bar. 
6013      */
6014     toolbar : false,
6015
6016     /**
6017      * Creates a new {@link Roo.TabPanelItem} by looking for an existing element with the provided id -- if it's not found it creates one.
6018      * @param {String} id The id of the div to use <b>or create</b>
6019      * @param {String} text The text for the tab
6020      * @param {String} content (optional) Content to put in the TabPanelItem body
6021      * @param {Boolean} closable (optional) True to create a close icon on the tab
6022      * @return {Roo.TabPanelItem} The created TabPanelItem
6023      */
6024     addTab : function(id, text, content, closable){
6025         var item = new Roo.TabPanelItem(this, id, text, closable);
6026         this.addTabItem(item);
6027         if(content){
6028             item.setContent(content);
6029         }
6030         return item;
6031     },
6032
6033     /**
6034      * Returns the {@link Roo.TabPanelItem} with the specified id/index
6035      * @param {String/Number} id The id or index of the TabPanelItem to fetch.
6036      * @return {Roo.TabPanelItem}
6037      */
6038     getTab : function(id){
6039         return this.items[id];
6040     },
6041
6042     /**
6043      * Hides the {@link Roo.TabPanelItem} with the specified id/index
6044      * @param {String/Number} id The id or index of the TabPanelItem to hide.
6045      */
6046     hideTab : function(id){
6047         var t = this.items[id];
6048         if(!t.isHidden()){
6049            t.setHidden(true);
6050            this.hiddenCount++;
6051            this.autoSizeTabs();
6052         }
6053     },
6054
6055     /**
6056      * "Unhides" the {@link Roo.TabPanelItem} with the specified id/index.
6057      * @param {String/Number} id The id or index of the TabPanelItem to unhide.
6058      */
6059     unhideTab : function(id){
6060         var t = this.items[id];
6061         if(t.isHidden()){
6062            t.setHidden(false);
6063            this.hiddenCount--;
6064            this.autoSizeTabs();
6065         }
6066     },
6067
6068     /**
6069      * Adds an existing {@link Roo.TabPanelItem}.
6070      * @param {Roo.TabPanelItem} item The TabPanelItem to add
6071      */
6072     addTabItem : function(item){
6073         this.items[item.id] = item;
6074         this.items.push(item);
6075         if(this.resizeTabs){
6076            item.setWidth(this.currentTabWidth || this.preferredTabWidth);
6077            this.autoSizeTabs();
6078         }else{
6079             item.autoSize();
6080         }
6081     },
6082
6083     /**
6084      * Removes a {@link Roo.TabPanelItem}.
6085      * @param {String/Number} id The id or index of the TabPanelItem to remove.
6086      */
6087     removeTab : function(id){
6088         var items = this.items;
6089         var tab = items[id];
6090         if(!tab) { return; }
6091         var index = items.indexOf(tab);
6092         if(this.active == tab && items.length > 1){
6093             var newTab = this.getNextAvailable(index);
6094             if(newTab) {
6095                 newTab.activate();
6096             }
6097         }
6098         this.stripEl.dom.removeChild(tab.pnode.dom);
6099         if(tab.bodyEl.dom.parentNode == this.bodyEl.dom){ // if it was moved already prevent error
6100             this.bodyEl.dom.removeChild(tab.bodyEl.dom);
6101         }
6102         items.splice(index, 1);
6103         delete this.items[tab.id];
6104         tab.fireEvent("close", tab);
6105         tab.purgeListeners();
6106         this.autoSizeTabs();
6107     },
6108
6109     getNextAvailable : function(start){
6110         var items = this.items;
6111         var index = start;
6112         // look for a next tab that will slide over to
6113         // replace the one being removed
6114         while(index < items.length){
6115             var item = items[++index];
6116             if(item && !item.isHidden()){
6117                 return item;
6118             }
6119         }
6120         // if one isn't found select the previous tab (on the left)
6121         index = start;
6122         while(index >= 0){
6123             var item = items[--index];
6124             if(item && !item.isHidden()){
6125                 return item;
6126             }
6127         }
6128         return null;
6129     },
6130
6131     /**
6132      * Disables a {@link Roo.TabPanelItem}. It cannot be the active tab, if it is this call is ignored.
6133      * @param {String/Number} id The id or index of the TabPanelItem to disable.
6134      */
6135     disableTab : function(id){
6136         var tab = this.items[id];
6137         if(tab && this.active != tab){
6138             tab.disable();
6139         }
6140     },
6141
6142     /**
6143      * Enables a {@link Roo.TabPanelItem} that is disabled.
6144      * @param {String/Number} id The id or index of the TabPanelItem to enable.
6145      */
6146     enableTab : function(id){
6147         var tab = this.items[id];
6148         tab.enable();
6149     },
6150
6151     /**
6152      * Activates a {@link Roo.TabPanelItem}. The currently active one will be deactivated.
6153      * @param {String/Number} id The id or index of the TabPanelItem to activate.
6154      * @return {Roo.TabPanelItem} The TabPanelItem.
6155      */
6156     activate : function(id){
6157         var tab = this.items[id];
6158         if(!tab){
6159             return null;
6160         }
6161         if(tab == this.active || tab.disabled){
6162             return tab;
6163         }
6164         var e = {};
6165         this.fireEvent("beforetabchange", this, e, tab);
6166         if(e.cancel !== true && !tab.disabled){
6167             if(this.active){
6168                 this.active.hide();
6169             }
6170             this.active = this.items[id];
6171             this.active.show();
6172             this.fireEvent("tabchange", this, this.active);
6173         }
6174         return tab;
6175     },
6176
6177     /**
6178      * Gets the active {@link Roo.TabPanelItem}.
6179      * @return {Roo.TabPanelItem} The active TabPanelItem or null if none are active.
6180      */
6181     getActiveTab : function(){
6182         return this.active;
6183     },
6184
6185     /**
6186      * Updates the tab body element to fit the height of the container element
6187      * for overflow scrolling
6188      * @param {Number} targetHeight (optional) Override the starting height from the elements height
6189      */
6190     syncHeight : function(targetHeight){
6191         var height = (targetHeight || this.el.getHeight())-this.el.getBorderWidth("tb")-this.el.getPadding("tb");
6192         var bm = this.bodyEl.getMargins();
6193         var newHeight = height-(this.stripWrap.getHeight()||0)-(bm.top+bm.bottom);
6194         this.bodyEl.setHeight(newHeight);
6195         return newHeight;
6196     },
6197
6198     onResize : function(){
6199         if(this.monitorResize){
6200             this.autoSizeTabs();
6201         }
6202     },
6203
6204     /**
6205      * Disables tab resizing while tabs are being added (if {@link #resizeTabs} is false this does nothing)
6206      */
6207     beginUpdate : function(){
6208         this.updating = true;
6209     },
6210
6211     /**
6212      * Stops an update and resizes the tabs (if {@link #resizeTabs} is false this does nothing)
6213      */
6214     endUpdate : function(){
6215         this.updating = false;
6216         this.autoSizeTabs();
6217     },
6218
6219     /**
6220      * Manual call to resize the tabs (if {@link #resizeTabs} is false this does nothing)
6221      */
6222     autoSizeTabs : function(){
6223         var count = this.items.length;
6224         var vcount = count - this.hiddenCount;
6225         if(!this.resizeTabs || count < 1 || vcount < 1 || this.updating) {
6226             return;
6227         }
6228         var w = Math.max(this.el.getWidth() - this.cpad, 10);
6229         var availWidth = Math.floor(w / vcount);
6230         var b = this.stripBody;
6231         if(b.getWidth() > w){
6232             var tabs = this.items;
6233             this.setTabWidth(Math.max(availWidth, this.minTabWidth)-2);
6234             if(availWidth < this.minTabWidth){
6235                 /*if(!this.sleft){    // incomplete scrolling code
6236                     this.createScrollButtons();
6237                 }
6238                 this.showScroll();
6239                 this.stripClip.setWidth(w - (this.sleft.getWidth()+this.sright.getWidth()));*/
6240             }
6241         }else{
6242             if(this.currentTabWidth < this.preferredTabWidth){
6243                 this.setTabWidth(Math.min(availWidth, this.preferredTabWidth)-2);
6244             }
6245         }
6246     },
6247
6248     /**
6249      * Returns the number of tabs in this TabPanel.
6250      * @return {Number}
6251      */
6252      getCount : function(){
6253          return this.items.length;
6254      },
6255
6256     /**
6257      * Resizes all the tabs to the passed width
6258      * @param {Number} The new width
6259      */
6260     setTabWidth : function(width){
6261         this.currentTabWidth = width;
6262         for(var i = 0, len = this.items.length; i < len; i++) {
6263                 if(!this.items[i].isHidden()) {
6264                 this.items[i].setWidth(width);
6265             }
6266         }
6267     },
6268
6269     /**
6270      * Destroys this TabPanel
6271      * @param {Boolean} removeEl (optional) True to remove the element from the DOM as well (defaults to undefined)
6272      */
6273     destroy : function(removeEl){
6274         Roo.EventManager.removeResizeListener(this.onResize, this);
6275         for(var i = 0, len = this.items.length; i < len; i++){
6276             this.items[i].purgeListeners();
6277         }
6278         if(removeEl === true){
6279             this.el.update("");
6280             this.el.remove();
6281         }
6282     }
6283 });
6284
6285 /**
6286  * @class Roo.TabPanelItem
6287  * @extends Roo.util.Observable
6288  * Represents an individual item (tab plus body) in a TabPanel.
6289  * @param {Roo.TabPanel} tabPanel The {@link Roo.TabPanel} this TabPanelItem belongs to
6290  * @param {String} id The id of this TabPanelItem
6291  * @param {String} text The text for the tab of this TabPanelItem
6292  * @param {Boolean} closable True to allow this TabPanelItem to be closable (defaults to false)
6293  */
6294 Roo.TabPanelItem = function(tabPanel, id, text, closable){
6295     /**
6296      * The {@link Roo.TabPanel} this TabPanelItem belongs to
6297      * @type Roo.TabPanel
6298      */
6299     this.tabPanel = tabPanel;
6300     /**
6301      * The id for this TabPanelItem
6302      * @type String
6303      */
6304     this.id = id;
6305     /** @private */
6306     this.disabled = false;
6307     /** @private */
6308     this.text = text;
6309     /** @private */
6310     this.loaded = false;
6311     this.closable = closable;
6312
6313     /**
6314      * The body element for this TabPanelItem.
6315      * @type Roo.Element
6316      */
6317     this.bodyEl = Roo.get(tabPanel.createItemBody(tabPanel.bodyEl.dom, id));
6318     this.bodyEl.setVisibilityMode(Roo.Element.VISIBILITY);
6319     this.bodyEl.setStyle("display", "block");
6320     this.bodyEl.setStyle("zoom", "1");
6321     this.hideAction();
6322
6323     var els = tabPanel.createStripElements(tabPanel.stripEl.dom, text, closable);
6324     /** @private */
6325     this.el = Roo.get(els.el, true);
6326     this.inner = Roo.get(els.inner, true);
6327     this.textEl = Roo.get(this.el.dom.firstChild.firstChild.firstChild, true);
6328     this.pnode = Roo.get(els.el.parentNode, true);
6329     this.el.on("mousedown", this.onTabMouseDown, this);
6330     this.el.on("click", this.onTabClick, this);
6331     /** @private */
6332     if(closable){
6333         var c = Roo.get(els.close, true);
6334         c.dom.title = this.closeText;
6335         c.addClassOnOver("close-over");
6336         c.on("click", this.closeClick, this);
6337      }
6338
6339     this.addEvents({
6340          /**
6341          * @event activate
6342          * Fires when this tab becomes the active tab.
6343          * @param {Roo.TabPanel} tabPanel The parent TabPanel
6344          * @param {Roo.TabPanelItem} this
6345          */
6346         "activate": true,
6347         /**
6348          * @event beforeclose
6349          * Fires before this tab is closed. To cancel the close, set cancel to true on e (e.cancel = true).
6350          * @param {Roo.TabPanelItem} this
6351          * @param {Object} e Set cancel to true on this object to cancel the close.
6352          */
6353         "beforeclose": true,
6354         /**
6355          * @event close
6356          * Fires when this tab is closed.
6357          * @param {Roo.TabPanelItem} this
6358          */
6359          "close": true,
6360         /**
6361          * @event deactivate
6362          * Fires when this tab is no longer the active tab.
6363          * @param {Roo.TabPanel} tabPanel The parent TabPanel
6364          * @param {Roo.TabPanelItem} this
6365          */
6366          "deactivate" : true
6367     });
6368     this.hidden = false;
6369
6370     Roo.TabPanelItem.superclass.constructor.call(this);
6371 };
6372
6373 Roo.extend(Roo.TabPanelItem, Roo.util.Observable, {
6374     purgeListeners : function(){
6375        Roo.util.Observable.prototype.purgeListeners.call(this);
6376        this.el.removeAllListeners();
6377     },
6378     /**
6379      * Shows this TabPanelItem -- this <b>does not</b> deactivate the currently active TabPanelItem.
6380      */
6381     show : function(){
6382         this.pnode.addClass("on");
6383         this.showAction();
6384         if(Roo.isOpera){
6385             this.tabPanel.stripWrap.repaint();
6386         }
6387         this.fireEvent("activate", this.tabPanel, this);
6388     },
6389
6390     /**
6391      * Returns true if this tab is the active tab.
6392      * @return {Boolean}
6393      */
6394     isActive : function(){
6395         return this.tabPanel.getActiveTab() == this;
6396     },
6397
6398     /**
6399      * Hides this TabPanelItem -- if you don't activate another TabPanelItem this could look odd.
6400      */
6401     hide : function(){
6402         this.pnode.removeClass("on");
6403         this.hideAction();
6404         this.fireEvent("deactivate", this.tabPanel, this);
6405     },
6406
6407     hideAction : function(){
6408         this.bodyEl.hide();
6409         this.bodyEl.setStyle("position", "absolute");
6410         this.bodyEl.setLeft("-20000px");
6411         this.bodyEl.setTop("-20000px");
6412     },
6413
6414     showAction : function(){
6415         this.bodyEl.setStyle("position", "relative");
6416         this.bodyEl.setTop("");
6417         this.bodyEl.setLeft("");
6418         this.bodyEl.show();
6419     },
6420
6421     /**
6422      * Set the tooltip for the tab.
6423      * @param {String} tooltip The tab's tooltip
6424      */
6425     setTooltip : function(text){
6426         if(Roo.QuickTips && Roo.QuickTips.isEnabled()){
6427             this.textEl.dom.qtip = text;
6428             this.textEl.dom.removeAttribute('title');
6429         }else{
6430             this.textEl.dom.title = text;
6431         }
6432     },
6433
6434     onTabClick : function(e){
6435         e.preventDefault();
6436         this.tabPanel.activate(this.id);
6437     },
6438
6439     onTabMouseDown : function(e){
6440         e.preventDefault();
6441         this.tabPanel.activate(this.id);
6442     },
6443
6444     getWidth : function(){
6445         return this.inner.getWidth();
6446     },
6447
6448     setWidth : function(width){
6449         var iwidth = width - this.pnode.getPadding("lr");
6450         this.inner.setWidth(iwidth);
6451         this.textEl.setWidth(iwidth-this.inner.getPadding("lr"));
6452         this.pnode.setWidth(width);
6453     },
6454
6455     /**
6456      * Show or hide the tab
6457      * @param {Boolean} hidden True to hide or false to show.
6458      */
6459     setHidden : function(hidden){
6460         this.hidden = hidden;
6461         this.pnode.setStyle("display", hidden ? "none" : "");
6462     },
6463
6464     /**
6465      * Returns true if this tab is "hidden"
6466      * @return {Boolean}
6467      */
6468     isHidden : function(){
6469         return this.hidden;
6470     },
6471
6472     /**
6473      * Returns the text for this tab
6474      * @return {String}
6475      */
6476     getText : function(){
6477         return this.text;
6478     },
6479
6480     autoSize : function(){
6481         //this.el.beginMeasure();
6482         this.textEl.setWidth(1);
6483         /*
6484          *  #2804 [new] Tabs in Roojs
6485          *  increase the width by 2-4 pixels to prevent the ellipssis showing in chrome
6486          */
6487         this.setWidth(this.textEl.dom.scrollWidth+this.pnode.getPadding("lr")+this.inner.getPadding("lr") + 2);
6488         //this.el.endMeasure();
6489     },
6490
6491     /**
6492      * Sets the text for the tab (Note: this also sets the tooltip text)
6493      * @param {String} text The tab's text and tooltip
6494      */
6495     setText : function(text){
6496         this.text = text;
6497         this.textEl.update(text);
6498         this.setTooltip(text);
6499         if(!this.tabPanel.resizeTabs){
6500             this.autoSize();
6501         }
6502     },
6503     /**
6504      * Activates this TabPanelItem -- this <b>does</b> deactivate the currently active TabPanelItem.
6505      */
6506     activate : function(){
6507         this.tabPanel.activate(this.id);
6508     },
6509
6510     /**
6511      * Disables this TabPanelItem -- this does nothing if this is the active TabPanelItem.
6512      */
6513     disable : function(){
6514         if(this.tabPanel.active != this){
6515             this.disabled = true;
6516             this.pnode.addClass("disabled");
6517         }
6518     },
6519
6520     /**
6521      * Enables this TabPanelItem if it was previously disabled.
6522      */
6523     enable : function(){
6524         this.disabled = false;
6525         this.pnode.removeClass("disabled");
6526     },
6527
6528     /**
6529      * Sets the content for this TabPanelItem.
6530      * @param {String} content The content
6531      * @param {Boolean} loadScripts true to look for and load scripts
6532      */
6533     setContent : function(content, loadScripts){
6534         this.bodyEl.update(content, loadScripts);
6535     },
6536
6537     /**
6538      * Gets the {@link Roo.UpdateManager} for the body of this TabPanelItem. Enables you to perform Ajax updates.
6539      * @return {Roo.UpdateManager} The UpdateManager
6540      */
6541     getUpdateManager : function(){
6542         return this.bodyEl.getUpdateManager();
6543     },
6544
6545     /**
6546      * Set a URL to be used to load the content for this TabPanelItem.
6547      * @param {String/Function} url The URL to load the content from, or a function to call to get the URL
6548      * @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)
6549      * @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)
6550      * @return {Roo.UpdateManager} The UpdateManager
6551      */
6552     setUrl : function(url, params, loadOnce){
6553         if(this.refreshDelegate){
6554             this.un('activate', this.refreshDelegate);
6555         }
6556         this.refreshDelegate = this._handleRefresh.createDelegate(this, [url, params, loadOnce]);
6557         this.on("activate", this.refreshDelegate);
6558         return this.bodyEl.getUpdateManager();
6559     },
6560
6561     /** @private */
6562     _handleRefresh : function(url, params, loadOnce){
6563         if(!loadOnce || !this.loaded){
6564             var updater = this.bodyEl.getUpdateManager();
6565             updater.update(url, params, this._setLoaded.createDelegate(this));
6566         }
6567     },
6568
6569     /**
6570      *   Forces a content refresh from the URL specified in the {@link #setUrl} method.
6571      *   Will fail silently if the setUrl method has not been called.
6572      *   This does not activate the panel, just updates its content.
6573      */
6574     refresh : function(){
6575         if(this.refreshDelegate){
6576            this.loaded = false;
6577            this.refreshDelegate();
6578         }
6579     },
6580
6581     /** @private */
6582     _setLoaded : function(){
6583         this.loaded = true;
6584     },
6585
6586     /** @private */
6587     closeClick : function(e){
6588         var o = {};
6589         e.stopEvent();
6590         this.fireEvent("beforeclose", this, o);
6591         if(o.cancel !== true){
6592             this.tabPanel.removeTab(this.id);
6593         }
6594     },
6595     /**
6596      * The text displayed in the tooltip for the close icon.
6597      * @type String
6598      */
6599     closeText : "Close this tab"
6600 });
6601
6602 /** @private */
6603 Roo.TabPanel.prototype.createStrip = function(container){
6604     var strip = document.createElement("div");
6605     strip.className = "x-tabs-wrap";
6606     container.appendChild(strip);
6607     return strip;
6608 };
6609 /** @private */
6610 Roo.TabPanel.prototype.createStripList = function(strip){
6611     // div wrapper for retard IE
6612     // returns the "tr" element.
6613     strip.innerHTML = '<div class="x-tabs-strip-wrap">'+
6614         '<table class="x-tabs-strip" cellspacing="0" cellpadding="0" border="0"><tbody><tr>'+
6615         '<td class="x-tab-strip-toolbar"></td></tr></tbody></table></div>';
6616     return strip.firstChild.firstChild.firstChild.firstChild;
6617 };
6618 /** @private */
6619 Roo.TabPanel.prototype.createBody = function(container){
6620     var body = document.createElement("div");
6621     Roo.id(body, "tab-body");
6622     Roo.fly(body).addClass("x-tabs-body");
6623     container.appendChild(body);
6624     return body;
6625 };
6626 /** @private */
6627 Roo.TabPanel.prototype.createItemBody = function(bodyEl, id){
6628     var body = Roo.getDom(id);
6629     if(!body){
6630         body = document.createElement("div");
6631         body.id = id;
6632     }
6633     Roo.fly(body).addClass("x-tabs-item-body");
6634     bodyEl.insertBefore(body, bodyEl.firstChild);
6635     return body;
6636 };
6637 /** @private */
6638 Roo.TabPanel.prototype.createStripElements = function(stripEl, text, closable){
6639     var td = document.createElement("td");
6640     stripEl.insertBefore(td, stripEl.childNodes[stripEl.childNodes.length-1]);
6641     //stripEl.appendChild(td);
6642     if(closable){
6643         td.className = "x-tabs-closable";
6644         if(!this.closeTpl){
6645             this.closeTpl = new Roo.Template(
6646                '<a href="#" class="x-tabs-right"><span class="x-tabs-left"><em class="x-tabs-inner">' +
6647                '<span unselectable="on"' + (this.disableTooltips ? '' : ' title="{text}"') +' class="x-tabs-text">{text}</span>' +
6648                '<div unselectable="on" class="close-icon">&#160;</div></em></span></a>'
6649             );
6650         }
6651         var el = this.closeTpl.overwrite(td, {"text": text});
6652         var close = el.getElementsByTagName("div")[0];
6653         var inner = el.getElementsByTagName("em")[0];
6654         return {"el": el, "close": close, "inner": inner};
6655     } else {
6656         if(!this.tabTpl){
6657             this.tabTpl = new Roo.Template(
6658                '<a href="#" class="x-tabs-right"><span class="x-tabs-left"><em class="x-tabs-inner">' +
6659                '<span unselectable="on"' + (this.disableTooltips ? '' : ' title="{text}"') +' class="x-tabs-text">{text}</span></em></span></a>'
6660             );
6661         }
6662         var el = this.tabTpl.overwrite(td, {"text": text});
6663         var inner = el.getElementsByTagName("em")[0];
6664         return {"el": el, "inner": inner};
6665     }
6666 };/*
6667  * Based on:
6668  * Ext JS Library 1.1.1
6669  * Copyright(c) 2006-2007, Ext JS, LLC.
6670  *
6671  * Originally Released Under LGPL - original licence link has changed is not relivant.
6672  *
6673  * Fork - LGPL
6674  * <script type="text/javascript">
6675  */
6676
6677 /**
6678  * @class Roo.Button
6679  * @extends Roo.util.Observable
6680  * Simple Button class
6681  * @cfg {String} text The button text
6682  * @cfg {String} icon The path to an image to display in the button (the image will be set as the background-image
6683  * CSS property of the button by default, so if you want a mixed icon/text button, set cls:"x-btn-text-icon")
6684  * @cfg {Function} handler A function called when the button is clicked (can be used instead of click event)
6685  * @cfg {Object} scope The scope of the handler
6686  * @cfg {Number} minWidth The minimum width for this button (used to give a set of buttons a common width)
6687  * @cfg {String/Object} tooltip The tooltip for the button - can be a string or QuickTips config object
6688  * @cfg {Boolean} hidden True to start hidden (defaults to false)
6689  * @cfg {Boolean} disabled True to start disabled (defaults to false)
6690  * @cfg {Boolean} pressed True to start pressed (only if enableToggle = true)
6691  * @cfg {String} toggleGroup The group this toggle button is a member of (only 1 per group can be pressed, only
6692    applies if enableToggle = true)
6693  * @cfg {String/HTMLElement/Element} renderTo The element to append the button to
6694  * @cfg {Boolean/Object} repeat True to repeat fire the click event while the mouse is down. This can also be
6695   an {@link Roo.util.ClickRepeater} config object (defaults to false).
6696  * @constructor
6697  * Create a new button
6698  * @param {Object} config The config object
6699  */
6700 Roo.Button = function(renderTo, config)
6701 {
6702     if (!config) {
6703         config = renderTo;
6704         renderTo = config.renderTo || false;
6705     }
6706     
6707     Roo.apply(this, config);
6708     this.addEvents({
6709         /**
6710              * @event click
6711              * Fires when this button is clicked
6712              * @param {Button} this
6713              * @param {EventObject} e The click event
6714              */
6715             "click" : true,
6716         /**
6717              * @event toggle
6718              * Fires when the "pressed" state of this button changes (only if enableToggle = true)
6719              * @param {Button} this
6720              * @param {Boolean} pressed
6721              */
6722             "toggle" : true,
6723         /**
6724              * @event mouseover
6725              * Fires when the mouse hovers over the button
6726              * @param {Button} this
6727              * @param {Event} e The event object
6728              */
6729         'mouseover' : true,
6730         /**
6731              * @event mouseout
6732              * Fires when the mouse exits the button
6733              * @param {Button} this
6734              * @param {Event} e The event object
6735              */
6736         'mouseout': true,
6737          /**
6738              * @event render
6739              * Fires when the button is rendered
6740              * @param {Button} this
6741              */
6742         'render': true
6743     });
6744     if(this.menu){
6745         this.menu = Roo.menu.MenuMgr.get(this.menu);
6746     }
6747     // register listeners first!!  - so render can be captured..
6748     Roo.util.Observable.call(this);
6749     if(renderTo){
6750         this.render(renderTo);
6751     }
6752     
6753   
6754 };
6755
6756 Roo.extend(Roo.Button, Roo.util.Observable, {
6757     /**
6758      * 
6759      */
6760     
6761     /**
6762      * Read-only. True if this button is hidden
6763      * @type Boolean
6764      */
6765     hidden : false,
6766     /**
6767      * Read-only. True if this button is disabled
6768      * @type Boolean
6769      */
6770     disabled : false,
6771     /**
6772      * Read-only. True if this button is pressed (only if enableToggle = true)
6773      * @type Boolean
6774      */
6775     pressed : false,
6776
6777     /**
6778      * @cfg {Number} tabIndex 
6779      * The DOM tabIndex for this button (defaults to undefined)
6780      */
6781     tabIndex : undefined,
6782
6783     /**
6784      * @cfg {Boolean} enableToggle
6785      * True to enable pressed/not pressed toggling (defaults to false)
6786      */
6787     enableToggle: false,
6788     /**
6789      * @cfg {Mixed} menu
6790      * Standard menu attribute consisting of a reference to a menu object, a menu id or a menu config blob (defaults to undefined).
6791      */
6792     menu : undefined,
6793     /**
6794      * @cfg {String} menuAlign
6795      * The position to align the menu to (see {@link Roo.Element#alignTo} for more details, defaults to 'tl-bl?').
6796      */
6797     menuAlign : "tl-bl?",
6798
6799     /**
6800      * @cfg {String} iconCls
6801      * A css class which sets a background image to be used as the icon for this button (defaults to undefined).
6802      */
6803     iconCls : undefined,
6804     /**
6805      * @cfg {String} type
6806      * The button's type, corresponding to the DOM input element type attribute.  Either "submit," "reset" or "button" (default).
6807      */
6808     type : 'button',
6809
6810     // private
6811     menuClassTarget: 'tr',
6812
6813     /**
6814      * @cfg {String} clickEvent
6815      * The type of event to map to the button's event handler (defaults to 'click')
6816      */
6817     clickEvent : 'click',
6818
6819     /**
6820      * @cfg {Boolean} handleMouseEvents
6821      * False to disable visual cues on mouseover, mouseout and mousedown (defaults to true)
6822      */
6823     handleMouseEvents : true,
6824
6825     /**
6826      * @cfg {String} tooltipType
6827      * The type of tooltip to use. Either "qtip" (default) for QuickTips or "title" for title attribute.
6828      */
6829     tooltipType : 'qtip',
6830
6831     /**
6832      * @cfg {String} cls
6833      * A CSS class to apply to the button's main element.
6834      */
6835     
6836     /**
6837      * @cfg {Roo.Template} template (Optional)
6838      * An {@link Roo.Template} with which to create the Button's main element. This Template must
6839      * contain numeric substitution parameter 0 if it is to display the tRoo property. Changing the template could
6840      * require code modifications if required elements (e.g. a button) aren't present.
6841      */
6842
6843     // private
6844     render : function(renderTo){
6845         var btn;
6846         if(this.hideParent){
6847             this.parentEl = Roo.get(renderTo);
6848         }
6849         if(!this.dhconfig){
6850             if(!this.template){
6851                 if(!Roo.Button.buttonTemplate){
6852                     // hideous table template
6853                     Roo.Button.buttonTemplate = new Roo.Template(
6854                         '<table border="0" cellpadding="0" cellspacing="0" class="x-btn-wrap"><tbody><tr>',
6855                         '<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>',
6856                         "</tr></tbody></table>");
6857                 }
6858                 this.template = Roo.Button.buttonTemplate;
6859             }
6860             btn = this.template.append(renderTo, [this.text || '&#160;', this.type], true);
6861             var btnEl = btn.child("button:first");
6862             btnEl.on('focus', this.onFocus, this);
6863             btnEl.on('blur', this.onBlur, this);
6864             if(this.cls){
6865                 btn.addClass(this.cls);
6866             }
6867             if(this.icon){
6868                 btnEl.setStyle('background-image', 'url(' +this.icon +')');
6869             }
6870             if(this.iconCls){
6871                 btnEl.addClass(this.iconCls);
6872                 if(!this.cls){
6873                     btn.addClass(this.text ? 'x-btn-text-icon' : 'x-btn-icon');
6874                 }
6875             }
6876             if(this.tabIndex !== undefined){
6877                 btnEl.dom.tabIndex = this.tabIndex;
6878             }
6879             if(this.tooltip){
6880                 if(typeof this.tooltip == 'object'){
6881                     Roo.QuickTips.tips(Roo.apply({
6882                           target: btnEl.id
6883                     }, this.tooltip));
6884                 } else {
6885                     btnEl.dom[this.tooltipType] = this.tooltip;
6886                 }
6887             }
6888         }else{
6889             btn = Roo.DomHelper.append(Roo.get(renderTo).dom, this.dhconfig, true);
6890         }
6891         this.el = btn;
6892         if(this.id){
6893             this.el.dom.id = this.el.id = this.id;
6894         }
6895         if(this.menu){
6896             this.el.child(this.menuClassTarget).addClass("x-btn-with-menu");
6897             this.menu.on("show", this.onMenuShow, this);
6898             this.menu.on("hide", this.onMenuHide, this);
6899         }
6900         btn.addClass("x-btn");
6901         if(Roo.isIE && !Roo.isIE7){
6902             this.autoWidth.defer(1, this);
6903         }else{
6904             this.autoWidth();
6905         }
6906         if(this.handleMouseEvents){
6907             btn.on("mouseover", this.onMouseOver, this);
6908             btn.on("mouseout", this.onMouseOut, this);
6909             btn.on("mousedown", this.onMouseDown, this);
6910         }
6911         btn.on(this.clickEvent, this.onClick, this);
6912         //btn.on("mouseup", this.onMouseUp, this);
6913         if(this.hidden){
6914             this.hide();
6915         }
6916         if(this.disabled){
6917             this.disable();
6918         }
6919         Roo.ButtonToggleMgr.register(this);
6920         if(this.pressed){
6921             this.el.addClass("x-btn-pressed");
6922         }
6923         if(this.repeat){
6924             var repeater = new Roo.util.ClickRepeater(btn,
6925                 typeof this.repeat == "object" ? this.repeat : {}
6926             );
6927             repeater.on("click", this.onClick,  this);
6928         }
6929         
6930         this.fireEvent('render', this);
6931         
6932     },
6933     /**
6934      * Returns the button's underlying element
6935      * @return {Roo.Element} The element
6936      */
6937     getEl : function(){
6938         return this.el;  
6939     },
6940     
6941     /**
6942      * Destroys this Button and removes any listeners.
6943      */
6944     destroy : function(){
6945         Roo.ButtonToggleMgr.unregister(this);
6946         this.el.removeAllListeners();
6947         this.purgeListeners();
6948         this.el.remove();
6949     },
6950
6951     // private
6952     autoWidth : function(){
6953         if(this.el){
6954             this.el.setWidth("auto");
6955             if(Roo.isIE7 && Roo.isStrict){
6956                 var ib = this.el.child('button');
6957                 if(ib && ib.getWidth() > 20){
6958                     ib.clip();
6959                     ib.setWidth(Roo.util.TextMetrics.measure(ib, this.text).width+ib.getFrameWidth('lr'));
6960                 }
6961             }
6962             if(this.minWidth){
6963                 if(this.hidden){
6964                     this.el.beginMeasure();
6965                 }
6966                 if(this.el.getWidth() < this.minWidth){
6967                     this.el.setWidth(this.minWidth);
6968                 }
6969                 if(this.hidden){
6970                     this.el.endMeasure();
6971                 }
6972             }
6973         }
6974     },
6975
6976     /**
6977      * Assigns this button's click handler
6978      * @param {Function} handler The function to call when the button is clicked
6979      * @param {Object} scope (optional) Scope for the function passed in
6980      */
6981     setHandler : function(handler, scope){
6982         this.handler = handler;
6983         this.scope = scope;  
6984     },
6985     
6986     /**
6987      * Sets this button's text
6988      * @param {String} text The button text
6989      */
6990     setText : function(text){
6991         this.text = text;
6992         if(this.el){
6993             this.el.child("td.x-btn-center button.x-btn-text").update(text);
6994         }
6995         this.autoWidth();
6996     },
6997     
6998     /**
6999      * Gets the text for this button
7000      * @return {String} The button text
7001      */
7002     getText : function(){
7003         return this.text;  
7004     },
7005     
7006     /**
7007      * Show this button
7008      */
7009     show: function(){
7010         this.hidden = false;
7011         if(this.el){
7012             this[this.hideParent? 'parentEl' : 'el'].setStyle("display", "");
7013         }
7014     },
7015     
7016     /**
7017      * Hide this button
7018      */
7019     hide: function(){
7020         this.hidden = true;
7021         if(this.el){
7022             this[this.hideParent? 'parentEl' : 'el'].setStyle("display", "none");
7023         }
7024     },
7025     
7026     /**
7027      * Convenience function for boolean show/hide
7028      * @param {Boolean} visible True to show, false to hide
7029      */
7030     setVisible: function(visible){
7031         if(visible) {
7032             this.show();
7033         }else{
7034             this.hide();
7035         }
7036     },
7037     
7038     /**
7039      * If a state it passed, it becomes the pressed state otherwise the current state is toggled.
7040      * @param {Boolean} state (optional) Force a particular state
7041      */
7042     toggle : function(state){
7043         state = state === undefined ? !this.pressed : state;
7044         if(state != this.pressed){
7045             if(state){
7046                 this.el.addClass("x-btn-pressed");
7047                 this.pressed = true;
7048                 this.fireEvent("toggle", this, true);
7049             }else{
7050                 this.el.removeClass("x-btn-pressed");
7051                 this.pressed = false;
7052                 this.fireEvent("toggle", this, false);
7053             }
7054             if(this.toggleHandler){
7055                 this.toggleHandler.call(this.scope || this, this, state);
7056             }
7057         }
7058     },
7059     
7060     /**
7061      * Focus the button
7062      */
7063     focus : function(){
7064         this.el.child('button:first').focus();
7065     },
7066     
7067     /**
7068      * Disable this button
7069      */
7070     disable : function(){
7071         if(this.el){
7072             this.el.addClass("x-btn-disabled");
7073         }
7074         this.disabled = true;
7075     },
7076     
7077     /**
7078      * Enable this button
7079      */
7080     enable : function(){
7081         if(this.el){
7082             this.el.removeClass("x-btn-disabled");
7083         }
7084         this.disabled = false;
7085     },
7086
7087     /**
7088      * Convenience function for boolean enable/disable
7089      * @param {Boolean} enabled True to enable, false to disable
7090      */
7091     setDisabled : function(v){
7092         this[v !== true ? "enable" : "disable"]();
7093     },
7094
7095     // private
7096     onClick : function(e)
7097     {
7098         if(e){
7099             e.preventDefault();
7100         }
7101         if(e.button != 0){
7102             return;
7103         }
7104         if(!this.disabled){
7105             if(this.enableToggle){
7106                 this.toggle();
7107             }
7108             if(this.menu && !this.menu.isVisible()){
7109                 this.menu.show(this.el, this.menuAlign);
7110             }
7111             this.fireEvent("click", this, e);
7112             if(this.handler){
7113                 this.el.removeClass("x-btn-over");
7114                 this.handler.call(this.scope || this, this, e);
7115             }
7116         }
7117     },
7118     // private
7119     onMouseOver : function(e){
7120         if(!this.disabled){
7121             this.el.addClass("x-btn-over");
7122             this.fireEvent('mouseover', this, e);
7123         }
7124     },
7125     // private
7126     onMouseOut : function(e){
7127         if(!e.within(this.el,  true)){
7128             this.el.removeClass("x-btn-over");
7129             this.fireEvent('mouseout', this, e);
7130         }
7131     },
7132     // private
7133     onFocus : function(e){
7134         if(!this.disabled){
7135             this.el.addClass("x-btn-focus");
7136         }
7137     },
7138     // private
7139     onBlur : function(e){
7140         this.el.removeClass("x-btn-focus");
7141     },
7142     // private
7143     onMouseDown : function(e){
7144         if(!this.disabled && e.button == 0){
7145             this.el.addClass("x-btn-click");
7146             Roo.get(document).on('mouseup', this.onMouseUp, this);
7147         }
7148     },
7149     // private
7150     onMouseUp : function(e){
7151         if(e.button == 0){
7152             this.el.removeClass("x-btn-click");
7153             Roo.get(document).un('mouseup', this.onMouseUp, this);
7154         }
7155     },
7156     // private
7157     onMenuShow : function(e){
7158         this.el.addClass("x-btn-menu-active");
7159     },
7160     // private
7161     onMenuHide : function(e){
7162         this.el.removeClass("x-btn-menu-active");
7163     }   
7164 });
7165
7166 // Private utility class used by Button
7167 Roo.ButtonToggleMgr = function(){
7168    var groups = {};
7169    
7170    function toggleGroup(btn, state){
7171        if(state){
7172            var g = groups[btn.toggleGroup];
7173            for(var i = 0, l = g.length; i < l; i++){
7174                if(g[i] != btn){
7175                    g[i].toggle(false);
7176                }
7177            }
7178        }
7179    }
7180    
7181    return {
7182        register : function(btn){
7183            if(!btn.toggleGroup){
7184                return;
7185            }
7186            var g = groups[btn.toggleGroup];
7187            if(!g){
7188                g = groups[btn.toggleGroup] = [];
7189            }
7190            g.push(btn);
7191            btn.on("toggle", toggleGroup);
7192        },
7193        
7194        unregister : function(btn){
7195            if(!btn.toggleGroup){
7196                return;
7197            }
7198            var g = groups[btn.toggleGroup];
7199            if(g){
7200                g.remove(btn);
7201                btn.un("toggle", toggleGroup);
7202            }
7203        }
7204    };
7205 }();/*
7206  * Based on:
7207  * Ext JS Library 1.1.1
7208  * Copyright(c) 2006-2007, Ext JS, LLC.
7209  *
7210  * Originally Released Under LGPL - original licence link has changed is not relivant.
7211  *
7212  * Fork - LGPL
7213  * <script type="text/javascript">
7214  */
7215  
7216 /**
7217  * @class Roo.SplitButton
7218  * @extends Roo.Button
7219  * A split button that provides a built-in dropdown arrow that can fire an event separately from the default
7220  * click event of the button.  Typically this would be used to display a dropdown menu that provides additional
7221  * options to the primary button action, but any custom handler can provide the arrowclick implementation.
7222  * @cfg {Function} arrowHandler A function called when the arrow button is clicked (can be used instead of click event)
7223  * @cfg {String} arrowTooltip The title attribute of the arrow
7224  * @constructor
7225  * Create a new menu button
7226  * @param {String/HTMLElement/Element} renderTo The element to append the button to
7227  * @param {Object} config The config object
7228  */
7229 Roo.SplitButton = function(renderTo, config){
7230     Roo.SplitButton.superclass.constructor.call(this, renderTo, config);
7231     /**
7232      * @event arrowclick
7233      * Fires when this button's arrow is clicked
7234      * @param {SplitButton} this
7235      * @param {EventObject} e The click event
7236      */
7237     this.addEvents({"arrowclick":true});
7238 };
7239
7240 Roo.extend(Roo.SplitButton, Roo.Button, {
7241     render : function(renderTo){
7242         // this is one sweet looking template!
7243         var tpl = new Roo.Template(
7244             '<table cellspacing="0" class="x-btn-menu-wrap x-btn"><tr><td>',
7245             '<table cellspacing="0" class="x-btn-wrap x-btn-menu-text-wrap"><tbody>',
7246             '<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>',
7247             "</tbody></table></td><td>",
7248             '<table cellspacing="0" class="x-btn-wrap x-btn-menu-arrow-wrap"><tbody>',
7249             '<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>',
7250             "</tbody></table></td></tr></table>"
7251         );
7252         var btn = tpl.append(renderTo, [this.text, this.type], true);
7253         var btnEl = btn.child("button");
7254         if(this.cls){
7255             btn.addClass(this.cls);
7256         }
7257         if(this.icon){
7258             btnEl.setStyle('background-image', 'url(' +this.icon +')');
7259         }
7260         if(this.iconCls){
7261             btnEl.addClass(this.iconCls);
7262             if(!this.cls){
7263                 btn.addClass(this.text ? 'x-btn-text-icon' : 'x-btn-icon');
7264             }
7265         }
7266         this.el = btn;
7267         if(this.handleMouseEvents){
7268             btn.on("mouseover", this.onMouseOver, this);
7269             btn.on("mouseout", this.onMouseOut, this);
7270             btn.on("mousedown", this.onMouseDown, this);
7271             btn.on("mouseup", this.onMouseUp, this);
7272         }
7273         btn.on(this.clickEvent, this.onClick, this);
7274         if(this.tooltip){
7275             if(typeof this.tooltip == 'object'){
7276                 Roo.QuickTips.tips(Roo.apply({
7277                       target: btnEl.id
7278                 }, this.tooltip));
7279             } else {
7280                 btnEl.dom[this.tooltipType] = this.tooltip;
7281             }
7282         }
7283         if(this.arrowTooltip){
7284             btn.child("button:nth(2)").dom[this.tooltipType] = this.arrowTooltip;
7285         }
7286         if(this.hidden){
7287             this.hide();
7288         }
7289         if(this.disabled){
7290             this.disable();
7291         }
7292         if(this.pressed){
7293             this.el.addClass("x-btn-pressed");
7294         }
7295         if(Roo.isIE && !Roo.isIE7){
7296             this.autoWidth.defer(1, this);
7297         }else{
7298             this.autoWidth();
7299         }
7300         if(this.menu){
7301             this.menu.on("show", this.onMenuShow, this);
7302             this.menu.on("hide", this.onMenuHide, this);
7303         }
7304         this.fireEvent('render', this);
7305     },
7306
7307     // private
7308     autoWidth : function(){
7309         if(this.el){
7310             var tbl = this.el.child("table:first");
7311             var tbl2 = this.el.child("table:last");
7312             this.el.setWidth("auto");
7313             tbl.setWidth("auto");
7314             if(Roo.isIE7 && Roo.isStrict){
7315                 var ib = this.el.child('button:first');
7316                 if(ib && ib.getWidth() > 20){
7317                     ib.clip();
7318                     ib.setWidth(Roo.util.TextMetrics.measure(ib, this.text).width+ib.getFrameWidth('lr'));
7319                 }
7320             }
7321             if(this.minWidth){
7322                 if(this.hidden){
7323                     this.el.beginMeasure();
7324                 }
7325                 if((tbl.getWidth()+tbl2.getWidth()) < this.minWidth){
7326                     tbl.setWidth(this.minWidth-tbl2.getWidth());
7327                 }
7328                 if(this.hidden){
7329                     this.el.endMeasure();
7330                 }
7331             }
7332             this.el.setWidth(tbl.getWidth()+tbl2.getWidth());
7333         } 
7334     },
7335     /**
7336      * Sets this button's click handler
7337      * @param {Function} handler The function to call when the button is clicked
7338      * @param {Object} scope (optional) Scope for the function passed above
7339      */
7340     setHandler : function(handler, scope){
7341         this.handler = handler;
7342         this.scope = scope;  
7343     },
7344     
7345     /**
7346      * Sets this button's arrow click handler
7347      * @param {Function} handler The function to call when the arrow is clicked
7348      * @param {Object} scope (optional) Scope for the function passed above
7349      */
7350     setArrowHandler : function(handler, scope){
7351         this.arrowHandler = handler;
7352         this.scope = scope;  
7353     },
7354     
7355     /**
7356      * Focus the button
7357      */
7358     focus : function(){
7359         if(this.el){
7360             this.el.child("button:first").focus();
7361         }
7362     },
7363
7364     // private
7365     onClick : function(e){
7366         e.preventDefault();
7367         if(!this.disabled){
7368             if(e.getTarget(".x-btn-menu-arrow-wrap")){
7369                 if(this.menu && !this.menu.isVisible()){
7370                     this.menu.show(this.el, this.menuAlign);
7371                 }
7372                 this.fireEvent("arrowclick", this, e);
7373                 if(this.arrowHandler){
7374                     this.arrowHandler.call(this.scope || this, this, e);
7375                 }
7376             }else{
7377                 this.fireEvent("click", this, e);
7378                 if(this.handler){
7379                     this.handler.call(this.scope || this, this, e);
7380                 }
7381             }
7382         }
7383     },
7384     // private
7385     onMouseDown : function(e){
7386         if(!this.disabled){
7387             Roo.fly(e.getTarget("table")).addClass("x-btn-click");
7388         }
7389     },
7390     // private
7391     onMouseUp : function(e){
7392         Roo.fly(e.getTarget("table")).removeClass("x-btn-click");
7393     }   
7394 });
7395
7396
7397 // backwards compat
7398 Roo.MenuButton = Roo.SplitButton;/*
7399  * Based on:
7400  * Ext JS Library 1.1.1
7401  * Copyright(c) 2006-2007, Ext JS, LLC.
7402  *
7403  * Originally Released Under LGPL - original licence link has changed is not relivant.
7404  *
7405  * Fork - LGPL
7406  * <script type="text/javascript">
7407  */
7408
7409 /**
7410  * @class Roo.Toolbar
7411  * Basic Toolbar class.
7412  * @constructor
7413  * Creates a new Toolbar
7414  * @param {Object} container The config object
7415  */ 
7416 Roo.Toolbar = function(container, buttons, config)
7417 {
7418     /// old consturctor format still supported..
7419     if(container instanceof Array){ // omit the container for later rendering
7420         buttons = container;
7421         config = buttons;
7422         container = null;
7423     }
7424     if (typeof(container) == 'object' && container.xtype) {
7425         config = container;
7426         container = config.container;
7427         buttons = config.buttons || []; // not really - use items!!
7428     }
7429     var xitems = [];
7430     if (config && config.items) {
7431         xitems = config.items;
7432         delete config.items;
7433     }
7434     Roo.apply(this, config);
7435     this.buttons = buttons;
7436     
7437     if(container){
7438         this.render(container);
7439     }
7440     this.xitems = xitems;
7441     Roo.each(xitems, function(b) {
7442         this.add(b);
7443     }, this);
7444     
7445 };
7446
7447 Roo.Toolbar.prototype = {
7448     /**
7449      * @cfg {Array} items
7450      * array of button configs or elements to add (will be converted to a MixedCollection)
7451      */
7452     
7453     /**
7454      * @cfg {String/HTMLElement/Element} container
7455      * The id or element that will contain the toolbar
7456      */
7457     // private
7458     render : function(ct){
7459         this.el = Roo.get(ct);
7460         if(this.cls){
7461             this.el.addClass(this.cls);
7462         }
7463         // using a table allows for vertical alignment
7464         // 100% width is needed by Safari...
7465         this.el.update('<div class="x-toolbar x-small-editor"><table cellspacing="0"><tr></tr></table></div>');
7466         this.tr = this.el.child("tr", true);
7467         var autoId = 0;
7468         this.items = new Roo.util.MixedCollection(false, function(o){
7469             return o.id || ("item" + (++autoId));
7470         });
7471         if(this.buttons){
7472             this.add.apply(this, this.buttons);
7473             delete this.buttons;
7474         }
7475     },
7476
7477     /**
7478      * Adds element(s) to the toolbar -- this function takes a variable number of 
7479      * arguments of mixed type and adds them to the toolbar.
7480      * @param {Mixed} arg1 The following types of arguments are all valid:<br />
7481      * <ul>
7482      * <li>{@link Roo.Toolbar.Button} config: A valid button config object (equivalent to {@link #addButton})</li>
7483      * <li>HtmlElement: Any standard HTML element (equivalent to {@link #addElement})</li>
7484      * <li>Field: Any form field (equivalent to {@link #addField})</li>
7485      * <li>Item: Any subclass of {@link Roo.Toolbar.Item} (equivalent to {@link #addItem})</li>
7486      * <li>String: Any generic string (gets wrapped in a {@link Roo.Toolbar.TextItem}, equivalent to {@link #addText}).
7487      * Note that there are a few special strings that are treated differently as explained nRoo.</li>
7488      * <li>'separator' or '-': Creates a separator element (equivalent to {@link #addSeparator})</li>
7489      * <li>' ': Creates a spacer element (equivalent to {@link #addSpacer})</li>
7490      * <li>'->': Creates a fill element (equivalent to {@link #addFill})</li>
7491      * </ul>
7492      * @param {Mixed} arg2
7493      * @param {Mixed} etc.
7494      */
7495     add : function(){
7496         var a = arguments, l = a.length;
7497         for(var i = 0; i < l; i++){
7498             this._add(a[i]);
7499         }
7500     },
7501     // private..
7502     _add : function(el) {
7503         
7504         if (el.xtype) {
7505             el = Roo.factory(el, typeof(Roo.Toolbar[el.xtype]) == 'undefined' ? Roo.form : Roo.Toolbar);
7506         }
7507         
7508         if (el.applyTo){ // some kind of form field
7509             return this.addField(el);
7510         } 
7511         if (el.render){ // some kind of Toolbar.Item
7512             return this.addItem(el);
7513         }
7514         if (typeof el == "string"){ // string
7515             if(el == "separator" || el == "-"){
7516                 return this.addSeparator();
7517             }
7518             if (el == " "){
7519                 return this.addSpacer();
7520             }
7521             if(el == "->"){
7522                 return this.addFill();
7523             }
7524             return this.addText(el);
7525             
7526         }
7527         if(el.tagName){ // element
7528             return this.addElement(el);
7529         }
7530         if(typeof el == "object"){ // must be button config?
7531             return this.addButton(el);
7532         }
7533         // and now what?!?!
7534         return false;
7535         
7536     },
7537     
7538     /**
7539      * Add an Xtype element
7540      * @param {Object} xtype Xtype Object
7541      * @return {Object} created Object
7542      */
7543     addxtype : function(e){
7544         return this.add(e);  
7545     },
7546     
7547     /**
7548      * Returns the Element for this toolbar.
7549      * @return {Roo.Element}
7550      */
7551     getEl : function(){
7552         return this.el;  
7553     },
7554     
7555     /**
7556      * Adds a separator
7557      * @return {Roo.Toolbar.Item} The separator item
7558      */
7559     addSeparator : function(){
7560         return this.addItem(new Roo.Toolbar.Separator());
7561     },
7562
7563     /**
7564      * Adds a spacer element
7565      * @return {Roo.Toolbar.Spacer} The spacer item
7566      */
7567     addSpacer : function(){
7568         return this.addItem(new Roo.Toolbar.Spacer());
7569     },
7570
7571     /**
7572      * Adds a fill element that forces subsequent additions to the right side of the toolbar
7573      * @return {Roo.Toolbar.Fill} The fill item
7574      */
7575     addFill : function(){
7576         return this.addItem(new Roo.Toolbar.Fill());
7577     },
7578
7579     /**
7580      * Adds any standard HTML element to the toolbar
7581      * @param {String/HTMLElement/Element} el The element or id of the element to add
7582      * @return {Roo.Toolbar.Item} The element's item
7583      */
7584     addElement : function(el){
7585         return this.addItem(new Roo.Toolbar.Item(el));
7586     },
7587     /**
7588      * Collection of items on the toolbar.. (only Toolbar Items, so use fields to retrieve fields)
7589      * @type Roo.util.MixedCollection  
7590      */
7591     items : false,
7592      
7593     /**
7594      * Adds any Toolbar.Item or subclass
7595      * @param {Roo.Toolbar.Item} item
7596      * @return {Roo.Toolbar.Item} The item
7597      */
7598     addItem : function(item){
7599         var td = this.nextBlock();
7600         item.render(td);
7601         this.items.add(item);
7602         return item;
7603     },
7604     
7605     /**
7606      * Adds a button (or buttons). See {@link Roo.Toolbar.Button} for more info on the config.
7607      * @param {Object/Array} config A button config or array of configs
7608      * @return {Roo.Toolbar.Button/Array}
7609      */
7610     addButton : function(config){
7611         if(config instanceof Array){
7612             var buttons = [];
7613             for(var i = 0, len = config.length; i < len; i++) {
7614                 buttons.push(this.addButton(config[i]));
7615             }
7616             return buttons;
7617         }
7618         var b = config;
7619         if(!(config instanceof Roo.Toolbar.Button)){
7620             b = config.split ?
7621                 new Roo.Toolbar.SplitButton(config) :
7622                 new Roo.Toolbar.Button(config);
7623         }
7624         var td = this.nextBlock();
7625         b.render(td);
7626         this.items.add(b);
7627         return b;
7628     },
7629     
7630     /**
7631      * Adds text to the toolbar
7632      * @param {String} text The text to add
7633      * @return {Roo.Toolbar.Item} The element's item
7634      */
7635     addText : function(text){
7636         return this.addItem(new Roo.Toolbar.TextItem(text));
7637     },
7638     
7639     /**
7640      * Inserts any {@link Roo.Toolbar.Item}/{@link Roo.Toolbar.Button} at the specified index.
7641      * @param {Number} index The index where the item is to be inserted
7642      * @param {Object/Roo.Toolbar.Item/Roo.Toolbar.Button (may be Array)} item The button, or button config object to be inserted.
7643      * @return {Roo.Toolbar.Button/Item}
7644      */
7645     insertButton : function(index, item){
7646         if(item instanceof Array){
7647             var buttons = [];
7648             for(var i = 0, len = item.length; i < len; i++) {
7649                buttons.push(this.insertButton(index + i, item[i]));
7650             }
7651             return buttons;
7652         }
7653         if (!(item instanceof Roo.Toolbar.Button)){
7654            item = new Roo.Toolbar.Button(item);
7655         }
7656         var td = document.createElement("td");
7657         this.tr.insertBefore(td, this.tr.childNodes[index]);
7658         item.render(td);
7659         this.items.insert(index, item);
7660         return item;
7661     },
7662     
7663     /**
7664      * Adds a new element to the toolbar from the passed {@link Roo.DomHelper} config.
7665      * @param {Object} config
7666      * @return {Roo.Toolbar.Item} The element's item
7667      */
7668     addDom : function(config, returnEl){
7669         var td = this.nextBlock();
7670         Roo.DomHelper.overwrite(td, config);
7671         var ti = new Roo.Toolbar.Item(td.firstChild);
7672         ti.render(td);
7673         this.items.add(ti);
7674         return ti;
7675     },
7676
7677     /**
7678      * Collection of fields on the toolbar.. usefull for quering (value is false if there are no fields)
7679      * @type Roo.util.MixedCollection  
7680      */
7681     fields : false,
7682     
7683     /**
7684      * Adds a dynamically rendered Roo.form field (TextField, ComboBox, etc).
7685      * Note: the field should not have been rendered yet. For a field that has already been
7686      * rendered, use {@link #addElement}.
7687      * @param {Roo.form.Field} field
7688      * @return {Roo.ToolbarItem}
7689      */
7690      
7691       
7692     addField : function(field) {
7693         if (!this.fields) {
7694             var autoId = 0;
7695             this.fields = new Roo.util.MixedCollection(false, function(o){
7696                 return o.id || ("item" + (++autoId));
7697             });
7698
7699         }
7700         
7701         var td = this.nextBlock();
7702         field.render(td);
7703         var ti = new Roo.Toolbar.Item(td.firstChild);
7704         ti.render(td);
7705         this.items.add(ti);
7706         this.fields.add(field);
7707         return ti;
7708     },
7709     /**
7710      * Hide the toolbar
7711      * @method hide
7712      */
7713      
7714       
7715     hide : function()
7716     {
7717         this.el.child('div').setVisibilityMode(Roo.Element.DISPLAY);
7718         this.el.child('div').hide();
7719     },
7720     /**
7721      * Show the toolbar
7722      * @method show
7723      */
7724     show : function()
7725     {
7726         this.el.child('div').show();
7727     },
7728       
7729     // private
7730     nextBlock : function(){
7731         var td = document.createElement("td");
7732         this.tr.appendChild(td);
7733         return td;
7734     },
7735
7736     // private
7737     destroy : function(){
7738         if(this.items){ // rendered?
7739             Roo.destroy.apply(Roo, this.items.items);
7740         }
7741         if(this.fields){ // rendered?
7742             Roo.destroy.apply(Roo, this.fields.items);
7743         }
7744         Roo.Element.uncache(this.el, this.tr);
7745     }
7746 };
7747
7748 /**
7749  * @class Roo.Toolbar.Item
7750  * The base class that other classes should extend in order to get some basic common toolbar item functionality.
7751  * @constructor
7752  * Creates a new Item
7753  * @param {HTMLElement} el 
7754  */
7755 Roo.Toolbar.Item = function(el){
7756     var cfg = {};
7757     if (typeof (el.xtype) != 'undefined') {
7758         cfg = el;
7759         el = cfg.el;
7760     }
7761     
7762     this.el = Roo.getDom(el);
7763     this.id = Roo.id(this.el);
7764     this.hidden = false;
7765     
7766     this.addEvents({
7767          /**
7768              * @event render
7769              * Fires when the button is rendered
7770              * @param {Button} this
7771              */
7772         'render': true
7773     });
7774     Roo.Toolbar.Item.superclass.constructor.call(this,cfg);
7775 };
7776 Roo.extend(Roo.Toolbar.Item, Roo.util.Observable, {
7777 //Roo.Toolbar.Item.prototype = {
7778     
7779     /**
7780      * Get this item's HTML Element
7781      * @return {HTMLElement}
7782      */
7783     getEl : function(){
7784        return this.el;  
7785     },
7786
7787     // private
7788     render : function(td){
7789         
7790          this.td = td;
7791         td.appendChild(this.el);
7792         
7793         this.fireEvent('render', this);
7794     },
7795     
7796     /**
7797      * Removes and destroys this item.
7798      */
7799     destroy : function(){
7800         this.td.parentNode.removeChild(this.td);
7801     },
7802     
7803     /**
7804      * Shows this item.
7805      */
7806     show: function(){
7807         this.hidden = false;
7808         this.td.style.display = "";
7809     },
7810     
7811     /**
7812      * Hides this item.
7813      */
7814     hide: function(){
7815         this.hidden = true;
7816         this.td.style.display = "none";
7817     },
7818     
7819     /**
7820      * Convenience function for boolean show/hide.
7821      * @param {Boolean} visible true to show/false to hide
7822      */
7823     setVisible: function(visible){
7824         if(visible) {
7825             this.show();
7826         }else{
7827             this.hide();
7828         }
7829     },
7830     
7831     /**
7832      * Try to focus this item.
7833      */
7834     focus : function(){
7835         Roo.fly(this.el).focus();
7836     },
7837     
7838     /**
7839      * Disables this item.
7840      */
7841     disable : function(){
7842         Roo.fly(this.td).addClass("x-item-disabled");
7843         this.disabled = true;
7844         this.el.disabled = true;
7845     },
7846     
7847     /**
7848      * Enables this item.
7849      */
7850     enable : function(){
7851         Roo.fly(this.td).removeClass("x-item-disabled");
7852         this.disabled = false;
7853         this.el.disabled = false;
7854     }
7855 });
7856
7857
7858 /**
7859  * @class Roo.Toolbar.Separator
7860  * @extends Roo.Toolbar.Item
7861  * A simple toolbar separator class
7862  * @constructor
7863  * Creates a new Separator
7864  */
7865 Roo.Toolbar.Separator = function(cfg){
7866     
7867     var s = document.createElement("span");
7868     s.className = "ytb-sep";
7869     if (cfg) {
7870         cfg.el = s;
7871     }
7872     
7873     Roo.Toolbar.Separator.superclass.constructor.call(this, cfg || s);
7874 };
7875 Roo.extend(Roo.Toolbar.Separator, Roo.Toolbar.Item, {
7876     enable:Roo.emptyFn,
7877     disable:Roo.emptyFn,
7878     focus:Roo.emptyFn
7879 });
7880
7881 /**
7882  * @class Roo.Toolbar.Spacer
7883  * @extends Roo.Toolbar.Item
7884  * A simple element that adds extra horizontal space to a toolbar.
7885  * @constructor
7886  * Creates a new Spacer
7887  */
7888 Roo.Toolbar.Spacer = function(cfg){
7889     var s = document.createElement("div");
7890     s.className = "ytb-spacer";
7891     if (cfg) {
7892         cfg.el = s;
7893     }
7894     Roo.Toolbar.Spacer.superclass.constructor.call(this, cfg || s);
7895 };
7896 Roo.extend(Roo.Toolbar.Spacer, Roo.Toolbar.Item, {
7897     enable:Roo.emptyFn,
7898     disable:Roo.emptyFn,
7899     focus:Roo.emptyFn
7900 });
7901
7902 /**
7903  * @class Roo.Toolbar.Fill
7904  * @extends Roo.Toolbar.Spacer
7905  * A simple element that adds a greedy (100% width) horizontal space to a toolbar.
7906  * @constructor
7907  * Creates a new Spacer
7908  */
7909 Roo.Toolbar.Fill = Roo.extend(Roo.Toolbar.Spacer, {
7910     // private
7911     render : function(td){
7912         td.style.width = '100%';
7913         Roo.Toolbar.Fill.superclass.render.call(this, td);
7914     }
7915 });
7916
7917 /**
7918  * @class Roo.Toolbar.TextItem
7919  * @extends Roo.Toolbar.Item
7920  * A simple class that renders text directly into a toolbar.
7921  * @constructor
7922  * Creates a new TextItem
7923  * @param {String} text
7924  */
7925 Roo.Toolbar.TextItem = function(cfg){
7926     var  text = cfg || "";
7927     if (typeof(cfg) == 'object') {
7928         text = cfg.text || "";
7929     }  else {
7930         cfg = null;
7931     }
7932     var s = document.createElement("span");
7933     s.className = "ytb-text";
7934     s.innerHTML = text;
7935     if (cfg) {
7936         cfg.el  = s;
7937     }
7938     
7939     Roo.Toolbar.TextItem.superclass.constructor.call(this, cfg ||  s);
7940 };
7941 Roo.extend(Roo.Toolbar.TextItem, Roo.Toolbar.Item, {
7942     
7943      
7944     enable:Roo.emptyFn,
7945     disable:Roo.emptyFn,
7946     focus:Roo.emptyFn
7947 });
7948
7949 /**
7950  * @class Roo.Toolbar.Button
7951  * @extends Roo.Button
7952  * A button that renders into a toolbar.
7953  * @constructor
7954  * Creates a new Button
7955  * @param {Object} config A standard {@link Roo.Button} config object
7956  */
7957 Roo.Toolbar.Button = function(config){
7958     Roo.Toolbar.Button.superclass.constructor.call(this, null, config);
7959 };
7960 Roo.extend(Roo.Toolbar.Button, Roo.Button, {
7961     render : function(td){
7962         this.td = td;
7963         Roo.Toolbar.Button.superclass.render.call(this, td);
7964     },
7965     
7966     /**
7967      * Removes and destroys this button
7968      */
7969     destroy : function(){
7970         Roo.Toolbar.Button.superclass.destroy.call(this);
7971         this.td.parentNode.removeChild(this.td);
7972     },
7973     
7974     /**
7975      * Shows this button
7976      */
7977     show: function(){
7978         this.hidden = false;
7979         this.td.style.display = "";
7980     },
7981     
7982     /**
7983      * Hides this button
7984      */
7985     hide: function(){
7986         this.hidden = true;
7987         this.td.style.display = "none";
7988     },
7989
7990     /**
7991      * Disables this item
7992      */
7993     disable : function(){
7994         Roo.fly(this.td).addClass("x-item-disabled");
7995         this.disabled = true;
7996     },
7997
7998     /**
7999      * Enables this item
8000      */
8001     enable : function(){
8002         Roo.fly(this.td).removeClass("x-item-disabled");
8003         this.disabled = false;
8004     }
8005 });
8006 // backwards compat
8007 Roo.ToolbarButton = Roo.Toolbar.Button;
8008
8009 /**
8010  * @class Roo.Toolbar.SplitButton
8011  * @extends Roo.SplitButton
8012  * A menu button that renders into a toolbar.
8013  * @constructor
8014  * Creates a new SplitButton
8015  * @param {Object} config A standard {@link Roo.SplitButton} config object
8016  */
8017 Roo.Toolbar.SplitButton = function(config){
8018     Roo.Toolbar.SplitButton.superclass.constructor.call(this, null, config);
8019 };
8020 Roo.extend(Roo.Toolbar.SplitButton, Roo.SplitButton, {
8021     render : function(td){
8022         this.td = td;
8023         Roo.Toolbar.SplitButton.superclass.render.call(this, td);
8024     },
8025     
8026     /**
8027      * Removes and destroys this button
8028      */
8029     destroy : function(){
8030         Roo.Toolbar.SplitButton.superclass.destroy.call(this);
8031         this.td.parentNode.removeChild(this.td);
8032     },
8033     
8034     /**
8035      * Shows this button
8036      */
8037     show: function(){
8038         this.hidden = false;
8039         this.td.style.display = "";
8040     },
8041     
8042     /**
8043      * Hides this button
8044      */
8045     hide: function(){
8046         this.hidden = true;
8047         this.td.style.display = "none";
8048     }
8049 });
8050
8051 // backwards compat
8052 Roo.Toolbar.MenuButton = Roo.Toolbar.SplitButton;/*
8053  * Based on:
8054  * Ext JS Library 1.1.1
8055  * Copyright(c) 2006-2007, Ext JS, LLC.
8056  *
8057  * Originally Released Under LGPL - original licence link has changed is not relivant.
8058  *
8059  * Fork - LGPL
8060  * <script type="text/javascript">
8061  */
8062  
8063 /**
8064  * @class Roo.PagingToolbar
8065  * @extends Roo.Toolbar
8066  * A specialized toolbar that is bound to a {@link Roo.data.Store} and provides automatic paging controls.
8067  * @constructor
8068  * Create a new PagingToolbar
8069  * @param {Object} config The config object
8070  */
8071 Roo.PagingToolbar = function(el, ds, config)
8072 {
8073     // old args format still supported... - xtype is prefered..
8074     if (typeof(el) == 'object' && el.xtype) {
8075         // created from xtype...
8076         config = el;
8077         ds = el.dataSource;
8078         el = config.container;
8079     }
8080     var items = [];
8081     if (config.items) {
8082         items = config.items;
8083         config.items = [];
8084     }
8085     
8086     Roo.PagingToolbar.superclass.constructor.call(this, el, null, config);
8087     this.ds = ds;
8088     this.cursor = 0;
8089     this.renderButtons(this.el);
8090     this.bind(ds);
8091     
8092     // supprot items array.
8093    
8094     Roo.each(items, function(e) {
8095         this.add(Roo.factory(e));
8096     },this);
8097     
8098 };
8099
8100 Roo.extend(Roo.PagingToolbar, Roo.Toolbar, {
8101     /**
8102      * @cfg {Roo.data.Store} dataSource
8103      * The underlying data store providing the paged data
8104      */
8105     /**
8106      * @cfg {String/HTMLElement/Element} container
8107      * container The id or element that will contain the toolbar
8108      */
8109     /**
8110      * @cfg {Boolean} displayInfo
8111      * True to display the displayMsg (defaults to false)
8112      */
8113     /**
8114      * @cfg {Number} pageSize
8115      * The number of records to display per page (defaults to 20)
8116      */
8117     pageSize: 20,
8118     /**
8119      * @cfg {String} displayMsg
8120      * The paging status message to display (defaults to "Displaying {start} - {end} of {total}")
8121      */
8122     displayMsg : 'Displaying {0} - {1} of {2}',
8123     /**
8124      * @cfg {String} emptyMsg
8125      * The message to display when no records are found (defaults to "No data to display")
8126      */
8127     emptyMsg : 'No data to display',
8128     /**
8129      * Customizable piece of the default paging text (defaults to "Page")
8130      * @type String
8131      */
8132     beforePageText : "Page",
8133     /**
8134      * Customizable piece of the default paging text (defaults to "of %0")
8135      * @type String
8136      */
8137     afterPageText : "of {0}",
8138     /**
8139      * Customizable piece of the default paging text (defaults to "First Page")
8140      * @type String
8141      */
8142     firstText : "First Page",
8143     /**
8144      * Customizable piece of the default paging text (defaults to "Previous Page")
8145      * @type String
8146      */
8147     prevText : "Previous Page",
8148     /**
8149      * Customizable piece of the default paging text (defaults to "Next Page")
8150      * @type String
8151      */
8152     nextText : "Next Page",
8153     /**
8154      * Customizable piece of the default paging text (defaults to "Last Page")
8155      * @type String
8156      */
8157     lastText : "Last Page",
8158     /**
8159      * Customizable piece of the default paging text (defaults to "Refresh")
8160      * @type String
8161      */
8162     refreshText : "Refresh",
8163
8164     // private
8165     renderButtons : function(el){
8166         Roo.PagingToolbar.superclass.render.call(this, el);
8167         this.first = this.addButton({
8168             tooltip: this.firstText,
8169             cls: "x-btn-icon x-grid-page-first",
8170             disabled: true,
8171             handler: this.onClick.createDelegate(this, ["first"])
8172         });
8173         this.prev = this.addButton({
8174             tooltip: this.prevText,
8175             cls: "x-btn-icon x-grid-page-prev",
8176             disabled: true,
8177             handler: this.onClick.createDelegate(this, ["prev"])
8178         });
8179         //this.addSeparator();
8180         this.add(this.beforePageText);
8181         this.field = Roo.get(this.addDom({
8182            tag: "input",
8183            type: "text",
8184            size: "3",
8185            value: "1",
8186            cls: "x-grid-page-number"
8187         }).el);
8188         this.field.on("keydown", this.onPagingKeydown, this);
8189         this.field.on("focus", function(){this.dom.select();});
8190         this.afterTextEl = this.addText(String.format(this.afterPageText, 1));
8191         this.field.setHeight(18);
8192         //this.addSeparator();
8193         this.next = this.addButton({
8194             tooltip: this.nextText,
8195             cls: "x-btn-icon x-grid-page-next",
8196             disabled: true,
8197             handler: this.onClick.createDelegate(this, ["next"])
8198         });
8199         this.last = this.addButton({
8200             tooltip: this.lastText,
8201             cls: "x-btn-icon x-grid-page-last",
8202             disabled: true,
8203             handler: this.onClick.createDelegate(this, ["last"])
8204         });
8205         //this.addSeparator();
8206         this.loading = this.addButton({
8207             tooltip: this.refreshText,
8208             cls: "x-btn-icon x-grid-loading",
8209             handler: this.onClick.createDelegate(this, ["refresh"])
8210         });
8211
8212         if(this.displayInfo){
8213             this.displayEl = Roo.fly(this.el.dom.firstChild).createChild({cls:'x-paging-info'});
8214         }
8215     },
8216
8217     // private
8218     updateInfo : function(){
8219         if(this.displayEl){
8220             var count = this.ds.getCount();
8221             var msg = count == 0 ?
8222                 this.emptyMsg :
8223                 String.format(
8224                     this.displayMsg,
8225                     this.cursor+1, this.cursor+count, this.ds.getTotalCount()    
8226                 );
8227             this.displayEl.update(msg);
8228         }
8229     },
8230
8231     // private
8232     onLoad : function(ds, r, o){
8233        this.cursor = o.params ? o.params.start : 0;
8234        var d = this.getPageData(), ap = d.activePage, ps = d.pages;
8235
8236        this.afterTextEl.el.innerHTML = String.format(this.afterPageText, d.pages);
8237        this.field.dom.value = ap;
8238        this.first.setDisabled(ap == 1);
8239        this.prev.setDisabled(ap == 1);
8240        this.next.setDisabled(ap == ps);
8241        this.last.setDisabled(ap == ps);
8242        this.loading.enable();
8243        this.updateInfo();
8244     },
8245
8246     // private
8247     getPageData : function(){
8248         var total = this.ds.getTotalCount();
8249         return {
8250             total : total,
8251             activePage : Math.ceil((this.cursor+this.pageSize)/this.pageSize),
8252             pages :  total < this.pageSize ? 1 : Math.ceil(total/this.pageSize)
8253         };
8254     },
8255
8256     // private
8257     onLoadError : function(){
8258         this.loading.enable();
8259     },
8260
8261     // private
8262     onPagingKeydown : function(e){
8263         var k = e.getKey();
8264         var d = this.getPageData();
8265         if(k == e.RETURN){
8266             var v = this.field.dom.value, pageNum;
8267             if(!v || isNaN(pageNum = parseInt(v, 10))){
8268                 this.field.dom.value = d.activePage;
8269                 return;
8270             }
8271             pageNum = Math.min(Math.max(1, pageNum), d.pages) - 1;
8272             this.ds.load({params:{start: pageNum * this.pageSize, limit: this.pageSize}});
8273             e.stopEvent();
8274         }
8275         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))
8276         {
8277           var pageNum = (k == e.HOME || (k == e.DOWN && e.ctrlKey) || (k == e.LEFT && e.ctrlKey) || (k == e.PAGEDOWN && e.ctrlKey)) ? 1 : d.pages;
8278           this.field.dom.value = pageNum;
8279           this.ds.load({params:{start: (pageNum - 1) * this.pageSize, limit: this.pageSize}});
8280           e.stopEvent();
8281         }
8282         else if(k == e.UP || k == e.RIGHT || k == e.PAGEUP || k == e.DOWN || k == e.LEFT || k == e.PAGEDOWN)
8283         {
8284           var v = this.field.dom.value, pageNum; 
8285           var increment = (e.shiftKey) ? 10 : 1;
8286           if(k == e.DOWN || k == e.LEFT || k == e.PAGEDOWN) {
8287             increment *= -1;
8288           }
8289           if(!v || isNaN(pageNum = parseInt(v, 10))) {
8290             this.field.dom.value = d.activePage;
8291             return;
8292           }
8293           else if(parseInt(v, 10) + increment >= 1 & parseInt(v, 10) + increment <= d.pages)
8294           {
8295             this.field.dom.value = parseInt(v, 10) + increment;
8296             pageNum = Math.min(Math.max(1, pageNum + increment), d.pages) - 1;
8297             this.ds.load({params:{start: pageNum * this.pageSize, limit: this.pageSize}});
8298           }
8299           e.stopEvent();
8300         }
8301     },
8302
8303     // private
8304     beforeLoad : function(){
8305         if(this.loading){
8306             this.loading.disable();
8307         }
8308     },
8309
8310     // private
8311     onClick : function(which){
8312         var ds = this.ds;
8313         switch(which){
8314             case "first":
8315                 ds.load({params:{start: 0, limit: this.pageSize}});
8316             break;
8317             case "prev":
8318                 ds.load({params:{start: Math.max(0, this.cursor-this.pageSize), limit: this.pageSize}});
8319             break;
8320             case "next":
8321                 ds.load({params:{start: this.cursor+this.pageSize, limit: this.pageSize}});
8322             break;
8323             case "last":
8324                 var total = ds.getTotalCount();
8325                 var extra = total % this.pageSize;
8326                 var lastStart = extra ? (total - extra) : total-this.pageSize;
8327                 ds.load({params:{start: lastStart, limit: this.pageSize}});
8328             break;
8329             case "refresh":
8330                 ds.load({params:{start: this.cursor, limit: this.pageSize}});
8331             break;
8332         }
8333     },
8334
8335     /**
8336      * Unbinds the paging toolbar from the specified {@link Roo.data.Store}
8337      * @param {Roo.data.Store} store The data store to unbind
8338      */
8339     unbind : function(ds){
8340         ds.un("beforeload", this.beforeLoad, this);
8341         ds.un("load", this.onLoad, this);
8342         ds.un("loadexception", this.onLoadError, this);
8343         ds.un("remove", this.updateInfo, this);
8344         ds.un("add", this.updateInfo, this);
8345         this.ds = undefined;
8346     },
8347
8348     /**
8349      * Binds the paging toolbar to the specified {@link Roo.data.Store}
8350      * @param {Roo.data.Store} store The data store to bind
8351      */
8352     bind : function(ds){
8353         ds.on("beforeload", this.beforeLoad, this);
8354         ds.on("load", this.onLoad, this);
8355         ds.on("loadexception", this.onLoadError, this);
8356         ds.on("remove", this.updateInfo, this);
8357         ds.on("add", this.updateInfo, this);
8358         this.ds = ds;
8359     }
8360 });/*
8361  * Based on:
8362  * Ext JS Library 1.1.1
8363  * Copyright(c) 2006-2007, Ext JS, LLC.
8364  *
8365  * Originally Released Under LGPL - original licence link has changed is not relivant.
8366  *
8367  * Fork - LGPL
8368  * <script type="text/javascript">
8369  */
8370
8371 /**
8372  * @class Roo.Resizable
8373  * @extends Roo.util.Observable
8374  * <p>Applies drag handles to an element to make it resizable. The drag handles are inserted into the element
8375  * and positioned absolute. Some elements, such as a textarea or image, don't support this. To overcome that, you can wrap
8376  * 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
8377  * the element will be wrapped for you automatically.</p>
8378  * <p>Here is the list of valid resize handles:</p>
8379  * <pre>
8380 Value   Description
8381 ------  -------------------
8382  'n'     north
8383  's'     south
8384  'e'     east
8385  'w'     west
8386  'nw'    northwest
8387  'sw'    southwest
8388  'se'    southeast
8389  'ne'    northeast
8390  'hd'    horizontal drag
8391  'all'   all
8392 </pre>
8393  * <p>Here's an example showing the creation of a typical Resizable:</p>
8394  * <pre><code>
8395 var resizer = new Roo.Resizable("element-id", {
8396     handles: 'all',
8397     minWidth: 200,
8398     minHeight: 100,
8399     maxWidth: 500,
8400     maxHeight: 400,
8401     pinned: true
8402 });
8403 resizer.on("resize", myHandler);
8404 </code></pre>
8405  * <p>To hide a particular handle, set its display to none in CSS, or through script:<br>
8406  * resizer.east.setDisplayed(false);</p>
8407  * @cfg {Boolean/String/Element} resizeChild True to resize the first child, or id/element to resize (defaults to false)
8408  * @cfg {Array/String} adjustments String "auto" or an array [width, height] with values to be <b>added</b> to the
8409  * resize operation's new size (defaults to [0, 0])
8410  * @cfg {Number} minWidth The minimum width for the element (defaults to 5)
8411  * @cfg {Number} minHeight The minimum height for the element (defaults to 5)
8412  * @cfg {Number} maxWidth The maximum width for the element (defaults to 10000)
8413  * @cfg {Number} maxHeight The maximum height for the element (defaults to 10000)
8414  * @cfg {Boolean} enabled False to disable resizing (defaults to true)
8415  * @cfg {Boolean} wrap True to wrap an element with a div if needed (required for textareas and images, defaults to false)
8416  * @cfg {Number} width The width of the element in pixels (defaults to null)
8417  * @cfg {Number} height The height of the element in pixels (defaults to null)
8418  * @cfg {Boolean} animate True to animate the resize (not compatible with dynamic sizing, defaults to false)
8419  * @cfg {Number} duration Animation duration if animate = true (defaults to .35)
8420  * @cfg {Boolean} dynamic True to resize the element while dragging instead of using a proxy (defaults to false)
8421  * @cfg {String} handles String consisting of the resize handles to display (defaults to undefined)
8422  * @cfg {Boolean} multiDirectional <b>Deprecated</b>.  The old style of adding multi-direction resize handles, deprecated
8423  * in favor of the handles config option (defaults to false)
8424  * @cfg {Boolean} disableTrackOver True to disable mouse tracking. This is only applied at config time. (defaults to false)
8425  * @cfg {String} easing Animation easing if animate = true (defaults to 'easingOutStrong')
8426  * @cfg {Number} widthIncrement The increment to snap the width resize in pixels (dynamic must be true, defaults to 0)
8427  * @cfg {Number} heightIncrement The increment to snap the height resize in pixels (dynamic must be true, defaults to 0)
8428  * @cfg {Boolean} pinned True to ensure that the resize handles are always visible, false to display them only when the
8429  * user mouses over the resizable borders. This is only applied at config time. (defaults to false)
8430  * @cfg {Boolean} preserveRatio True to preserve the original ratio between height and width during resize (defaults to false)
8431  * @cfg {Boolean} transparent True for transparent handles. This is only applied at config time. (defaults to false)
8432  * @cfg {Number} minX The minimum allowed page X for the element (only used for west resizing, defaults to 0)
8433  * @cfg {Number} minY The minimum allowed page Y for the element (only used for north resizing, defaults to 0)
8434  * @cfg {Boolean} draggable Convenience to initialize drag drop (defaults to false)
8435  * @constructor
8436  * Create a new resizable component
8437  * @param {String/HTMLElement/Roo.Element} el The id or element to resize
8438  * @param {Object} config configuration options
8439   */
8440 Roo.Resizable = function(el, config)
8441 {
8442     this.el = Roo.get(el);
8443
8444     if(config && config.wrap){
8445         config.resizeChild = this.el;
8446         this.el = this.el.wrap(typeof config.wrap == "object" ? config.wrap : {cls:"xresizable-wrap"});
8447         this.el.id = this.el.dom.id = config.resizeChild.id + "-rzwrap";
8448         this.el.setStyle("overflow", "hidden");
8449         this.el.setPositioning(config.resizeChild.getPositioning());
8450         config.resizeChild.clearPositioning();
8451         if(!config.width || !config.height){
8452             var csize = config.resizeChild.getSize();
8453             this.el.setSize(csize.width, csize.height);
8454         }
8455         if(config.pinned && !config.adjustments){
8456             config.adjustments = "auto";
8457         }
8458     }
8459
8460     this.proxy = this.el.createProxy({tag: "div", cls: "x-resizable-proxy", id: this.el.id + "-rzproxy"});
8461     this.proxy.unselectable();
8462     this.proxy.enableDisplayMode('block');
8463
8464     Roo.apply(this, config);
8465
8466     if(this.pinned){
8467         this.disableTrackOver = true;
8468         this.el.addClass("x-resizable-pinned");
8469     }
8470     // if the element isn't positioned, make it relative
8471     var position = this.el.getStyle("position");
8472     if(position != "absolute" && position != "fixed"){
8473         this.el.setStyle("position", "relative");
8474     }
8475     if(!this.handles){ // no handles passed, must be legacy style
8476         this.handles = 's,e,se';
8477         if(this.multiDirectional){
8478             this.handles += ',n,w';
8479         }
8480     }
8481     if(this.handles == "all"){
8482         this.handles = "n s e w ne nw se sw";
8483     }
8484     var hs = this.handles.split(/\s*?[,;]\s*?| /);
8485     var ps = Roo.Resizable.positions;
8486     for(var i = 0, len = hs.length; i < len; i++){
8487         if(hs[i] && ps[hs[i]]){
8488             var pos = ps[hs[i]];
8489             this[pos] = new Roo.Resizable.Handle(this, pos, this.disableTrackOver, this.transparent);
8490         }
8491     }
8492     // legacy
8493     this.corner = this.southeast;
8494     
8495     // updateBox = the box can move..
8496     if(this.handles.indexOf("n") != -1 || this.handles.indexOf("w") != -1 || this.handles.indexOf("hd") != -1) {
8497         this.updateBox = true;
8498     }
8499
8500     this.activeHandle = null;
8501
8502     if(this.resizeChild){
8503         if(typeof this.resizeChild == "boolean"){
8504             this.resizeChild = Roo.get(this.el.dom.firstChild, true);
8505         }else{
8506             this.resizeChild = Roo.get(this.resizeChild, true);
8507         }
8508     }
8509     
8510     if(this.adjustments == "auto"){
8511         var rc = this.resizeChild;
8512         var hw = this.west, he = this.east, hn = this.north, hs = this.south;
8513         if(rc && (hw || hn)){
8514             rc.position("relative");
8515             rc.setLeft(hw ? hw.el.getWidth() : 0);
8516             rc.setTop(hn ? hn.el.getHeight() : 0);
8517         }
8518         this.adjustments = [
8519             (he ? -he.el.getWidth() : 0) + (hw ? -hw.el.getWidth() : 0),
8520             (hn ? -hn.el.getHeight() : 0) + (hs ? -hs.el.getHeight() : 0) -1
8521         ];
8522     }
8523
8524     if(this.draggable){
8525         this.dd = this.dynamic ?
8526             this.el.initDD(null) : this.el.initDDProxy(null, {dragElId: this.proxy.id});
8527         this.dd.setHandleElId(this.resizeChild ? this.resizeChild.id : this.el.id);
8528     }
8529
8530     // public events
8531     this.addEvents({
8532         /**
8533          * @event beforeresize
8534          * Fired before resize is allowed. Set enabled to false to cancel resize.
8535          * @param {Roo.Resizable} this
8536          * @param {Roo.EventObject} e The mousedown event
8537          */
8538         "beforeresize" : true,
8539         /**
8540          * @event resizing
8541          * Fired a resizing.
8542          * @param {Roo.Resizable} this
8543          * @param {Number} x The new x position
8544          * @param {Number} y The new y position
8545          * @param {Number} w The new w width
8546          * @param {Number} h The new h hight
8547          * @param {Roo.EventObject} e The mouseup event
8548          */
8549         "resizing" : true,
8550         /**
8551          * @event resize
8552          * Fired after a resize.
8553          * @param {Roo.Resizable} this
8554          * @param {Number} width The new width
8555          * @param {Number} height The new height
8556          * @param {Roo.EventObject} e The mouseup event
8557          */
8558         "resize" : true
8559     });
8560
8561     if(this.width !== null && this.height !== null){
8562         this.resizeTo(this.width, this.height);
8563     }else{
8564         this.updateChildSize();
8565     }
8566     if(Roo.isIE){
8567         this.el.dom.style.zoom = 1;
8568     }
8569     Roo.Resizable.superclass.constructor.call(this);
8570 };
8571
8572 Roo.extend(Roo.Resizable, Roo.util.Observable, {
8573         resizeChild : false,
8574         adjustments : [0, 0],
8575         minWidth : 5,
8576         minHeight : 5,
8577         maxWidth : 10000,
8578         maxHeight : 10000,
8579         enabled : true,
8580         animate : false,
8581         duration : .35,
8582         dynamic : false,
8583         handles : false,
8584         multiDirectional : false,
8585         disableTrackOver : false,
8586         easing : 'easeOutStrong',
8587         widthIncrement : 0,
8588         heightIncrement : 0,
8589         pinned : false,
8590         width : null,
8591         height : null,
8592         preserveRatio : false,
8593         transparent: false,
8594         minX: 0,
8595         minY: 0,
8596         draggable: false,
8597
8598         /**
8599          * @cfg {String/HTMLElement/Element} constrainTo Constrain the resize to a particular element
8600          */
8601         constrainTo: undefined,
8602         /**
8603          * @cfg {Roo.lib.Region} resizeRegion Constrain the resize to a particular region
8604          */
8605         resizeRegion: undefined,
8606
8607
8608     /**
8609      * Perform a manual resize
8610      * @param {Number} width
8611      * @param {Number} height
8612      */
8613     resizeTo : function(width, height){
8614         this.el.setSize(width, height);
8615         this.updateChildSize();
8616         this.fireEvent("resize", this, width, height, null);
8617     },
8618
8619     // private
8620     startSizing : function(e, handle){
8621         this.fireEvent("beforeresize", this, e);
8622         if(this.enabled){ // 2nd enabled check in case disabled before beforeresize handler
8623
8624             if(!this.overlay){
8625                 this.overlay = this.el.createProxy({tag: "div", cls: "x-resizable-overlay", html: "&#160;"});
8626                 this.overlay.unselectable();
8627                 this.overlay.enableDisplayMode("block");
8628                 this.overlay.on("mousemove", this.onMouseMove, this);
8629                 this.overlay.on("mouseup", this.onMouseUp, this);
8630             }
8631             this.overlay.setStyle("cursor", handle.el.getStyle("cursor"));
8632
8633             this.resizing = true;
8634             this.startBox = this.el.getBox();
8635             this.startPoint = e.getXY();
8636             this.offsets = [(this.startBox.x + this.startBox.width) - this.startPoint[0],
8637                             (this.startBox.y + this.startBox.height) - this.startPoint[1]];
8638
8639             this.overlay.setSize(Roo.lib.Dom.getViewWidth(true), Roo.lib.Dom.getViewHeight(true));
8640             this.overlay.show();
8641
8642             if(this.constrainTo) {
8643                 var ct = Roo.get(this.constrainTo);
8644                 this.resizeRegion = ct.getRegion().adjust(
8645                     ct.getFrameWidth('t'),
8646                     ct.getFrameWidth('l'),
8647                     -ct.getFrameWidth('b'),
8648                     -ct.getFrameWidth('r')
8649                 );
8650             }
8651
8652             this.proxy.setStyle('visibility', 'hidden'); // workaround display none
8653             this.proxy.show();
8654             this.proxy.setBox(this.startBox);
8655             if(!this.dynamic){
8656                 this.proxy.setStyle('visibility', 'visible');
8657             }
8658         }
8659     },
8660
8661     // private
8662     onMouseDown : function(handle, e){
8663         if(this.enabled){
8664             e.stopEvent();
8665             this.activeHandle = handle;
8666             this.startSizing(e, handle);
8667         }
8668     },
8669
8670     // private
8671     onMouseUp : function(e){
8672         var size = this.resizeElement();
8673         this.resizing = false;
8674         this.handleOut();
8675         this.overlay.hide();
8676         this.proxy.hide();
8677         this.fireEvent("resize", this, size.width, size.height, e);
8678     },
8679
8680     // private
8681     updateChildSize : function(){
8682         
8683         if(this.resizeChild){
8684             var el = this.el;
8685             var child = this.resizeChild;
8686             var adj = this.adjustments;
8687             if(el.dom.offsetWidth){
8688                 var b = el.getSize(true);
8689                 child.setSize(b.width+adj[0], b.height+adj[1]);
8690             }
8691             // Second call here for IE
8692             // The first call enables instant resizing and
8693             // the second call corrects scroll bars if they
8694             // exist
8695             if(Roo.isIE){
8696                 setTimeout(function(){
8697                     if(el.dom.offsetWidth){
8698                         var b = el.getSize(true);
8699                         child.setSize(b.width+adj[0], b.height+adj[1]);
8700                     }
8701                 }, 10);
8702             }
8703         }
8704     },
8705
8706     // private
8707     snap : function(value, inc, min){
8708         if(!inc || !value) {
8709             return value;
8710         }
8711         var newValue = value;
8712         var m = value % inc;
8713         if(m > 0){
8714             if(m > (inc/2)){
8715                 newValue = value + (inc-m);
8716             }else{
8717                 newValue = value - m;
8718             }
8719         }
8720         return Math.max(min, newValue);
8721     },
8722
8723     // private
8724     resizeElement : function(){
8725         var box = this.proxy.getBox();
8726         if(this.updateBox){
8727             this.el.setBox(box, false, this.animate, this.duration, null, this.easing);
8728         }else{
8729             this.el.setSize(box.width, box.height, this.animate, this.duration, null, this.easing);
8730         }
8731         this.updateChildSize();
8732         if(!this.dynamic){
8733             this.proxy.hide();
8734         }
8735         return box;
8736     },
8737
8738     // private
8739     constrain : function(v, diff, m, mx){
8740         if(v - diff < m){
8741             diff = v - m;
8742         }else if(v - diff > mx){
8743             diff = mx - v;
8744         }
8745         return diff;
8746     },
8747
8748     // private
8749     onMouseMove : function(e){
8750         
8751         if(this.enabled){
8752             try{// try catch so if something goes wrong the user doesn't get hung
8753
8754             if(this.resizeRegion && !this.resizeRegion.contains(e.getPoint())) {
8755                 return;
8756             }
8757
8758             //var curXY = this.startPoint;
8759             var curSize = this.curSize || this.startBox;
8760             var x = this.startBox.x, y = this.startBox.y;
8761             var ox = x, oy = y;
8762             var w = curSize.width, h = curSize.height;
8763             var ow = w, oh = h;
8764             var mw = this.minWidth, mh = this.minHeight;
8765             var mxw = this.maxWidth, mxh = this.maxHeight;
8766             var wi = this.widthIncrement;
8767             var hi = this.heightIncrement;
8768
8769             var eventXY = e.getXY();
8770             var diffX = -(this.startPoint[0] - Math.max(this.minX, eventXY[0]));
8771             var diffY = -(this.startPoint[1] - Math.max(this.minY, eventXY[1]));
8772
8773             var pos = this.activeHandle.position;
8774
8775             switch(pos){
8776                 case "east":
8777                     w += diffX;
8778                     w = Math.min(Math.max(mw, w), mxw);
8779                     break;
8780              
8781                 case "south":
8782                     h += diffY;
8783                     h = Math.min(Math.max(mh, h), mxh);
8784                     break;
8785                 case "southeast":
8786                     w += diffX;
8787                     h += diffY;
8788                     w = Math.min(Math.max(mw, w), mxw);
8789                     h = Math.min(Math.max(mh, h), mxh);
8790                     break;
8791                 case "north":
8792                     diffY = this.constrain(h, diffY, mh, mxh);
8793                     y += diffY;
8794                     h -= diffY;
8795                     break;
8796                 case "hdrag":
8797                     
8798                     if (wi) {
8799                         var adiffX = Math.abs(diffX);
8800                         var sub = (adiffX % wi); // how much 
8801                         if (sub > (wi/2)) { // far enough to snap
8802                             diffX = (diffX > 0) ? diffX-sub + wi : diffX+sub - wi;
8803                         } else {
8804                             // remove difference.. 
8805                             diffX = (diffX > 0) ? diffX-sub : diffX+sub;
8806                         }
8807                     }
8808                     x += diffX;
8809                     x = Math.max(this.minX, x);
8810                     break;
8811                 case "west":
8812                     diffX = this.constrain(w, diffX, mw, mxw);
8813                     x += diffX;
8814                     w -= diffX;
8815                     break;
8816                 case "northeast":
8817                     w += diffX;
8818                     w = Math.min(Math.max(mw, w), mxw);
8819                     diffY = this.constrain(h, diffY, mh, mxh);
8820                     y += diffY;
8821                     h -= diffY;
8822                     break;
8823                 case "northwest":
8824                     diffX = this.constrain(w, diffX, mw, mxw);
8825                     diffY = this.constrain(h, diffY, mh, mxh);
8826                     y += diffY;
8827                     h -= diffY;
8828                     x += diffX;
8829                     w -= diffX;
8830                     break;
8831                case "southwest":
8832                     diffX = this.constrain(w, diffX, mw, mxw);
8833                     h += diffY;
8834                     h = Math.min(Math.max(mh, h), mxh);
8835                     x += diffX;
8836                     w -= diffX;
8837                     break;
8838             }
8839
8840             var sw = this.snap(w, wi, mw);
8841             var sh = this.snap(h, hi, mh);
8842             if(sw != w || sh != h){
8843                 switch(pos){
8844                     case "northeast":
8845                         y -= sh - h;
8846                     break;
8847                     case "north":
8848                         y -= sh - h;
8849                         break;
8850                     case "southwest":
8851                         x -= sw - w;
8852                     break;
8853                     case "west":
8854                         x -= sw - w;
8855                         break;
8856                     case "northwest":
8857                         x -= sw - w;
8858                         y -= sh - h;
8859                     break;
8860                 }
8861                 w = sw;
8862                 h = sh;
8863             }
8864
8865             if(this.preserveRatio){
8866                 switch(pos){
8867                     case "southeast":
8868                     case "east":
8869                         h = oh * (w/ow);
8870                         h = Math.min(Math.max(mh, h), mxh);
8871                         w = ow * (h/oh);
8872                        break;
8873                     case "south":
8874                         w = ow * (h/oh);
8875                         w = Math.min(Math.max(mw, w), mxw);
8876                         h = oh * (w/ow);
8877                         break;
8878                     case "northeast":
8879                         w = ow * (h/oh);
8880                         w = Math.min(Math.max(mw, w), mxw);
8881                         h = oh * (w/ow);
8882                     break;
8883                     case "north":
8884                         var tw = w;
8885                         w = ow * (h/oh);
8886                         w = Math.min(Math.max(mw, w), mxw);
8887                         h = oh * (w/ow);
8888                         x += (tw - w) / 2;
8889                         break;
8890                     case "southwest":
8891                         h = oh * (w/ow);
8892                         h = Math.min(Math.max(mh, h), mxh);
8893                         var tw = w;
8894                         w = ow * (h/oh);
8895                         x += tw - w;
8896                         break;
8897                     case "west":
8898                         var th = h;
8899                         h = oh * (w/ow);
8900                         h = Math.min(Math.max(mh, h), mxh);
8901                         y += (th - h) / 2;
8902                         var tw = w;
8903                         w = ow * (h/oh);
8904                         x += tw - w;
8905                        break;
8906                     case "northwest":
8907                         var tw = w;
8908                         var th = h;
8909                         h = oh * (w/ow);
8910                         h = Math.min(Math.max(mh, h), mxh);
8911                         w = ow * (h/oh);
8912                         y += th - h;
8913                         x += tw - w;
8914                        break;
8915
8916                 }
8917             }
8918             if (pos == 'hdrag') {
8919                 w = ow;
8920             }
8921             this.proxy.setBounds(x, y, w, h);
8922             if(this.dynamic){
8923                 this.resizeElement();
8924             }
8925             }catch(e){}
8926         }
8927         this.fireEvent("resizing", this, x, y, w, h, e);
8928     },
8929
8930     // private
8931     handleOver : function(){
8932         if(this.enabled){
8933             this.el.addClass("x-resizable-over");
8934         }
8935     },
8936
8937     // private
8938     handleOut : function(){
8939         if(!this.resizing){
8940             this.el.removeClass("x-resizable-over");
8941         }
8942     },
8943
8944     /**
8945      * Returns the element this component is bound to.
8946      * @return {Roo.Element}
8947      */
8948     getEl : function(){
8949         return this.el;
8950     },
8951
8952     /**
8953      * Returns the resizeChild element (or null).
8954      * @return {Roo.Element}
8955      */
8956     getResizeChild : function(){
8957         return this.resizeChild;
8958     },
8959     groupHandler : function()
8960     {
8961         
8962     },
8963     /**
8964      * Destroys this resizable. If the element was wrapped and
8965      * removeEl is not true then the element remains.
8966      * @param {Boolean} removeEl (optional) true to remove the element from the DOM
8967      */
8968     destroy : function(removeEl){
8969         this.proxy.remove();
8970         if(this.overlay){
8971             this.overlay.removeAllListeners();
8972             this.overlay.remove();
8973         }
8974         var ps = Roo.Resizable.positions;
8975         for(var k in ps){
8976             if(typeof ps[k] != "function" && this[ps[k]]){
8977                 var h = this[ps[k]];
8978                 h.el.removeAllListeners();
8979                 h.el.remove();
8980             }
8981         }
8982         if(removeEl){
8983             this.el.update("");
8984             this.el.remove();
8985         }
8986     }
8987 });
8988
8989 // private
8990 // hash to map config positions to true positions
8991 Roo.Resizable.positions = {
8992     n: "north", s: "south", e: "east", w: "west", se: "southeast", sw: "southwest", nw: "northwest", ne: "northeast", 
8993     hd: "hdrag"
8994 };
8995
8996 // private
8997 Roo.Resizable.Handle = function(rz, pos, disableTrackOver, transparent){
8998     if(!this.tpl){
8999         // only initialize the template if resizable is used
9000         var tpl = Roo.DomHelper.createTemplate(
9001             {tag: "div", cls: "x-resizable-handle x-resizable-handle-{0}"}
9002         );
9003         tpl.compile();
9004         Roo.Resizable.Handle.prototype.tpl = tpl;
9005     }
9006     this.position = pos;
9007     this.rz = rz;
9008     // show north drag fro topdra
9009     var handlepos = pos == 'hdrag' ? 'north' : pos;
9010     
9011     this.el = this.tpl.append(rz.el.dom, [handlepos], true);
9012     if (pos == 'hdrag') {
9013         this.el.setStyle('cursor', 'pointer');
9014     }
9015     this.el.unselectable();
9016     if(transparent){
9017         this.el.setOpacity(0);
9018     }
9019     this.el.on("mousedown", this.onMouseDown, this);
9020     if(!disableTrackOver){
9021         this.el.on("mouseover", this.onMouseOver, this);
9022         this.el.on("mouseout", this.onMouseOut, this);
9023     }
9024 };
9025
9026 // private
9027 Roo.Resizable.Handle.prototype = {
9028     afterResize : function(rz){
9029         Roo.log('after?');
9030         // do nothing
9031     },
9032     // private
9033     onMouseDown : function(e){
9034         this.rz.onMouseDown(this, e);
9035     },
9036     // private
9037     onMouseOver : function(e){
9038         this.rz.handleOver(this, e);
9039     },
9040     // private
9041     onMouseOut : function(e){
9042         this.rz.handleOut(this, e);
9043     }
9044 };/*
9045  * Based on:
9046  * Ext JS Library 1.1.1
9047  * Copyright(c) 2006-2007, Ext JS, LLC.
9048  *
9049  * Originally Released Under LGPL - original licence link has changed is not relivant.
9050  *
9051  * Fork - LGPL
9052  * <script type="text/javascript">
9053  */
9054
9055 /**
9056  * @class Roo.Editor
9057  * @extends Roo.Component
9058  * A base editor field that handles displaying/hiding on demand and has some built-in sizing and event handling logic.
9059  * @constructor
9060  * Create a new Editor
9061  * @param {Roo.form.Field} field The Field object (or descendant)
9062  * @param {Object} config The config object
9063  */
9064 Roo.Editor = function(field, config){
9065     Roo.Editor.superclass.constructor.call(this, config);
9066     this.field = field;
9067     this.addEvents({
9068         /**
9069              * @event beforestartedit
9070              * Fires when editing is initiated, but before the value changes.  Editing can be canceled by returning
9071              * false from the handler of this event.
9072              * @param {Editor} this
9073              * @param {Roo.Element} boundEl The underlying element bound to this editor
9074              * @param {Mixed} value The field value being set
9075              */
9076         "beforestartedit" : true,
9077         /**
9078              * @event startedit
9079              * Fires when this editor is displayed
9080              * @param {Roo.Element} boundEl The underlying element bound to this editor
9081              * @param {Mixed} value The starting field value
9082              */
9083         "startedit" : true,
9084         /**
9085              * @event beforecomplete
9086              * Fires after a change has been made to the field, but before the change is reflected in the underlying
9087              * field.  Saving the change to the field can be canceled by returning false from the handler of this event.
9088              * Note that if the value has not changed and ignoreNoChange = true, the editing will still end but this
9089              * event will not fire since no edit actually occurred.
9090              * @param {Editor} this
9091              * @param {Mixed} value The current field value
9092              * @param {Mixed} startValue The original field value
9093              */
9094         "beforecomplete" : true,
9095         /**
9096              * @event complete
9097              * Fires after editing is complete and any changed value has been written to the underlying field.
9098              * @param {Editor} this
9099              * @param {Mixed} value The current field value
9100              * @param {Mixed} startValue The original field value
9101              */
9102         "complete" : true,
9103         /**
9104          * @event specialkey
9105          * Fires when any key related to navigation (arrows, tab, enter, esc, etc.) is pressed.  You can check
9106          * {@link Roo.EventObject#getKey} to determine which key was pressed.
9107          * @param {Roo.form.Field} this
9108          * @param {Roo.EventObject} e The event object
9109          */
9110         "specialkey" : true
9111     });
9112 };
9113
9114 Roo.extend(Roo.Editor, Roo.Component, {
9115     /**
9116      * @cfg {Boolean/String} autosize
9117      * True for the editor to automatically adopt the size of the underlying field, "width" to adopt the width only,
9118      * or "height" to adopt the height only (defaults to false)
9119      */
9120     /**
9121      * @cfg {Boolean} revertInvalid
9122      * True to automatically revert the field value and cancel the edit when the user completes an edit and the field
9123      * validation fails (defaults to true)
9124      */
9125     /**
9126      * @cfg {Boolean} ignoreNoChange
9127      * True to skip the the edit completion process (no save, no events fired) if the user completes an edit and
9128      * the value has not changed (defaults to false).  Applies only to string values - edits for other data types
9129      * will never be ignored.
9130      */
9131     /**
9132      * @cfg {Boolean} hideEl
9133      * False to keep the bound element visible while the editor is displayed (defaults to true)
9134      */
9135     /**
9136      * @cfg {Mixed} value
9137      * The data value of the underlying field (defaults to "")
9138      */
9139     value : "",
9140     /**
9141      * @cfg {String} alignment
9142      * The position to align to (see {@link Roo.Element#alignTo} for more details, defaults to "c-c?").
9143      */
9144     alignment: "c-c?",
9145     /**
9146      * @cfg {Boolean/String} shadow "sides" for sides/bottom only, "frame" for 4-way shadow, and "drop"
9147      * for bottom-right shadow (defaults to "frame")
9148      */
9149     shadow : "frame",
9150     /**
9151      * @cfg {Boolean} constrain True to constrain the editor to the viewport
9152      */
9153     constrain : false,
9154     /**
9155      * @cfg {Boolean} completeOnEnter True to complete the edit when the enter key is pressed (defaults to false)
9156      */
9157     completeOnEnter : false,
9158     /**
9159      * @cfg {Boolean} cancelOnEsc True to cancel the edit when the escape key is pressed (defaults to false)
9160      */
9161     cancelOnEsc : false,
9162     /**
9163      * @cfg {Boolean} updateEl True to update the innerHTML of the bound element when the update completes (defaults to false)
9164      */
9165     updateEl : false,
9166
9167     // private
9168     onRender : function(ct, position){
9169         this.el = new Roo.Layer({
9170             shadow: this.shadow,
9171             cls: "x-editor",
9172             parentEl : ct,
9173             shim : this.shim,
9174             shadowOffset:4,
9175             id: this.id,
9176             constrain: this.constrain
9177         });
9178         this.el.setStyle("overflow", Roo.isGecko ? "auto" : "hidden");
9179         if(this.field.msgTarget != 'title'){
9180             this.field.msgTarget = 'qtip';
9181         }
9182         this.field.render(this.el);
9183         if(Roo.isGecko){
9184             this.field.el.dom.setAttribute('autocomplete', 'off');
9185         }
9186         this.field.on("specialkey", this.onSpecialKey, this);
9187         if(this.swallowKeys){
9188             this.field.el.swallowEvent(['keydown','keypress']);
9189         }
9190         this.field.show();
9191         this.field.on("blur", this.onBlur, this);
9192         if(this.field.grow){
9193             this.field.on("autosize", this.el.sync,  this.el, {delay:1});
9194         }
9195     },
9196
9197     onSpecialKey : function(field, e)
9198     {
9199         //Roo.log('editor onSpecialKey');
9200         if(this.completeOnEnter && e.getKey() == e.ENTER){
9201             e.stopEvent();
9202             this.completeEdit();
9203             return;
9204         }
9205         // do not fire special key otherwise it might hide close the editor...
9206         if(e.getKey() == e.ENTER){    
9207             return;
9208         }
9209         if(this.cancelOnEsc && e.getKey() == e.ESC){
9210             this.cancelEdit();
9211             return;
9212         } 
9213         this.fireEvent('specialkey', field, e);
9214     
9215     },
9216
9217     /**
9218      * Starts the editing process and shows the editor.
9219      * @param {String/HTMLElement/Element} el The element to edit
9220      * @param {String} value (optional) A value to initialize the editor with. If a value is not provided, it defaults
9221       * to the innerHTML of el.
9222      */
9223     startEdit : function(el, value){
9224         if(this.editing){
9225             this.completeEdit();
9226         }
9227         this.boundEl = Roo.get(el);
9228         var v = value !== undefined ? value : this.boundEl.dom.innerHTML;
9229         if(!this.rendered){
9230             this.render(this.parentEl || document.body);
9231         }
9232         if(this.fireEvent("beforestartedit", this, this.boundEl, v) === false){
9233             return;
9234         }
9235         this.startValue = v;
9236         this.field.setValue(v);
9237         if(this.autoSize){
9238             var sz = this.boundEl.getSize();
9239             switch(this.autoSize){
9240                 case "width":
9241                 this.setSize(sz.width,  "");
9242                 break;
9243                 case "height":
9244                 this.setSize("",  sz.height);
9245                 break;
9246                 default:
9247                 this.setSize(sz.width,  sz.height);
9248             }
9249         }
9250         this.el.alignTo(this.boundEl, this.alignment);
9251         this.editing = true;
9252         if(Roo.QuickTips){
9253             Roo.QuickTips.disable();
9254         }
9255         this.show();
9256     },
9257
9258     /**
9259      * Sets the height and width of this editor.
9260      * @param {Number} width The new width
9261      * @param {Number} height The new height
9262      */
9263     setSize : function(w, h){
9264         this.field.setSize(w, h);
9265         if(this.el){
9266             this.el.sync();
9267         }
9268     },
9269
9270     /**
9271      * Realigns the editor to the bound field based on the current alignment config value.
9272      */
9273     realign : function(){
9274         this.el.alignTo(this.boundEl, this.alignment);
9275     },
9276
9277     /**
9278      * Ends the editing process, persists the changed value to the underlying field, and hides the editor.
9279      * @param {Boolean} remainVisible Override the default behavior and keep the editor visible after edit (defaults to false)
9280      */
9281     completeEdit : function(remainVisible){
9282         if(!this.editing){
9283             return;
9284         }
9285         var v = this.getValue();
9286         if(this.revertInvalid !== false && !this.field.isValid()){
9287             v = this.startValue;
9288             this.cancelEdit(true);
9289         }
9290         if(String(v) === String(this.startValue) && this.ignoreNoChange){
9291             this.editing = false;
9292             this.hide();
9293             return;
9294         }
9295         if(this.fireEvent("beforecomplete", this, v, this.startValue) !== false){
9296             this.editing = false;
9297             if(this.updateEl && this.boundEl){
9298                 this.boundEl.update(v);
9299             }
9300             if(remainVisible !== true){
9301                 this.hide();
9302             }
9303             this.fireEvent("complete", this, v, this.startValue);
9304         }
9305     },
9306
9307     // private
9308     onShow : function(){
9309         this.el.show();
9310         if(this.hideEl !== false){
9311             this.boundEl.hide();
9312         }
9313         this.field.show();
9314         if(Roo.isIE && !this.fixIEFocus){ // IE has problems with focusing the first time
9315             this.fixIEFocus = true;
9316             this.deferredFocus.defer(50, this);
9317         }else{
9318             this.field.focus();
9319         }
9320         this.fireEvent("startedit", this.boundEl, this.startValue);
9321     },
9322
9323     deferredFocus : function(){
9324         if(this.editing){
9325             this.field.focus();
9326         }
9327     },
9328
9329     /**
9330      * Cancels the editing process and hides the editor without persisting any changes.  The field value will be
9331      * reverted to the original starting value.
9332      * @param {Boolean} remainVisible Override the default behavior and keep the editor visible after
9333      * cancel (defaults to false)
9334      */
9335     cancelEdit : function(remainVisible){
9336         if(this.editing){
9337             this.setValue(this.startValue);
9338             if(remainVisible !== true){
9339                 this.hide();
9340             }
9341         }
9342     },
9343
9344     // private
9345     onBlur : function(){
9346         if(this.allowBlur !== true && this.editing){
9347             this.completeEdit();
9348         }
9349     },
9350
9351     // private
9352     onHide : function(){
9353         if(this.editing){
9354             this.completeEdit();
9355             return;
9356         }
9357         this.field.blur();
9358         if(this.field.collapse){
9359             this.field.collapse();
9360         }
9361         this.el.hide();
9362         if(this.hideEl !== false){
9363             this.boundEl.show();
9364         }
9365         if(Roo.QuickTips){
9366             Roo.QuickTips.enable();
9367         }
9368     },
9369
9370     /**
9371      * Sets the data value of the editor
9372      * @param {Mixed} value Any valid value supported by the underlying field
9373      */
9374     setValue : function(v){
9375         this.field.setValue(v);
9376     },
9377
9378     /**
9379      * Gets the data value of the editor
9380      * @return {Mixed} The data value
9381      */
9382     getValue : function(){
9383         return this.field.getValue();
9384     }
9385 });/*
9386  * Based on:
9387  * Ext JS Library 1.1.1
9388  * Copyright(c) 2006-2007, Ext JS, LLC.
9389  *
9390  * Originally Released Under LGPL - original licence link has changed is not relivant.
9391  *
9392  * Fork - LGPL
9393  * <script type="text/javascript">
9394  */
9395  
9396 /**
9397  * @class Roo.BasicDialog
9398  * @extends Roo.util.Observable
9399  * Lightweight Dialog Class.  The code below shows the creation of a typical dialog using existing HTML markup:
9400  * <pre><code>
9401 var dlg = new Roo.BasicDialog("my-dlg", {
9402     height: 200,
9403     width: 300,
9404     minHeight: 100,
9405     minWidth: 150,
9406     modal: true,
9407     proxyDrag: true,
9408     shadow: true
9409 });
9410 dlg.addKeyListener(27, dlg.hide, dlg); // ESC can also close the dialog
9411 dlg.addButton('OK', dlg.hide, dlg);    // Could call a save function instead of hiding
9412 dlg.addButton('Cancel', dlg.hide, dlg);
9413 dlg.show();
9414 </code></pre>
9415   <b>A Dialog should always be a direct child of the body element.</b>
9416  * @cfg {Boolean/DomHelper} autoCreate True to auto create from scratch, or using a DomHelper Object (defaults to false)
9417  * @cfg {String} title Default text to display in the title bar (defaults to null)
9418  * @cfg {Number} width Width of the dialog in pixels (can also be set via CSS).  Determined by browser if unspecified.
9419  * @cfg {Number} height Height of the dialog in pixels (can also be set via CSS).  Determined by browser if unspecified.
9420  * @cfg {Number} x The default left page coordinate of the dialog (defaults to center screen)
9421  * @cfg {Number} y The default top page coordinate of the dialog (defaults to center screen)
9422  * @cfg {String/Element} animateTarget Id or element from which the dialog should animate while opening
9423  * (defaults to null with no animation)
9424  * @cfg {Boolean} resizable False to disable manual dialog resizing (defaults to true)
9425  * @cfg {String} resizeHandles Which resize handles to display - see the {@link Roo.Resizable} handles config
9426  * property for valid values (defaults to 'all')
9427  * @cfg {Number} minHeight The minimum allowable height for a resizable dialog (defaults to 80)
9428  * @cfg {Number} minWidth The minimum allowable width for a resizable dialog (defaults to 200)
9429  * @cfg {Boolean} modal True to show the dialog modally, preventing user interaction with the rest of the page (defaults to false)
9430  * @cfg {Boolean} autoScroll True to allow the dialog body contents to overflow and display scrollbars (defaults to false)
9431  * @cfg {Boolean} closable False to remove the built-in top-right corner close button (defaults to true)
9432  * @cfg {Boolean} collapsible False to remove the built-in top-right corner collapse button (defaults to true)
9433  * @cfg {Boolean} constraintoviewport True to keep the dialog constrained within the visible viewport boundaries (defaults to true)
9434  * @cfg {Boolean} syncHeightBeforeShow True to cause the dimensions to be recalculated before the dialog is shown (defaults to false)
9435  * @cfg {Boolean} draggable False to disable dragging of the dialog within the viewport (defaults to true)
9436  * @cfg {Boolean} autoTabs If true, all elements with class 'x-dlg-tab' will get automatically converted to tabs (defaults to false)
9437  * @cfg {String} tabTag The tag name of tab elements, used when autoTabs = true (defaults to 'div')
9438  * @cfg {Boolean} proxyDrag True to drag a lightweight proxy element rather than the dialog itself, used when
9439  * draggable = true (defaults to false)
9440  * @cfg {Boolean} fixedcenter True to ensure that anytime the dialog is shown or resized it gets centered (defaults to false)
9441  * @cfg {Boolean/String} shadow True or "sides" for the default effect, "frame" for 4-way shadow, and "drop" for bottom-right
9442  * shadow (defaults to false)
9443  * @cfg {Number} shadowOffset The number of pixels to offset the shadow if displayed (defaults to 5)
9444  * @cfg {String} buttonAlign Valid values are "left," "center" and "right" (defaults to "right")
9445  * @cfg {Number} minButtonWidth Minimum width of all dialog buttons (defaults to 75)
9446  * @cfg {Array} buttons Array of buttons
9447  * @cfg {Boolean} shim True to create an iframe shim that prevents selects from showing through (defaults to false)
9448  * @constructor
9449  * Create a new BasicDialog.
9450  * @param {String/HTMLElement/Roo.Element} el The container element or DOM node, or its id
9451  * @param {Object} config Configuration options
9452  */
9453 Roo.BasicDialog = function(el, config){
9454     this.el = Roo.get(el);
9455     var dh = Roo.DomHelper;
9456     if(!this.el && config && config.autoCreate){
9457         if(typeof config.autoCreate == "object"){
9458             if(!config.autoCreate.id){
9459                 config.autoCreate.id = el;
9460             }
9461             this.el = dh.append(document.body,
9462                         config.autoCreate, true);
9463         }else{
9464             this.el = dh.append(document.body,
9465                         {tag: "div", id: el, style:'visibility:hidden;'}, true);
9466         }
9467     }
9468     el = this.el;
9469     el.setDisplayed(true);
9470     el.hide = this.hideAction;
9471     this.id = el.id;
9472     el.addClass("x-dlg");
9473
9474     Roo.apply(this, config);
9475
9476     this.proxy = el.createProxy("x-dlg-proxy");
9477     this.proxy.hide = this.hideAction;
9478     this.proxy.setOpacity(.5);
9479     this.proxy.hide();
9480
9481     if(config.width){
9482         el.setWidth(config.width);
9483     }
9484     if(config.height){
9485         el.setHeight(config.height);
9486     }
9487     this.size = el.getSize();
9488     if(typeof config.x != "undefined" && typeof config.y != "undefined"){
9489         this.xy = [config.x,config.y];
9490     }else{
9491         this.xy = el.getCenterXY(true);
9492     }
9493     /** The header element @type Roo.Element */
9494     this.header = el.child("> .x-dlg-hd");
9495     /** The body element @type Roo.Element */
9496     this.body = el.child("> .x-dlg-bd");
9497     /** The footer element @type Roo.Element */
9498     this.footer = el.child("> .x-dlg-ft");
9499
9500     if(!this.header){
9501         this.header = el.createChild({tag: "div", cls:"x-dlg-hd", html: "&#160;"}, this.body ? this.body.dom : null);
9502     }
9503     if(!this.body){
9504         this.body = el.createChild({tag: "div", cls:"x-dlg-bd"});
9505     }
9506
9507     this.header.unselectable();
9508     if(this.title){
9509         this.header.update(this.title);
9510     }
9511     // this element allows the dialog to be focused for keyboard event
9512     this.focusEl = el.createChild({tag: "a", href:"#", cls:"x-dlg-focus", tabIndex:"-1"});
9513     this.focusEl.swallowEvent("click", true);
9514
9515     this.header.wrap({cls:"x-dlg-hd-right"}).wrap({cls:"x-dlg-hd-left"}, true);
9516
9517     // wrap the body and footer for special rendering
9518     this.bwrap = this.body.wrap({tag: "div", cls:"x-dlg-dlg-body"});
9519     if(this.footer){
9520         this.bwrap.dom.appendChild(this.footer.dom);
9521     }
9522
9523     this.bg = this.el.createChild({
9524         tag: "div", cls:"x-dlg-bg",
9525         html: '<div class="x-dlg-bg-left"><div class="x-dlg-bg-right"><div class="x-dlg-bg-center">&#160;</div></div></div>'
9526     });
9527     this.centerBg = this.bg.child("div.x-dlg-bg-center");
9528
9529
9530     if(this.autoScroll !== false && !this.autoTabs){
9531         this.body.setStyle("overflow", "auto");
9532     }
9533
9534     this.toolbox = this.el.createChild({cls: "x-dlg-toolbox"});
9535
9536     if(this.closable !== false){
9537         this.el.addClass("x-dlg-closable");
9538         this.close = this.toolbox.createChild({cls:"x-dlg-close"});
9539         this.close.on("click", this.closeClick, this);
9540         this.close.addClassOnOver("x-dlg-close-over");
9541     }
9542     if(this.collapsible !== false){
9543         this.collapseBtn = this.toolbox.createChild({cls:"x-dlg-collapse"});
9544         this.collapseBtn.on("click", this.collapseClick, this);
9545         this.collapseBtn.addClassOnOver("x-dlg-collapse-over");
9546         this.header.on("dblclick", this.collapseClick, this);
9547     }
9548     if(this.resizable !== false){
9549         this.el.addClass("x-dlg-resizable");
9550         this.resizer = new Roo.Resizable(el, {
9551             minWidth: this.minWidth || 80,
9552             minHeight:this.minHeight || 80,
9553             handles: this.resizeHandles || "all",
9554             pinned: true
9555         });
9556         this.resizer.on("beforeresize", this.beforeResize, this);
9557         this.resizer.on("resize", this.onResize, this);
9558     }
9559     if(this.draggable !== false){
9560         el.addClass("x-dlg-draggable");
9561         if (!this.proxyDrag) {
9562             var dd = new Roo.dd.DD(el.dom.id, "WindowDrag");
9563         }
9564         else {
9565             var dd = new Roo.dd.DDProxy(el.dom.id, "WindowDrag", {dragElId: this.proxy.id});
9566         }
9567         dd.setHandleElId(this.header.id);
9568         dd.endDrag = this.endMove.createDelegate(this);
9569         dd.startDrag = this.startMove.createDelegate(this);
9570         dd.onDrag = this.onDrag.createDelegate(this);
9571         dd.scroll = false;
9572         this.dd = dd;
9573     }
9574     if(this.modal){
9575         this.mask = dh.append(document.body, {tag: "div", cls:"x-dlg-mask"}, true);
9576         this.mask.enableDisplayMode("block");
9577         this.mask.hide();
9578         this.el.addClass("x-dlg-modal");
9579     }
9580     if(this.shadow){
9581         this.shadow = new Roo.Shadow({
9582             mode : typeof this.shadow == "string" ? this.shadow : "sides",
9583             offset : this.shadowOffset
9584         });
9585     }else{
9586         this.shadowOffset = 0;
9587     }
9588     if(Roo.useShims && this.shim !== false){
9589         this.shim = this.el.createShim();
9590         this.shim.hide = this.hideAction;
9591         this.shim.hide();
9592     }else{
9593         this.shim = false;
9594     }
9595     if(this.autoTabs){
9596         this.initTabs();
9597     }
9598     if (this.buttons) { 
9599         var bts= this.buttons;
9600         this.buttons = [];
9601         Roo.each(bts, function(b) {
9602             this.addButton(b);
9603         }, this);
9604     }
9605     
9606     
9607     this.addEvents({
9608         /**
9609          * @event keydown
9610          * Fires when a key is pressed
9611          * @param {Roo.BasicDialog} this
9612          * @param {Roo.EventObject} e
9613          */
9614         "keydown" : true,
9615         /**
9616          * @event move
9617          * Fires when this dialog is moved by the user.
9618          * @param {Roo.BasicDialog} this
9619          * @param {Number} x The new page X
9620          * @param {Number} y The new page Y
9621          */
9622         "move" : true,
9623         /**
9624          * @event resize
9625          * Fires when this dialog is resized by the user.
9626          * @param {Roo.BasicDialog} this
9627          * @param {Number} width The new width
9628          * @param {Number} height The new height
9629          */
9630         "resize" : true,
9631         /**
9632          * @event beforehide
9633          * Fires before this dialog is hidden.
9634          * @param {Roo.BasicDialog} this
9635          */
9636         "beforehide" : true,
9637         /**
9638          * @event hide
9639          * Fires when this dialog is hidden.
9640          * @param {Roo.BasicDialog} this
9641          */
9642         "hide" : true,
9643         /**
9644          * @event beforeshow
9645          * Fires before this dialog is shown.
9646          * @param {Roo.BasicDialog} this
9647          */
9648         "beforeshow" : true,
9649         /**
9650          * @event show
9651          * Fires when this dialog is shown.
9652          * @param {Roo.BasicDialog} this
9653          */
9654         "show" : true
9655     });
9656     el.on("keydown", this.onKeyDown, this);
9657     el.on("mousedown", this.toFront, this);
9658     Roo.EventManager.onWindowResize(this.adjustViewport, this, true);
9659     this.el.hide();
9660     Roo.DialogManager.register(this);
9661     Roo.BasicDialog.superclass.constructor.call(this);
9662 };
9663
9664 Roo.extend(Roo.BasicDialog, Roo.util.Observable, {
9665     shadowOffset: Roo.isIE ? 6 : 5,
9666     minHeight: 80,
9667     minWidth: 200,
9668     minButtonWidth: 75,
9669     defaultButton: null,
9670     buttonAlign: "right",
9671     tabTag: 'div',
9672     firstShow: true,
9673
9674     /**
9675      * Sets the dialog title text
9676      * @param {String} text The title text to display
9677      * @return {Roo.BasicDialog} this
9678      */
9679     setTitle : function(text){
9680         this.header.update(text);
9681         return this;
9682     },
9683
9684     // private
9685     closeClick : function(){
9686         this.hide();
9687     },
9688
9689     // private
9690     collapseClick : function(){
9691         this[this.collapsed ? "expand" : "collapse"]();
9692     },
9693
9694     /**
9695      * Collapses the dialog to its minimized state (only the title bar is visible).
9696      * Equivalent to the user clicking the collapse dialog button.
9697      */
9698     collapse : function(){
9699         if(!this.collapsed){
9700             this.collapsed = true;
9701             this.el.addClass("x-dlg-collapsed");
9702             this.restoreHeight = this.el.getHeight();
9703             this.resizeTo(this.el.getWidth(), this.header.getHeight());
9704         }
9705     },
9706
9707     /**
9708      * Expands a collapsed dialog back to its normal state.  Equivalent to the user
9709      * clicking the expand dialog button.
9710      */
9711     expand : function(){
9712         if(this.collapsed){
9713             this.collapsed = false;
9714             this.el.removeClass("x-dlg-collapsed");
9715             this.resizeTo(this.el.getWidth(), this.restoreHeight);
9716         }
9717     },
9718
9719     /**
9720      * Reinitializes the tabs component, clearing out old tabs and finding new ones.
9721      * @return {Roo.TabPanel} The tabs component
9722      */
9723     initTabs : function(){
9724         var tabs = this.getTabs();
9725         while(tabs.getTab(0)){
9726             tabs.removeTab(0);
9727         }
9728         this.el.select(this.tabTag+'.x-dlg-tab').each(function(el){
9729             var dom = el.dom;
9730             tabs.addTab(Roo.id(dom), dom.title);
9731             dom.title = "";
9732         });
9733         tabs.activate(0);
9734         return tabs;
9735     },
9736
9737     // private
9738     beforeResize : function(){
9739         this.resizer.minHeight = Math.max(this.minHeight, this.getHeaderFooterHeight(true)+40);
9740     },
9741
9742     // private
9743     onResize : function(){
9744         this.refreshSize();
9745         this.syncBodyHeight();
9746         this.adjustAssets();
9747         this.focus();
9748         this.fireEvent("resize", this, this.size.width, this.size.height);
9749     },
9750
9751     // private
9752     onKeyDown : function(e){
9753         if(this.isVisible()){
9754             this.fireEvent("keydown", this, e);
9755         }
9756     },
9757
9758     /**
9759      * Resizes the dialog.
9760      * @param {Number} width
9761      * @param {Number} height
9762      * @return {Roo.BasicDialog} this
9763      */
9764     resizeTo : function(width, height){
9765         this.el.setSize(width, height);
9766         this.size = {width: width, height: height};
9767         this.syncBodyHeight();
9768         if(this.fixedcenter){
9769             this.center();
9770         }
9771         if(this.isVisible()){
9772             this.constrainXY();
9773             this.adjustAssets();
9774         }
9775         this.fireEvent("resize", this, width, height);
9776         return this;
9777     },
9778
9779
9780     /**
9781      * Resizes the dialog to fit the specified content size.
9782      * @param {Number} width
9783      * @param {Number} height
9784      * @return {Roo.BasicDialog} this
9785      */
9786     setContentSize : function(w, h){
9787         h += this.getHeaderFooterHeight() + this.body.getMargins("tb");
9788         w += this.body.getMargins("lr") + this.bwrap.getMargins("lr") + this.centerBg.getPadding("lr");
9789         //if(!this.el.isBorderBox()){
9790             h +=  this.body.getPadding("tb") + this.bwrap.getBorderWidth("tb") + this.body.getBorderWidth("tb") + this.el.getBorderWidth("tb");
9791             w += this.body.getPadding("lr") + this.bwrap.getBorderWidth("lr") + this.body.getBorderWidth("lr") + this.bwrap.getPadding("lr") + this.el.getBorderWidth("lr");
9792         //}
9793         if(this.tabs){
9794             h += this.tabs.stripWrap.getHeight() + this.tabs.bodyEl.getMargins("tb") + this.tabs.bodyEl.getPadding("tb");
9795             w += this.tabs.bodyEl.getMargins("lr") + this.tabs.bodyEl.getPadding("lr");
9796         }
9797         this.resizeTo(w, h);
9798         return this;
9799     },
9800
9801     /**
9802      * Adds a key listener for when this dialog is displayed.  This allows you to hook in a function that will be
9803      * executed in response to a particular key being pressed while the dialog is active.
9804      * @param {Number/Array/Object} key Either the numeric key code, array of key codes or an object with the following options:
9805      *                                  {key: (number or array), shift: (true/false), ctrl: (true/false), alt: (true/false)}
9806      * @param {Function} fn The function to call
9807      * @param {Object} scope (optional) The scope of the function
9808      * @return {Roo.BasicDialog} this
9809      */
9810     addKeyListener : function(key, fn, scope){
9811         var keyCode, shift, ctrl, alt;
9812         if(typeof key == "object" && !(key instanceof Array)){
9813             keyCode = key["key"];
9814             shift = key["shift"];
9815             ctrl = key["ctrl"];
9816             alt = key["alt"];
9817         }else{
9818             keyCode = key;
9819         }
9820         var handler = function(dlg, e){
9821             if((!shift || e.shiftKey) && (!ctrl || e.ctrlKey) &&  (!alt || e.altKey)){
9822                 var k = e.getKey();
9823                 if(keyCode instanceof Array){
9824                     for(var i = 0, len = keyCode.length; i < len; i++){
9825                         if(keyCode[i] == k){
9826                           fn.call(scope || window, dlg, k, e);
9827                           return;
9828                         }
9829                     }
9830                 }else{
9831                     if(k == keyCode){
9832                         fn.call(scope || window, dlg, k, e);
9833                     }
9834                 }
9835             }
9836         };
9837         this.on("keydown", handler);
9838         return this;
9839     },
9840
9841     /**
9842      * Returns the TabPanel component (creates it if it doesn't exist).
9843      * Note: If you wish to simply check for the existence of tabs without creating them,
9844      * check for a null 'tabs' property.
9845      * @return {Roo.TabPanel} The tabs component
9846      */
9847     getTabs : function(){
9848         if(!this.tabs){
9849             this.el.addClass("x-dlg-auto-tabs");
9850             this.body.addClass(this.tabPosition == "bottom" ? "x-tabs-bottom" : "x-tabs-top");
9851             this.tabs = new Roo.TabPanel(this.body.dom, this.tabPosition == "bottom");
9852         }
9853         return this.tabs;
9854     },
9855
9856     /**
9857      * Adds a button to the footer section of the dialog.
9858      * @param {String/Object} config A string becomes the button text, an object can either be a Button config
9859      * object or a valid Roo.DomHelper element config
9860      * @param {Function} handler The function called when the button is clicked
9861      * @param {Object} scope (optional) The scope of the handler function (accepts position as a property)
9862      * @return {Roo.Button} The new button
9863      */
9864     addButton : function(config, handler, scope){
9865         var dh = Roo.DomHelper;
9866         if(!this.footer){
9867             this.footer = dh.append(this.bwrap, {tag: "div", cls:"x-dlg-ft"}, true);
9868         }
9869         if(!this.btnContainer){
9870             var tb = this.footer.createChild({
9871
9872                 cls:"x-dlg-btns x-dlg-btns-"+this.buttonAlign,
9873                 html:'<table cellspacing="0"><tbody><tr></tr></tbody></table><div class="x-clear"></div>'
9874             }, null, true);
9875             this.btnContainer = tb.firstChild.firstChild.firstChild;
9876         }
9877         var bconfig = {
9878             handler: handler,
9879             scope: scope,
9880             minWidth: this.minButtonWidth,
9881             hideParent:true
9882         };
9883         if(typeof config == "string"){
9884             bconfig.text = config;
9885         }else{
9886             if(config.tag){
9887                 bconfig.dhconfig = config;
9888             }else{
9889                 Roo.apply(bconfig, config);
9890             }
9891         }
9892         var fc = false;
9893         if ((typeof(bconfig.position) != 'undefined') && bconfig.position < this.btnContainer.childNodes.length-1) {
9894             bconfig.position = Math.max(0, bconfig.position);
9895             fc = this.btnContainer.childNodes[bconfig.position];
9896         }
9897          
9898         var btn = new Roo.Button(
9899             fc ? 
9900                 this.btnContainer.insertBefore(document.createElement("td"),fc)
9901                 : this.btnContainer.appendChild(document.createElement("td")),
9902             //Roo.get(this.btnContainer).createChild( { tag: 'td'},  fc ),
9903             bconfig
9904         );
9905         this.syncBodyHeight();
9906         if(!this.buttons){
9907             /**
9908              * Array of all the buttons that have been added to this dialog via addButton
9909              * @type Array
9910              */
9911             this.buttons = [];
9912         }
9913         this.buttons.push(btn);
9914         return btn;
9915     },
9916
9917     /**
9918      * Sets the default button to be focused when the dialog is displayed.
9919      * @param {Roo.BasicDialog.Button} btn The button object returned by {@link #addButton}
9920      * @return {Roo.BasicDialog} this
9921      */
9922     setDefaultButton : function(btn){
9923         this.defaultButton = btn;
9924         return this;
9925     },
9926
9927     // private
9928     getHeaderFooterHeight : function(safe){
9929         var height = 0;
9930         if(this.header){
9931            height += this.header.getHeight();
9932         }
9933         if(this.footer){
9934            var fm = this.footer.getMargins();
9935             height += (this.footer.getHeight()+fm.top+fm.bottom);
9936         }
9937         height += this.bwrap.getPadding("tb")+this.bwrap.getBorderWidth("tb");
9938         height += this.centerBg.getPadding("tb");
9939         return height;
9940     },
9941
9942     // private
9943     syncBodyHeight : function()
9944     {
9945         var bd = this.body, // the text
9946             cb = this.centerBg, // wrapper around bottom.. but does not seem to be used..
9947             bw = this.bwrap;
9948         var height = this.size.height - this.getHeaderFooterHeight(false);
9949         bd.setHeight(height-bd.getMargins("tb"));
9950         var hh = this.header.getHeight();
9951         var h = this.size.height-hh;
9952         cb.setHeight(h);
9953         
9954         bw.setLeftTop(cb.getPadding("l"), hh+cb.getPadding("t"));
9955         bw.setHeight(h-cb.getPadding("tb"));
9956         
9957         bw.setWidth(this.el.getWidth(true)-cb.getPadding("lr"));
9958         bd.setWidth(bw.getWidth(true));
9959         if(this.tabs){
9960             this.tabs.syncHeight();
9961             if(Roo.isIE){
9962                 this.tabs.el.repaint();
9963             }
9964         }
9965     },
9966
9967     /**
9968      * Restores the previous state of the dialog if Roo.state is configured.
9969      * @return {Roo.BasicDialog} this
9970      */
9971     restoreState : function(){
9972         var box = Roo.state.Manager.get(this.stateId || (this.el.id + "-state"));
9973         if(box && box.width){
9974             this.xy = [box.x, box.y];
9975             this.resizeTo(box.width, box.height);
9976         }
9977         return this;
9978     },
9979
9980     // private
9981     beforeShow : function(){
9982         this.expand();
9983         if(this.fixedcenter){
9984             this.xy = this.el.getCenterXY(true);
9985         }
9986         if(this.modal){
9987             Roo.get(document.body).addClass("x-body-masked");
9988             this.mask.setSize(Roo.lib.Dom.getViewWidth(true), Roo.lib.Dom.getViewHeight(true));
9989             this.mask.show();
9990         }
9991         this.constrainXY();
9992     },
9993
9994     // private
9995     animShow : function(){
9996         var b = Roo.get(this.animateTarget).getBox();
9997         this.proxy.setSize(b.width, b.height);
9998         this.proxy.setLocation(b.x, b.y);
9999         this.proxy.show();
10000         this.proxy.setBounds(this.xy[0], this.xy[1], this.size.width, this.size.height,
10001                     true, .35, this.showEl.createDelegate(this));
10002     },
10003
10004     /**
10005      * Shows the dialog.
10006      * @param {String/HTMLElement/Roo.Element} animateTarget (optional) Reset the animation target
10007      * @return {Roo.BasicDialog} this
10008      */
10009     show : function(animateTarget){
10010         if (this.fireEvent("beforeshow", this) === false){
10011             return;
10012         }
10013         if(this.syncHeightBeforeShow){
10014             this.syncBodyHeight();
10015         }else if(this.firstShow){
10016             this.firstShow = false;
10017             this.syncBodyHeight(); // sync the height on the first show instead of in the constructor
10018         }
10019         this.animateTarget = animateTarget || this.animateTarget;
10020         if(!this.el.isVisible()){
10021             this.beforeShow();
10022             if(this.animateTarget && Roo.get(this.animateTarget)){
10023                 this.animShow();
10024             }else{
10025                 this.showEl();
10026             }
10027         }
10028         return this;
10029     },
10030
10031     // private
10032     showEl : function(){
10033         this.proxy.hide();
10034         this.el.setXY(this.xy);
10035         this.el.show();
10036         this.adjustAssets(true);
10037         this.toFront();
10038         this.focus();
10039         // IE peekaboo bug - fix found by Dave Fenwick
10040         if(Roo.isIE){
10041             this.el.repaint();
10042         }
10043         this.fireEvent("show", this);
10044     },
10045
10046     /**
10047      * Focuses the dialog.  If a defaultButton is set, it will receive focus, otherwise the
10048      * dialog itself will receive focus.
10049      */
10050     focus : function(){
10051         if(this.defaultButton){
10052             this.defaultButton.focus();
10053         }else{
10054             this.focusEl.focus();
10055         }
10056     },
10057
10058     // private
10059     constrainXY : function(){
10060         if(this.constraintoviewport !== false){
10061             if(!this.viewSize){
10062                 if(this.container){
10063                     var s = this.container.getSize();
10064                     this.viewSize = [s.width, s.height];
10065                 }else{
10066                     this.viewSize = [Roo.lib.Dom.getViewWidth(),Roo.lib.Dom.getViewHeight()];
10067                 }
10068             }
10069             var s = Roo.get(this.container||document).getScroll();
10070
10071             var x = this.xy[0], y = this.xy[1];
10072             var w = this.size.width, h = this.size.height;
10073             var vw = this.viewSize[0], vh = this.viewSize[1];
10074             // only move it if it needs it
10075             var moved = false;
10076             // first validate right/bottom
10077             if(x + w > vw+s.left){
10078                 x = vw - w;
10079                 moved = true;
10080             }
10081             if(y + h > vh+s.top){
10082                 y = vh - h;
10083                 moved = true;
10084             }
10085             // then make sure top/left isn't negative
10086             if(x < s.left){
10087                 x = s.left;
10088                 moved = true;
10089             }
10090             if(y < s.top){
10091                 y = s.top;
10092                 moved = true;
10093             }
10094             if(moved){
10095                 // cache xy
10096                 this.xy = [x, y];
10097                 if(this.isVisible()){
10098                     this.el.setLocation(x, y);
10099                     this.adjustAssets();
10100                 }
10101             }
10102         }
10103     },
10104
10105     // private
10106     onDrag : function(){
10107         if(!this.proxyDrag){
10108             this.xy = this.el.getXY();
10109             this.adjustAssets();
10110         }
10111     },
10112
10113     // private
10114     adjustAssets : function(doShow){
10115         var x = this.xy[0], y = this.xy[1];
10116         var w = this.size.width, h = this.size.height;
10117         if(doShow === true){
10118             if(this.shadow){
10119                 this.shadow.show(this.el);
10120             }
10121             if(this.shim){
10122                 this.shim.show();
10123             }
10124         }
10125         if(this.shadow && this.shadow.isVisible()){
10126             this.shadow.show(this.el);
10127         }
10128         if(this.shim && this.shim.isVisible()){
10129             this.shim.setBounds(x, y, w, h);
10130         }
10131     },
10132
10133     // private
10134     adjustViewport : function(w, h){
10135         if(!w || !h){
10136             w = Roo.lib.Dom.getViewWidth();
10137             h = Roo.lib.Dom.getViewHeight();
10138         }
10139         // cache the size
10140         this.viewSize = [w, h];
10141         if(this.modal && this.mask.isVisible()){
10142             this.mask.setSize(w, h); // first make sure the mask isn't causing overflow
10143             this.mask.setSize(Roo.lib.Dom.getViewWidth(true), Roo.lib.Dom.getViewHeight(true));
10144         }
10145         if(this.isVisible()){
10146             this.constrainXY();
10147         }
10148     },
10149
10150     /**
10151      * Destroys this dialog and all its supporting elements (including any tabs, shim,
10152      * shadow, proxy, mask, etc.)  Also removes all event listeners.
10153      * @param {Boolean} removeEl (optional) true to remove the element from the DOM
10154      */
10155     destroy : function(removeEl){
10156         if(this.isVisible()){
10157             this.animateTarget = null;
10158             this.hide();
10159         }
10160         Roo.EventManager.removeResizeListener(this.adjustViewport, this);
10161         if(this.tabs){
10162             this.tabs.destroy(removeEl);
10163         }
10164         Roo.destroy(
10165              this.shim,
10166              this.proxy,
10167              this.resizer,
10168              this.close,
10169              this.mask
10170         );
10171         if(this.dd){
10172             this.dd.unreg();
10173         }
10174         if(this.buttons){
10175            for(var i = 0, len = this.buttons.length; i < len; i++){
10176                this.buttons[i].destroy();
10177            }
10178         }
10179         this.el.removeAllListeners();
10180         if(removeEl === true){
10181             this.el.update("");
10182             this.el.remove();
10183         }
10184         Roo.DialogManager.unregister(this);
10185     },
10186
10187     // private
10188     startMove : function(){
10189         if(this.proxyDrag){
10190             this.proxy.show();
10191         }
10192         if(this.constraintoviewport !== false){
10193             this.dd.constrainTo(document.body, {right: this.shadowOffset, bottom: this.shadowOffset});
10194         }
10195     },
10196
10197     // private
10198     endMove : function(){
10199         if(!this.proxyDrag){
10200             Roo.dd.DD.prototype.endDrag.apply(this.dd, arguments);
10201         }else{
10202             Roo.dd.DDProxy.prototype.endDrag.apply(this.dd, arguments);
10203             this.proxy.hide();
10204         }
10205         this.refreshSize();
10206         this.adjustAssets();
10207         this.focus();
10208         this.fireEvent("move", this, this.xy[0], this.xy[1]);
10209     },
10210
10211     /**
10212      * Brings this dialog to the front of any other visible dialogs
10213      * @return {Roo.BasicDialog} this
10214      */
10215     toFront : function(){
10216         Roo.DialogManager.bringToFront(this);
10217         return this;
10218     },
10219
10220     /**
10221      * Sends this dialog to the back (under) of any other visible dialogs
10222      * @return {Roo.BasicDialog} this
10223      */
10224     toBack : function(){
10225         Roo.DialogManager.sendToBack(this);
10226         return this;
10227     },
10228
10229     /**
10230      * Centers this dialog in the viewport
10231      * @return {Roo.BasicDialog} this
10232      */
10233     center : function(){
10234         var xy = this.el.getCenterXY(true);
10235         this.moveTo(xy[0], xy[1]);
10236         return this;
10237     },
10238
10239     /**
10240      * Moves the dialog's top-left corner to the specified point
10241      * @param {Number} x
10242      * @param {Number} y
10243      * @return {Roo.BasicDialog} this
10244      */
10245     moveTo : function(x, y){
10246         this.xy = [x,y];
10247         if(this.isVisible()){
10248             this.el.setXY(this.xy);
10249             this.adjustAssets();
10250         }
10251         return this;
10252     },
10253
10254     /**
10255      * Aligns the dialog to the specified element
10256      * @param {String/HTMLElement/Roo.Element} element The element to align to.
10257      * @param {String} position The position to align to (see {@link Roo.Element#alignTo} for more details).
10258      * @param {Array} offsets (optional) Offset the positioning by [x, y]
10259      * @return {Roo.BasicDialog} this
10260      */
10261     alignTo : function(element, position, offsets){
10262         this.xy = this.el.getAlignToXY(element, position, offsets);
10263         if(this.isVisible()){
10264             this.el.setXY(this.xy);
10265             this.adjustAssets();
10266         }
10267         return this;
10268     },
10269
10270     /**
10271      * Anchors an element to another element and realigns it when the window is resized.
10272      * @param {String/HTMLElement/Roo.Element} element The element to align to.
10273      * @param {String} position The position to align to (see {@link Roo.Element#alignTo} for more details)
10274      * @param {Array} offsets (optional) Offset the positioning by [x, y]
10275      * @param {Boolean/Number} monitorScroll (optional) true to monitor body scroll and reposition. If this parameter
10276      * is a number, it is used as the buffer delay (defaults to 50ms).
10277      * @return {Roo.BasicDialog} this
10278      */
10279     anchorTo : function(el, alignment, offsets, monitorScroll){
10280         var action = function(){
10281             this.alignTo(el, alignment, offsets);
10282         };
10283         Roo.EventManager.onWindowResize(action, this);
10284         var tm = typeof monitorScroll;
10285         if(tm != 'undefined'){
10286             Roo.EventManager.on(window, 'scroll', action, this,
10287                 {buffer: tm == 'number' ? monitorScroll : 50});
10288         }
10289         action.call(this);
10290         return this;
10291     },
10292
10293     /**
10294      * Returns true if the dialog is visible
10295      * @return {Boolean}
10296      */
10297     isVisible : function(){
10298         return this.el.isVisible();
10299     },
10300
10301     // private
10302     animHide : function(callback){
10303         var b = Roo.get(this.animateTarget).getBox();
10304         this.proxy.show();
10305         this.proxy.setBounds(this.xy[0], this.xy[1], this.size.width, this.size.height);
10306         this.el.hide();
10307         this.proxy.setBounds(b.x, b.y, b.width, b.height, true, .35,
10308                     this.hideEl.createDelegate(this, [callback]));
10309     },
10310
10311     /**
10312      * Hides the dialog.
10313      * @param {Function} callback (optional) Function to call when the dialog is hidden
10314      * @return {Roo.BasicDialog} this
10315      */
10316     hide : function(callback){
10317         if (this.fireEvent("beforehide", this) === false){
10318             return;
10319         }
10320         if(this.shadow){
10321             this.shadow.hide();
10322         }
10323         if(this.shim) {
10324           this.shim.hide();
10325         }
10326         // sometimes animateTarget seems to get set.. causing problems...
10327         // this just double checks..
10328         if(this.animateTarget && Roo.get(this.animateTarget)) {
10329            this.animHide(callback);
10330         }else{
10331             this.el.hide();
10332             this.hideEl(callback);
10333         }
10334         return this;
10335     },
10336
10337     // private
10338     hideEl : function(callback){
10339         this.proxy.hide();
10340         if(this.modal){
10341             this.mask.hide();
10342             Roo.get(document.body).removeClass("x-body-masked");
10343         }
10344         this.fireEvent("hide", this);
10345         if(typeof callback == "function"){
10346             callback();
10347         }
10348     },
10349
10350     // private
10351     hideAction : function(){
10352         this.setLeft("-10000px");
10353         this.setTop("-10000px");
10354         this.setStyle("visibility", "hidden");
10355     },
10356
10357     // private
10358     refreshSize : function(){
10359         this.size = this.el.getSize();
10360         this.xy = this.el.getXY();
10361         Roo.state.Manager.set(this.stateId || this.el.id + "-state", this.el.getBox());
10362     },
10363
10364     // private
10365     // z-index is managed by the DialogManager and may be overwritten at any time
10366     setZIndex : function(index){
10367         if(this.modal){
10368             this.mask.setStyle("z-index", index);
10369         }
10370         if(this.shim){
10371             this.shim.setStyle("z-index", ++index);
10372         }
10373         if(this.shadow){
10374             this.shadow.setZIndex(++index);
10375         }
10376         this.el.setStyle("z-index", ++index);
10377         if(this.proxy){
10378             this.proxy.setStyle("z-index", ++index);
10379         }
10380         if(this.resizer){
10381             this.resizer.proxy.setStyle("z-index", ++index);
10382         }
10383
10384         this.lastZIndex = index;
10385     },
10386
10387     /**
10388      * Returns the element for this dialog
10389      * @return {Roo.Element} The underlying dialog Element
10390      */
10391     getEl : function(){
10392         return this.el;
10393     }
10394 });
10395
10396 /**
10397  * @class Roo.DialogManager
10398  * Provides global access to BasicDialogs that have been created and
10399  * support for z-indexing (layering) multiple open dialogs.
10400  */
10401 Roo.DialogManager = function(){
10402     var list = {};
10403     var accessList = [];
10404     var front = null;
10405
10406     // private
10407     var sortDialogs = function(d1, d2){
10408         return (!d1._lastAccess || d1._lastAccess < d2._lastAccess) ? -1 : 1;
10409     };
10410
10411     // private
10412     var orderDialogs = function(){
10413         accessList.sort(sortDialogs);
10414         var seed = Roo.DialogManager.zseed;
10415         for(var i = 0, len = accessList.length; i < len; i++){
10416             var dlg = accessList[i];
10417             if(dlg){
10418                 dlg.setZIndex(seed + (i*10));
10419             }
10420         }
10421     };
10422
10423     return {
10424         /**
10425          * The starting z-index for BasicDialogs (defaults to 9000)
10426          * @type Number The z-index value
10427          */
10428         zseed : 9000,
10429
10430         // private
10431         register : function(dlg){
10432             list[dlg.id] = dlg;
10433             accessList.push(dlg);
10434         },
10435
10436         // private
10437         unregister : function(dlg){
10438             delete list[dlg.id];
10439             var i=0;
10440             var len=0;
10441             if(!accessList.indexOf){
10442                 for(  i = 0, len = accessList.length; i < len; i++){
10443                     if(accessList[i] == dlg){
10444                         accessList.splice(i, 1);
10445                         return;
10446                     }
10447                 }
10448             }else{
10449                  i = accessList.indexOf(dlg);
10450                 if(i != -1){
10451                     accessList.splice(i, 1);
10452                 }
10453             }
10454         },
10455
10456         /**
10457          * Gets a registered dialog by id
10458          * @param {String/Object} id The id of the dialog or a dialog
10459          * @return {Roo.BasicDialog} this
10460          */
10461         get : function(id){
10462             return typeof id == "object" ? id : list[id];
10463         },
10464
10465         /**
10466          * Brings the specified dialog to the front
10467          * @param {String/Object} dlg The id of the dialog or a dialog
10468          * @return {Roo.BasicDialog} this
10469          */
10470         bringToFront : function(dlg){
10471             dlg = this.get(dlg);
10472             if(dlg != front){
10473                 front = dlg;
10474                 dlg._lastAccess = new Date().getTime();
10475                 orderDialogs();
10476             }
10477             return dlg;
10478         },
10479
10480         /**
10481          * Sends the specified dialog to the back
10482          * @param {String/Object} dlg The id of the dialog or a dialog
10483          * @return {Roo.BasicDialog} this
10484          */
10485         sendToBack : function(dlg){
10486             dlg = this.get(dlg);
10487             dlg._lastAccess = -(new Date().getTime());
10488             orderDialogs();
10489             return dlg;
10490         },
10491
10492         /**
10493          * Hides all dialogs
10494          */
10495         hideAll : function(){
10496             for(var id in list){
10497                 if(list[id] && typeof list[id] != "function" && list[id].isVisible()){
10498                     list[id].hide();
10499                 }
10500             }
10501         }
10502     };
10503 }();
10504
10505 /**
10506  * @class Roo.LayoutDialog
10507  * @extends Roo.BasicDialog
10508  * Dialog which provides adjustments for working with a layout in a Dialog.
10509  * Add your necessary layout config options to the dialog's config.<br>
10510  * Example usage (including a nested layout):
10511  * <pre><code>
10512 if(!dialog){
10513     dialog = new Roo.LayoutDialog("download-dlg", {
10514         modal: true,
10515         width:600,
10516         height:450,
10517         shadow:true,
10518         minWidth:500,
10519         minHeight:350,
10520         autoTabs:true,
10521         proxyDrag:true,
10522         // layout config merges with the dialog config
10523         center:{
10524             tabPosition: "top",
10525             alwaysShowTabs: true
10526         }
10527     });
10528     dialog.addKeyListener(27, dialog.hide, dialog);
10529     dialog.setDefaultButton(dialog.addButton("Close", dialog.hide, dialog));
10530     dialog.addButton("Build It!", this.getDownload, this);
10531
10532     // we can even add nested layouts
10533     var innerLayout = new Roo.BorderLayout("dl-inner", {
10534         east: {
10535             initialSize: 200,
10536             autoScroll:true,
10537             split:true
10538         },
10539         center: {
10540             autoScroll:true
10541         }
10542     });
10543     innerLayout.beginUpdate();
10544     innerLayout.add("east", new Roo.ContentPanel("dl-details"));
10545     innerLayout.add("center", new Roo.ContentPanel("selection-panel"));
10546     innerLayout.endUpdate(true);
10547
10548     var layout = dialog.getLayout();
10549     layout.beginUpdate();
10550     layout.add("center", new Roo.ContentPanel("standard-panel",
10551                         {title: "Download the Source", fitToFrame:true}));
10552     layout.add("center", new Roo.NestedLayoutPanel(innerLayout,
10553                {title: "Build your own roo.js"}));
10554     layout.getRegion("center").showPanel(sp);
10555     layout.endUpdate();
10556 }
10557 </code></pre>
10558     * @constructor
10559     * @param {String/HTMLElement/Roo.Element} el The id of or container element, or config
10560     * @param {Object} config configuration options
10561   */
10562 Roo.LayoutDialog = function(el, cfg){
10563     
10564     var config=  cfg;
10565     if (typeof(cfg) == 'undefined') {
10566         config = Roo.apply({}, el);
10567         // not sure why we use documentElement here.. - it should always be body.
10568         // IE7 borks horribly if we use documentElement.
10569         // webkit also does not like documentElement - it creates a body element...
10570         el = Roo.get( document.body || document.documentElement ).createChild();
10571         //config.autoCreate = true;
10572     }
10573     
10574     
10575     config.autoTabs = false;
10576     Roo.LayoutDialog.superclass.constructor.call(this, el, config);
10577     this.body.setStyle({overflow:"hidden", position:"relative"});
10578     this.layout = new Roo.BorderLayout(this.body.dom, config);
10579     this.layout.monitorWindowResize = false;
10580     this.el.addClass("x-dlg-auto-layout");
10581     // fix case when center region overwrites center function
10582     this.center = Roo.BasicDialog.prototype.center;
10583     this.on("show", this.layout.layout, this.layout, true);
10584     if (config.items) {
10585         var xitems = config.items;
10586         delete config.items;
10587         Roo.each(xitems, this.addxtype, this);
10588     }
10589     
10590     
10591 };
10592 Roo.extend(Roo.LayoutDialog, Roo.BasicDialog, {
10593     /**
10594      * Ends update of the layout <strike>and resets display to none</strike>. Use standard beginUpdate/endUpdate on the layout.
10595      * @deprecated
10596      */
10597     endUpdate : function(){
10598         this.layout.endUpdate();
10599     },
10600
10601     /**
10602      * Begins an update of the layout <strike>and sets display to block and visibility to hidden</strike>. Use standard beginUpdate/endUpdate on the layout.
10603      *  @deprecated
10604      */
10605     beginUpdate : function(){
10606         this.layout.beginUpdate();
10607     },
10608
10609     /**
10610      * Get the BorderLayout for this dialog
10611      * @return {Roo.BorderLayout}
10612      */
10613     getLayout : function(){
10614         return this.layout;
10615     },
10616
10617     showEl : function(){
10618         Roo.LayoutDialog.superclass.showEl.apply(this, arguments);
10619         if(Roo.isIE7){
10620             this.layout.layout();
10621         }
10622     },
10623
10624     // private
10625     // Use the syncHeightBeforeShow config option to control this automatically
10626     syncBodyHeight : function(){
10627         Roo.LayoutDialog.superclass.syncBodyHeight.call(this);
10628         if(this.layout){this.layout.layout();}
10629     },
10630     
10631       /**
10632      * Add an xtype element (actually adds to the layout.)
10633      * @return {Object} xdata xtype object data.
10634      */
10635     
10636     addxtype : function(c) {
10637         return this.layout.addxtype(c);
10638     }
10639 });/*
10640  * Based on:
10641  * Ext JS Library 1.1.1
10642  * Copyright(c) 2006-2007, Ext JS, LLC.
10643  *
10644  * Originally Released Under LGPL - original licence link has changed is not relivant.
10645  *
10646  * Fork - LGPL
10647  * <script type="text/javascript">
10648  */
10649  
10650 /**
10651  * @class Roo.MessageBox
10652  * Utility class for generating different styles of message boxes.  The alias Roo.Msg can also be used.
10653  * Example usage:
10654  *<pre><code>
10655 // Basic alert:
10656 Roo.Msg.alert('Status', 'Changes saved successfully.');
10657
10658 // Prompt for user data:
10659 Roo.Msg.prompt('Name', 'Please enter your name:', function(btn, text){
10660     if (btn == 'ok'){
10661         // process text value...
10662     }
10663 });
10664
10665 // Show a dialog using config options:
10666 Roo.Msg.show({
10667    title:'Save Changes?',
10668    msg: 'Your are closing a tab that has unsaved changes. Would you like to save your changes?',
10669    buttons: Roo.Msg.YESNOCANCEL,
10670    fn: processResult,
10671    animEl: 'elId'
10672 });
10673 </code></pre>
10674  * @singleton
10675  */
10676 Roo.MessageBox = function(){
10677     var dlg, opt, mask, waitTimer;
10678     var bodyEl, msgEl, textboxEl, textareaEl, progressEl, pp;
10679     var buttons, activeTextEl, bwidth;
10680
10681     // private
10682     var handleButton = function(button){
10683         dlg.hide();
10684         Roo.callback(opt.fn, opt.scope||window, [button, activeTextEl.dom.value], 1);
10685     };
10686
10687     // private
10688     var handleHide = function(){
10689         if(opt && opt.cls){
10690             dlg.el.removeClass(opt.cls);
10691         }
10692         if(waitTimer){
10693             Roo.TaskMgr.stop(waitTimer);
10694             waitTimer = null;
10695         }
10696     };
10697
10698     // private
10699     var updateButtons = function(b){
10700         var width = 0;
10701         if(!b){
10702             buttons["ok"].hide();
10703             buttons["cancel"].hide();
10704             buttons["yes"].hide();
10705             buttons["no"].hide();
10706             dlg.footer.dom.style.display = 'none';
10707             return width;
10708         }
10709         dlg.footer.dom.style.display = '';
10710         for(var k in buttons){
10711             if(typeof buttons[k] != "function"){
10712                 if(b[k]){
10713                     buttons[k].show();
10714                     buttons[k].setText(typeof b[k] == "string" ? b[k] : Roo.MessageBox.buttonText[k]);
10715                     width += buttons[k].el.getWidth()+15;
10716                 }else{
10717                     buttons[k].hide();
10718                 }
10719             }
10720         }
10721         return width;
10722     };
10723
10724     // private
10725     var handleEsc = function(d, k, e){
10726         if(opt && opt.closable !== false){
10727             dlg.hide();
10728         }
10729         if(e){
10730             e.stopEvent();
10731         }
10732     };
10733
10734     return {
10735         /**
10736          * Returns a reference to the underlying {@link Roo.BasicDialog} element
10737          * @return {Roo.BasicDialog} The BasicDialog element
10738          */
10739         getDialog : function(){
10740            if(!dlg){
10741                 dlg = new Roo.BasicDialog("x-msg-box", {
10742                     autoCreate : true,
10743                     shadow: true,
10744                     draggable: true,
10745                     resizable:false,
10746                     constraintoviewport:false,
10747                     fixedcenter:true,
10748                     collapsible : false,
10749                     shim:true,
10750                     modal: true,
10751                     width:400, height:100,
10752                     buttonAlign:"center",
10753                     closeClick : function(){
10754                         if(opt && opt.buttons && opt.buttons.no && !opt.buttons.cancel){
10755                             handleButton("no");
10756                         }else{
10757                             handleButton("cancel");
10758                         }
10759                     }
10760                 });
10761                 dlg.on("hide", handleHide);
10762                 mask = dlg.mask;
10763                 dlg.addKeyListener(27, handleEsc);
10764                 buttons = {};
10765                 var bt = this.buttonText;
10766                 buttons["ok"] = dlg.addButton(bt["ok"], handleButton.createCallback("ok"));
10767                 buttons["yes"] = dlg.addButton(bt["yes"], handleButton.createCallback("yes"));
10768                 buttons["no"] = dlg.addButton(bt["no"], handleButton.createCallback("no"));
10769                 buttons["cancel"] = dlg.addButton(bt["cancel"], handleButton.createCallback("cancel"));
10770                 bodyEl = dlg.body.createChild({
10771
10772                     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>'
10773                 });
10774                 msgEl = bodyEl.dom.firstChild;
10775                 textboxEl = Roo.get(bodyEl.dom.childNodes[2]);
10776                 textboxEl.enableDisplayMode();
10777                 textboxEl.addKeyListener([10,13], function(){
10778                     if(dlg.isVisible() && opt && opt.buttons){
10779                         if(opt.buttons.ok){
10780                             handleButton("ok");
10781                         }else if(opt.buttons.yes){
10782                             handleButton("yes");
10783                         }
10784                     }
10785                 });
10786                 textareaEl = Roo.get(bodyEl.dom.childNodes[3]);
10787                 textareaEl.enableDisplayMode();
10788                 progressEl = Roo.get(bodyEl.dom.childNodes[4]);
10789                 progressEl.enableDisplayMode();
10790                 var pf = progressEl.dom.firstChild;
10791                 if (pf) {
10792                     pp = Roo.get(pf.firstChild);
10793                     pp.setHeight(pf.offsetHeight);
10794                 }
10795                 
10796             }
10797             return dlg;
10798         },
10799
10800         /**
10801          * Updates the message box body text
10802          * @param {String} text (optional) Replaces the message box element's innerHTML with the specified string (defaults to
10803          * the XHTML-compliant non-breaking space character '&amp;#160;')
10804          * @return {Roo.MessageBox} This message box
10805          */
10806         updateText : function(text){
10807             if(!dlg.isVisible() && !opt.width){
10808                 dlg.resizeTo(this.maxWidth, 100); // resize first so content is never clipped from previous shows
10809             }
10810             msgEl.innerHTML = text || '&#160;';
10811       
10812             var cw =  Math.max(msgEl.offsetWidth, msgEl.parentNode.scrollWidth);
10813             //Roo.log("guesed size: " + JSON.stringify([cw,msgEl.offsetWidth, msgEl.parentNode.scrollWidth]));
10814             var w = Math.max(
10815                     Math.min(opt.width || cw , this.maxWidth), 
10816                     Math.max(opt.minWidth || this.minWidth, bwidth)
10817             );
10818             if(opt.prompt){
10819                 activeTextEl.setWidth(w);
10820             }
10821             if(dlg.isVisible()){
10822                 dlg.fixedcenter = false;
10823             }
10824             // to big, make it scroll. = But as usual stupid IE does not support
10825             // !important..
10826             
10827             if ( bodyEl.getHeight() > (Roo.lib.Dom.getViewHeight() - 100)) {
10828                 bodyEl.setHeight ( Roo.lib.Dom.getViewHeight() - 100 );
10829                 bodyEl.dom.style.overflowY = 'auto' + ( Roo.isIE ? '' : ' !important');
10830             } else {
10831                 bodyEl.dom.style.height = '';
10832                 bodyEl.dom.style.overflowY = '';
10833             }
10834             if (cw > w) {
10835                 bodyEl.dom.style.get = 'auto' + ( Roo.isIE ? '' : ' !important');
10836             } else {
10837                 bodyEl.dom.style.overflowX = '';
10838             }
10839             
10840             dlg.setContentSize(w, bodyEl.getHeight());
10841             if(dlg.isVisible()){
10842                 dlg.fixedcenter = true;
10843             }
10844             return this;
10845         },
10846
10847         /**
10848          * Updates a progress-style message box's text and progress bar.  Only relevant on message boxes
10849          * initiated via {@link Roo.MessageBox#progress} or by calling {@link Roo.MessageBox#show} with progress: true.
10850          * @param {Number} value Any number between 0 and 1 (e.g., .5)
10851          * @param {String} text (optional) If defined, the message box's body text is replaced with the specified string (defaults to undefined)
10852          * @return {Roo.MessageBox} This message box
10853          */
10854         updateProgress : function(value, text){
10855             if(text){
10856                 this.updateText(text);
10857             }
10858             if (pp) { // weird bug on my firefox - for some reason this is not defined
10859                 pp.setWidth(Math.floor(value*progressEl.dom.firstChild.offsetWidth));
10860             }
10861             return this;
10862         },        
10863
10864         /**
10865          * Returns true if the message box is currently displayed
10866          * @return {Boolean} True if the message box is visible, else false
10867          */
10868         isVisible : function(){
10869             return dlg && dlg.isVisible();  
10870         },
10871
10872         /**
10873          * Hides the message box if it is displayed
10874          */
10875         hide : function(){
10876             if(this.isVisible()){
10877                 dlg.hide();
10878             }  
10879         },
10880
10881         /**
10882          * Displays a new message box, or reinitializes an existing message box, based on the config options
10883          * passed in. All functions (e.g. prompt, alert, etc) on MessageBox call this function internally.
10884          * The following config object properties are supported:
10885          * <pre>
10886 Property    Type             Description
10887 ----------  ---------------  ------------------------------------------------------------------------------------
10888 animEl            String/Element   An id or Element from which the message box should animate as it opens and
10889                                    closes (defaults to undefined)
10890 buttons           Object/Boolean   A button config object (e.g., Roo.MessageBox.OKCANCEL or {ok:'Foo',
10891                                    cancel:'Bar'}), or false to not show any buttons (defaults to false)
10892 closable          Boolean          False to hide the top-right close button (defaults to true).  Note that
10893                                    progress and wait dialogs will ignore this property and always hide the
10894                                    close button as they can only be closed programmatically.
10895 cls               String           A custom CSS class to apply to the message box element
10896 defaultTextHeight Number           The default height in pixels of the message box's multiline textarea if
10897                                    displayed (defaults to 75)
10898 fn                Function         A callback function to execute after closing the dialog.  The arguments to the
10899                                    function will be btn (the name of the button that was clicked, if applicable,
10900                                    e.g. "ok"), and text (the value of the active text field, if applicable).
10901                                    Progress and wait dialogs will ignore this option since they do not respond to
10902                                    user actions and can only be closed programmatically, so any required function
10903                                    should be called by the same code after it closes the dialog.
10904 icon              String           A CSS class that provides a background image to be used as an icon for
10905                                    the dialog (e.g., Roo.MessageBox.WARNING or 'custom-class', defaults to '')
10906 maxWidth          Number           The maximum width in pixels of the message box (defaults to 600)
10907 minWidth          Number           The minimum width in pixels of the message box (defaults to 100)
10908 modal             Boolean          False to allow user interaction with the page while the message box is
10909                                    displayed (defaults to true)
10910 msg               String           A string that will replace the existing message box body text (defaults
10911                                    to the XHTML-compliant non-breaking space character '&#160;')
10912 multiline         Boolean          True to prompt the user to enter multi-line text (defaults to false)
10913 progress          Boolean          True to display a progress bar (defaults to false)
10914 progressText      String           The text to display inside the progress bar if progress = true (defaults to '')
10915 prompt            Boolean          True to prompt the user to enter single-line text (defaults to false)
10916 proxyDrag         Boolean          True to display a lightweight proxy while dragging (defaults to false)
10917 title             String           The title text
10918 value             String           The string value to set into the active textbox element if displayed
10919 wait              Boolean          True to display a progress bar (defaults to false)
10920 width             Number           The width of the dialog in pixels
10921 </pre>
10922          *
10923          * Example usage:
10924          * <pre><code>
10925 Roo.Msg.show({
10926    title: 'Address',
10927    msg: 'Please enter your address:',
10928    width: 300,
10929    buttons: Roo.MessageBox.OKCANCEL,
10930    multiline: true,
10931    fn: saveAddress,
10932    animEl: 'addAddressBtn'
10933 });
10934 </code></pre>
10935          * @param {Object} config Configuration options
10936          * @return {Roo.MessageBox} This message box
10937          */
10938         show : function(options)
10939         {
10940             
10941             // this causes nightmares if you show one dialog after another
10942             // especially on callbacks..
10943              
10944             if(this.isVisible()){
10945                 
10946                 this.hide();
10947                 Roo.log("[Roo.Messagebox] Show called while message displayed:" );
10948                 Roo.log("Old Dialog Message:" +  msgEl.innerHTML );
10949                 Roo.log("New Dialog Message:" +  options.msg )
10950                 //this.alert("ERROR", "Multiple dialogs where displayed at the same time");
10951                 //throw "Roo.MessageBox ERROR : Multiple dialogs where displayed at the same time";
10952                 
10953             }
10954             var d = this.getDialog();
10955             opt = options;
10956             d.setTitle(opt.title || "&#160;");
10957             d.close.setDisplayed(opt.closable !== false);
10958             activeTextEl = textboxEl;
10959             opt.prompt = opt.prompt || (opt.multiline ? true : false);
10960             if(opt.prompt){
10961                 if(opt.multiline){
10962                     textboxEl.hide();
10963                     textareaEl.show();
10964                     textareaEl.setHeight(typeof opt.multiline == "number" ?
10965                         opt.multiline : this.defaultTextHeight);
10966                     activeTextEl = textareaEl;
10967                 }else{
10968                     textboxEl.show();
10969                     textareaEl.hide();
10970                 }
10971             }else{
10972                 textboxEl.hide();
10973                 textareaEl.hide();
10974             }
10975             progressEl.setDisplayed(opt.progress === true);
10976             this.updateProgress(0);
10977             activeTextEl.dom.value = opt.value || "";
10978             if(opt.prompt){
10979                 dlg.setDefaultButton(activeTextEl);
10980             }else{
10981                 var bs = opt.buttons;
10982                 var db = null;
10983                 if(bs && bs.ok){
10984                     db = buttons["ok"];
10985                 }else if(bs && bs.yes){
10986                     db = buttons["yes"];
10987                 }
10988                 dlg.setDefaultButton(db);
10989             }
10990             bwidth = updateButtons(opt.buttons);
10991             this.updateText(opt.msg);
10992             if(opt.cls){
10993                 d.el.addClass(opt.cls);
10994             }
10995             d.proxyDrag = opt.proxyDrag === true;
10996             d.modal = opt.modal !== false;
10997             d.mask = opt.modal !== false ? mask : false;
10998             if(!d.isVisible()){
10999                 // force it to the end of the z-index stack so it gets a cursor in FF
11000                 document.body.appendChild(dlg.el.dom);
11001                 d.animateTarget = null;
11002                 d.show(options.animEl);
11003             }
11004             return this;
11005         },
11006
11007         /**
11008          * Displays a message box with a progress bar.  This message box has no buttons and is not closeable by
11009          * the user.  You are responsible for updating the progress bar as needed via {@link Roo.MessageBox#updateProgress}
11010          * and closing the message box when the process is complete.
11011          * @param {String} title The title bar text
11012          * @param {String} msg The message box body text
11013          * @return {Roo.MessageBox} This message box
11014          */
11015         progress : function(title, msg){
11016             this.show({
11017                 title : title,
11018                 msg : msg,
11019                 buttons: false,
11020                 progress:true,
11021                 closable:false,
11022                 minWidth: this.minProgressWidth,
11023                 modal : true
11024             });
11025             return this;
11026         },
11027
11028         /**
11029          * Displays a standard read-only message box with an OK button (comparable to the basic JavaScript Window.alert).
11030          * If a callback function is passed it will be called after the user clicks the button, and the
11031          * id of the button that was clicked will be passed as the only parameter to the callback
11032          * (could also be the top-right close button).
11033          * @param {String} title The title bar text
11034          * @param {String} msg The message box body text
11035          * @param {Function} fn (optional) The callback function invoked after the message box is closed
11036          * @param {Object} scope (optional) The scope of the callback function
11037          * @return {Roo.MessageBox} This message box
11038          */
11039         alert : function(title, msg, fn, scope){
11040             this.show({
11041                 title : title,
11042                 msg : msg,
11043                 buttons: this.OK,
11044                 fn: fn,
11045                 scope : scope,
11046                 modal : true
11047             });
11048             return this;
11049         },
11050
11051         /**
11052          * Displays a message box with an infinitely auto-updating progress bar.  This can be used to block user
11053          * interaction while waiting for a long-running process to complete that does not have defined intervals.
11054          * You are responsible for closing the message box when the process is complete.
11055          * @param {String} msg The message box body text
11056          * @param {String} title (optional) The title bar text
11057          * @return {Roo.MessageBox} This message box
11058          */
11059         wait : function(msg, title){
11060             this.show({
11061                 title : title,
11062                 msg : msg,
11063                 buttons: false,
11064                 closable:false,
11065                 progress:true,
11066                 modal:true,
11067                 width:300,
11068                 wait:true
11069             });
11070             waitTimer = Roo.TaskMgr.start({
11071                 run: function(i){
11072                     Roo.MessageBox.updateProgress(((((i+20)%20)+1)*5)*.01);
11073                 },
11074                 interval: 1000
11075             });
11076             return this;
11077         },
11078
11079         /**
11080          * Displays a confirmation message box with Yes and No buttons (comparable to JavaScript's Window.confirm).
11081          * If a callback function is passed it will be called after the user clicks either button, and the id of the
11082          * button that was clicked will be passed as the only parameter to the callback (could also be the top-right close button).
11083          * @param {String} title The title bar text
11084          * @param {String} msg The message box body text
11085          * @param {Function} fn (optional) The callback function invoked after the message box is closed
11086          * @param {Object} scope (optional) The scope of the callback function
11087          * @return {Roo.MessageBox} This message box
11088          */
11089         confirm : function(title, msg, fn, scope){
11090             this.show({
11091                 title : title,
11092                 msg : msg,
11093                 buttons: this.YESNO,
11094                 fn: fn,
11095                 scope : scope,
11096                 modal : true
11097             });
11098             return this;
11099         },
11100
11101         /**
11102          * Displays a message box with OK and Cancel buttons prompting the user to enter some text (comparable to
11103          * JavaScript's Window.prompt).  The prompt can be a single-line or multi-line textbox.  If a callback function
11104          * is passed it will be called after the user clicks either button, and the id of the button that was clicked
11105          * (could also be the top-right close button) and the text that was entered will be passed as the two
11106          * parameters to the callback.
11107          * @param {String} title The title bar text
11108          * @param {String} msg The message box body text
11109          * @param {Function} fn (optional) The callback function invoked after the message box is closed
11110          * @param {Object} scope (optional) The scope of the callback function
11111          * @param {Boolean/Number} multiline (optional) True to create a multiline textbox using the defaultTextHeight
11112          * property, or the height in pixels to create the textbox (defaults to false / single-line)
11113          * @return {Roo.MessageBox} This message box
11114          */
11115         prompt : function(title, msg, fn, scope, multiline){
11116             this.show({
11117                 title : title,
11118                 msg : msg,
11119                 buttons: this.OKCANCEL,
11120                 fn: fn,
11121                 minWidth:250,
11122                 scope : scope,
11123                 prompt:true,
11124                 multiline: multiline,
11125                 modal : true
11126             });
11127             return this;
11128         },
11129
11130         /**
11131          * Button config that displays a single OK button
11132          * @type Object
11133          */
11134         OK : {ok:true},
11135         /**
11136          * Button config that displays Yes and No buttons
11137          * @type Object
11138          */
11139         YESNO : {yes:true, no:true},
11140         /**
11141          * Button config that displays OK and Cancel buttons
11142          * @type Object
11143          */
11144         OKCANCEL : {ok:true, cancel:true},
11145         /**
11146          * Button config that displays Yes, No and Cancel buttons
11147          * @type Object
11148          */
11149         YESNOCANCEL : {yes:true, no:true, cancel:true},
11150
11151         /**
11152          * The default height in pixels of the message box's multiline textarea if displayed (defaults to 75)
11153          * @type Number
11154          */
11155         defaultTextHeight : 75,
11156         /**
11157          * The maximum width in pixels of the message box (defaults to 600)
11158          * @type Number
11159          */
11160         maxWidth : 600,
11161         /**
11162          * The minimum width in pixels of the message box (defaults to 100)
11163          * @type Number
11164          */
11165         minWidth : 100,
11166         /**
11167          * The minimum width in pixels of the message box if it is a progress-style dialog.  This is useful
11168          * for setting a different minimum width than text-only dialogs may need (defaults to 250)
11169          * @type Number
11170          */
11171         minProgressWidth : 250,
11172         /**
11173          * An object containing the default button text strings that can be overriden for localized language support.
11174          * Supported properties are: ok, cancel, yes and no.
11175          * Customize the default text like so: Roo.MessageBox.buttonText.yes = "S?";
11176          * @type Object
11177          */
11178         buttonText : {
11179             ok : "OK",
11180             cancel : "Cancel",
11181             yes : "Yes",
11182             no : "No"
11183         }
11184     };
11185 }();
11186
11187 /**
11188  * Shorthand for {@link Roo.MessageBox}
11189  */
11190 Roo.Msg = Roo.MessageBox;/*
11191  * Based on:
11192  * Ext JS Library 1.1.1
11193  * Copyright(c) 2006-2007, Ext JS, LLC.
11194  *
11195  * Originally Released Under LGPL - original licence link has changed is not relivant.
11196  *
11197  * Fork - LGPL
11198  * <script type="text/javascript">
11199  */
11200 /**
11201  * @class Roo.QuickTips
11202  * Provides attractive and customizable tooltips for any element.
11203  * @singleton
11204  */
11205 Roo.QuickTips = function(){
11206     var el, tipBody, tipBodyText, tipTitle, tm, cfg, close, tagEls = {}, esc, removeCls = null, bdLeft, bdRight;
11207     var ce, bd, xy, dd;
11208     var visible = false, disabled = true, inited = false;
11209     var showProc = 1, hideProc = 1, dismissProc = 1, locks = [];
11210     
11211     var onOver = function(e){
11212         if(disabled){
11213             return;
11214         }
11215         var t = e.getTarget();
11216         if(!t || t.nodeType !== 1 || t == document || t == document.body){
11217             return;
11218         }
11219         if(ce && t == ce.el){
11220             clearTimeout(hideProc);
11221             return;
11222         }
11223         if(t && tagEls[t.id]){
11224             tagEls[t.id].el = t;
11225             showProc = show.defer(tm.showDelay, tm, [tagEls[t.id]]);
11226             return;
11227         }
11228         var ttp, et = Roo.fly(t);
11229         var ns = cfg.namespace;
11230         if(tm.interceptTitles && t.title){
11231             ttp = t.title;
11232             t.qtip = ttp;
11233             t.removeAttribute("title");
11234             e.preventDefault();
11235         }else{
11236             ttp = t.qtip || et.getAttributeNS(ns, cfg.attribute) || et.getAttributeNS(cfg.alt_namespace, cfg.attribute) ;
11237         }
11238         if(ttp){
11239             showProc = show.defer(tm.showDelay, tm, [{
11240                 el: t, 
11241                 text: ttp.replace(/\\n/g,'<br/>'),
11242                 width: et.getAttributeNS(ns, cfg.width),
11243                 autoHide: et.getAttributeNS(ns, cfg.hide) != "user",
11244                 title: et.getAttributeNS(ns, cfg.title),
11245                     cls: et.getAttributeNS(ns, cfg.cls)
11246             }]);
11247         }
11248     };
11249     
11250     var onOut = function(e){
11251         clearTimeout(showProc);
11252         var t = e.getTarget();
11253         if(t && ce && ce.el == t && (tm.autoHide && ce.autoHide !== false)){
11254             hideProc = setTimeout(hide, tm.hideDelay);
11255         }
11256     };
11257     
11258     var onMove = function(e){
11259         if(disabled){
11260             return;
11261         }
11262         xy = e.getXY();
11263         xy[1] += 18;
11264         if(tm.trackMouse && ce){
11265             el.setXY(xy);
11266         }
11267     };
11268     
11269     var onDown = function(e){
11270         clearTimeout(showProc);
11271         clearTimeout(hideProc);
11272         if(!e.within(el)){
11273             if(tm.hideOnClick){
11274                 hide();
11275                 tm.disable();
11276                 tm.enable.defer(100, tm);
11277             }
11278         }
11279     };
11280     
11281     var getPad = function(){
11282         return 2;//bdLeft.getPadding('l')+bdRight.getPadding('r');
11283     };
11284
11285     var show = function(o){
11286         if(disabled){
11287             return;
11288         }
11289         clearTimeout(dismissProc);
11290         ce = o;
11291         if(removeCls){ // in case manually hidden
11292             el.removeClass(removeCls);
11293             removeCls = null;
11294         }
11295         if(ce.cls){
11296             el.addClass(ce.cls);
11297             removeCls = ce.cls;
11298         }
11299         if(ce.title){
11300             tipTitle.update(ce.title);
11301             tipTitle.show();
11302         }else{
11303             tipTitle.update('');
11304             tipTitle.hide();
11305         }
11306         el.dom.style.width  = tm.maxWidth+'px';
11307         //tipBody.dom.style.width = '';
11308         tipBodyText.update(o.text);
11309         var p = getPad(), w = ce.width;
11310         if(!w){
11311             var td = tipBodyText.dom;
11312             var aw = Math.max(td.offsetWidth, td.clientWidth, td.scrollWidth);
11313             if(aw > tm.maxWidth){
11314                 w = tm.maxWidth;
11315             }else if(aw < tm.minWidth){
11316                 w = tm.minWidth;
11317             }else{
11318                 w = aw;
11319             }
11320         }
11321         //tipBody.setWidth(w);
11322         el.setWidth(parseInt(w, 10) + p);
11323         if(ce.autoHide === false){
11324             close.setDisplayed(true);
11325             if(dd){
11326                 dd.unlock();
11327             }
11328         }else{
11329             close.setDisplayed(false);
11330             if(dd){
11331                 dd.lock();
11332             }
11333         }
11334         if(xy){
11335             el.avoidY = xy[1]-18;
11336             el.setXY(xy);
11337         }
11338         if(tm.animate){
11339             el.setOpacity(.1);
11340             el.setStyle("visibility", "visible");
11341             el.fadeIn({callback: afterShow});
11342         }else{
11343             afterShow();
11344         }
11345     };
11346     
11347     var afterShow = function(){
11348         if(ce){
11349             el.show();
11350             esc.enable();
11351             if(tm.autoDismiss && ce.autoHide !== false){
11352                 dismissProc = setTimeout(hide, tm.autoDismissDelay);
11353             }
11354         }
11355     };
11356     
11357     var hide = function(noanim){
11358         clearTimeout(dismissProc);
11359         clearTimeout(hideProc);
11360         ce = null;
11361         if(el.isVisible()){
11362             esc.disable();
11363             if(noanim !== true && tm.animate){
11364                 el.fadeOut({callback: afterHide});
11365             }else{
11366                 afterHide();
11367             } 
11368         }
11369     };
11370     
11371     var afterHide = function(){
11372         el.hide();
11373         if(removeCls){
11374             el.removeClass(removeCls);
11375             removeCls = null;
11376         }
11377     };
11378     
11379     return {
11380         /**
11381         * @cfg {Number} minWidth
11382         * The minimum width of the quick tip (defaults to 40)
11383         */
11384        minWidth : 40,
11385         /**
11386         * @cfg {Number} maxWidth
11387         * The maximum width of the quick tip (defaults to 300)
11388         */
11389        maxWidth : 300,
11390         /**
11391         * @cfg {Boolean} interceptTitles
11392         * True to automatically use the element's DOM title value if available (defaults to false)
11393         */
11394        interceptTitles : false,
11395         /**
11396         * @cfg {Boolean} trackMouse
11397         * True to have the quick tip follow the mouse as it moves over the target element (defaults to false)
11398         */
11399        trackMouse : false,
11400         /**
11401         * @cfg {Boolean} hideOnClick
11402         * True to hide the quick tip if the user clicks anywhere in the document (defaults to true)
11403         */
11404        hideOnClick : true,
11405         /**
11406         * @cfg {Number} showDelay
11407         * Delay in milliseconds before the quick tip displays after the mouse enters the target element (defaults to 500)
11408         */
11409        showDelay : 500,
11410         /**
11411         * @cfg {Number} hideDelay
11412         * Delay in milliseconds before the quick tip hides when autoHide = true (defaults to 200)
11413         */
11414        hideDelay : 200,
11415         /**
11416         * @cfg {Boolean} autoHide
11417         * True to automatically hide the quick tip after the mouse exits the target element (defaults to true).
11418         * Used in conjunction with hideDelay.
11419         */
11420        autoHide : true,
11421         /**
11422         * @cfg {Boolean}
11423         * True to automatically hide the quick tip after a set period of time, regardless of the user's actions
11424         * (defaults to true).  Used in conjunction with autoDismissDelay.
11425         */
11426        autoDismiss : true,
11427         /**
11428         * @cfg {Number}
11429         * Delay in milliseconds before the quick tip hides when autoDismiss = true (defaults to 5000)
11430         */
11431        autoDismissDelay : 5000,
11432        /**
11433         * @cfg {Boolean} animate
11434         * True to turn on fade animation. Defaults to false (ClearType/scrollbar flicker issues in IE7).
11435         */
11436        animate : false,
11437
11438        /**
11439         * @cfg {String} title
11440         * Title text to display (defaults to '').  This can be any valid HTML markup.
11441         */
11442         title: '',
11443        /**
11444         * @cfg {String} text
11445         * Body text to display (defaults to '').  This can be any valid HTML markup.
11446         */
11447         text : '',
11448        /**
11449         * @cfg {String} cls
11450         * A CSS class to apply to the base quick tip element (defaults to '').
11451         */
11452         cls : '',
11453        /**
11454         * @cfg {Number} width
11455         * Width in pixels of the quick tip (defaults to auto).  Width will be ignored if it exceeds the bounds of
11456         * minWidth or maxWidth.
11457         */
11458         width : null,
11459
11460     /**
11461      * Initialize and enable QuickTips for first use.  This should be called once before the first attempt to access
11462      * or display QuickTips in a page.
11463      */
11464        init : function(){
11465           tm = Roo.QuickTips;
11466           cfg = tm.tagConfig;
11467           if(!inited){
11468               if(!Roo.isReady){ // allow calling of init() before onReady
11469                   Roo.onReady(Roo.QuickTips.init, Roo.QuickTips);
11470                   return;
11471               }
11472               el = new Roo.Layer({cls:"x-tip", shadow:"drop", shim: true, constrain:true, shadowOffset:4});
11473               el.fxDefaults = {stopFx: true};
11474               // maximum custom styling
11475               //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>');
11476               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>');              
11477               tipTitle = el.child('h3');
11478               tipTitle.enableDisplayMode("block");
11479               tipBody = el.child('div.x-tip-bd');
11480               tipBodyText = el.child('div.x-tip-bd-inner');
11481               //bdLeft = el.child('div.x-tip-bd-left');
11482               //bdRight = el.child('div.x-tip-bd-right');
11483               close = el.child('div.x-tip-close');
11484               close.enableDisplayMode("block");
11485               close.on("click", hide);
11486               var d = Roo.get(document);
11487               d.on("mousedown", onDown);
11488               d.on("mouseover", onOver);
11489               d.on("mouseout", onOut);
11490               d.on("mousemove", onMove);
11491               esc = d.addKeyListener(27, hide);
11492               esc.disable();
11493               if(Roo.dd.DD){
11494                   dd = el.initDD("default", null, {
11495                       onDrag : function(){
11496                           el.sync();  
11497                       }
11498                   });
11499                   dd.setHandleElId(tipTitle.id);
11500                   dd.lock();
11501               }
11502               inited = true;
11503           }
11504           this.enable(); 
11505        },
11506
11507     /**
11508      * Configures a new quick tip instance and assigns it to a target element.  The following config options
11509      * are supported:
11510      * <pre>
11511 Property    Type                   Description
11512 ----------  ---------------------  ------------------------------------------------------------------------
11513 target      Element/String/Array   An Element, id or array of ids that this quick tip should be tied to
11514      * </ul>
11515      * @param {Object} config The config object
11516      */
11517        register : function(config){
11518            var cs = config instanceof Array ? config : arguments;
11519            for(var i = 0, len = cs.length; i < len; i++) {
11520                var c = cs[i];
11521                var target = c.target;
11522                if(target){
11523                    if(target instanceof Array){
11524                        for(var j = 0, jlen = target.length; j < jlen; j++){
11525                            tagEls[target[j]] = c;
11526                        }
11527                    }else{
11528                        tagEls[typeof target == 'string' ? target : Roo.id(target)] = c;
11529                    }
11530                }
11531            }
11532        },
11533
11534     /**
11535      * Removes this quick tip from its element and destroys it.
11536      * @param {String/HTMLElement/Element} el The element from which the quick tip is to be removed.
11537      */
11538        unregister : function(el){
11539            delete tagEls[Roo.id(el)];
11540        },
11541
11542     /**
11543      * Enable this quick tip.
11544      */
11545        enable : function(){
11546            if(inited && disabled){
11547                locks.pop();
11548                if(locks.length < 1){
11549                    disabled = false;
11550                }
11551            }
11552        },
11553
11554     /**
11555      * Disable this quick tip.
11556      */
11557        disable : function(){
11558           disabled = true;
11559           clearTimeout(showProc);
11560           clearTimeout(hideProc);
11561           clearTimeout(dismissProc);
11562           if(ce){
11563               hide(true);
11564           }
11565           locks.push(1);
11566        },
11567
11568     /**
11569      * Returns true if the quick tip is enabled, else false.
11570      */
11571        isEnabled : function(){
11572             return !disabled;
11573        },
11574
11575         // private
11576        tagConfig : {
11577            namespace : "roo", // was ext?? this may break..
11578            alt_namespace : "ext",
11579            attribute : "qtip",
11580            width : "width",
11581            target : "target",
11582            title : "qtitle",
11583            hide : "hide",
11584            cls : "qclass"
11585        }
11586    };
11587 }();
11588
11589 // backwards compat
11590 Roo.QuickTips.tips = Roo.QuickTips.register;/*
11591  * Based on:
11592  * Ext JS Library 1.1.1
11593  * Copyright(c) 2006-2007, Ext JS, LLC.
11594  *
11595  * Originally Released Under LGPL - original licence link has changed is not relivant.
11596  *
11597  * Fork - LGPL
11598  * <script type="text/javascript">
11599  */
11600  
11601
11602 /**
11603  * @class Roo.tree.TreePanel
11604  * @extends Roo.data.Tree
11605
11606  * @cfg {Boolean} rootVisible false to hide the root node (defaults to true)
11607  * @cfg {Boolean} lines false to disable tree lines (defaults to true)
11608  * @cfg {Boolean} enableDD true to enable drag and drop
11609  * @cfg {Boolean} enableDrag true to enable just drag
11610  * @cfg {Boolean} enableDrop true to enable just drop
11611  * @cfg {Object} dragConfig Custom config to pass to the {@link Roo.tree.TreeDragZone} instance
11612  * @cfg {Object} dropConfig Custom config to pass to the {@link Roo.tree.TreeDropZone} instance
11613  * @cfg {String} ddGroup The DD group this TreePanel belongs to
11614  * @cfg {String} ddAppendOnly True if the tree should only allow append drops (use for trees which are sorted)
11615  * @cfg {Boolean} ddScroll true to enable YUI body scrolling
11616  * @cfg {Boolean} containerScroll true to register this container with ScrollManager
11617  * @cfg {Boolean} hlDrop false to disable node highlight on drop (defaults to the value of Roo.enableFx)
11618  * @cfg {String} hlColor The color of the node highlight (defaults to C3DAF9)
11619  * @cfg {Boolean} animate true to enable animated expand/collapse (defaults to the value of Roo.enableFx)
11620  * @cfg {Boolean} singleExpand true if only 1 node per branch may be expanded
11621  * @cfg {Boolean} selModel A tree selection model to use with this TreePanel (defaults to a {@link Roo.tree.DefaultSelectionModel})
11622  * @cfg {Boolean} loader A TreeLoader for use with this TreePanel
11623  * @cfg {Object|Roo.tree.TreeEditor} editor The TreeEditor or xtype data to display when clicked.
11624  * @cfg {String} pathSeparator The token used to separate sub-paths in path strings (defaults to '/')
11625  * @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>
11626  * @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>
11627  * 
11628  * @constructor
11629  * @param {String/HTMLElement/Element} el The container element
11630  * @param {Object} config
11631  */
11632 Roo.tree.TreePanel = function(el, config){
11633     var root = false;
11634     var loader = false;
11635     if (config.root) {
11636         root = config.root;
11637         delete config.root;
11638     }
11639     if (config.loader) {
11640         loader = config.loader;
11641         delete config.loader;
11642     }
11643     
11644     Roo.apply(this, config);
11645     Roo.tree.TreePanel.superclass.constructor.call(this);
11646     this.el = Roo.get(el);
11647     this.el.addClass('x-tree');
11648     //console.log(root);
11649     if (root) {
11650         this.setRootNode( Roo.factory(root, Roo.tree));
11651     }
11652     if (loader) {
11653         this.loader = Roo.factory(loader, Roo.tree);
11654     }
11655    /**
11656     * Read-only. The id of the container element becomes this TreePanel's id.
11657     */
11658     this.id = this.el.id;
11659     this.addEvents({
11660         /**
11661         * @event beforeload
11662         * Fires before a node is loaded, return false to cancel
11663         * @param {Node} node The node being loaded
11664         */
11665         "beforeload" : true,
11666         /**
11667         * @event load
11668         * Fires when a node is loaded
11669         * @param {Node} node The node that was loaded
11670         */
11671         "load" : true,
11672         /**
11673         * @event textchange
11674         * Fires when the text for a node is changed
11675         * @param {Node} node The node
11676         * @param {String} text The new text
11677         * @param {String} oldText The old text
11678         */
11679         "textchange" : true,
11680         /**
11681         * @event beforeexpand
11682         * Fires before a node is expanded, return false to cancel.
11683         * @param {Node} node The node
11684         * @param {Boolean} deep
11685         * @param {Boolean} anim
11686         */
11687         "beforeexpand" : true,
11688         /**
11689         * @event beforecollapse
11690         * Fires before a node is collapsed, return false to cancel.
11691         * @param {Node} node The node
11692         * @param {Boolean} deep
11693         * @param {Boolean} anim
11694         */
11695         "beforecollapse" : true,
11696         /**
11697         * @event expand
11698         * Fires when a node is expanded
11699         * @param {Node} node The node
11700         */
11701         "expand" : true,
11702         /**
11703         * @event disabledchange
11704         * Fires when the disabled status of a node changes
11705         * @param {Node} node The node
11706         * @param {Boolean} disabled
11707         */
11708         "disabledchange" : true,
11709         /**
11710         * @event collapse
11711         * Fires when a node is collapsed
11712         * @param {Node} node The node
11713         */
11714         "collapse" : true,
11715         /**
11716         * @event beforeclick
11717         * Fires before click processing on a node. Return false to cancel the default action.
11718         * @param {Node} node The node
11719         * @param {Roo.EventObject} e The event object
11720         */
11721         "beforeclick":true,
11722         /**
11723         * @event checkchange
11724         * Fires when a node with a checkbox's checked property changes
11725         * @param {Node} this This node
11726         * @param {Boolean} checked
11727         */
11728         "checkchange":true,
11729         /**
11730         * @event click
11731         * Fires when a node is clicked
11732         * @param {Node} node The node
11733         * @param {Roo.EventObject} e The event object
11734         */
11735         "click":true,
11736         /**
11737         * @event dblclick
11738         * Fires when a node is double clicked
11739         * @param {Node} node The node
11740         * @param {Roo.EventObject} e The event object
11741         */
11742         "dblclick":true,
11743         /**
11744         * @event contextmenu
11745         * Fires when a node is right clicked
11746         * @param {Node} node The node
11747         * @param {Roo.EventObject} e The event object
11748         */
11749         "contextmenu":true,
11750         /**
11751         * @event beforechildrenrendered
11752         * Fires right before the child nodes for a node are rendered
11753         * @param {Node} node The node
11754         */
11755         "beforechildrenrendered":true,
11756         /**
11757         * @event startdrag
11758         * Fires when a node starts being dragged
11759         * @param {Roo.tree.TreePanel} this
11760         * @param {Roo.tree.TreeNode} node
11761         * @param {event} e The raw browser event
11762         */ 
11763        "startdrag" : true,
11764        /**
11765         * @event enddrag
11766         * Fires when a drag operation is complete
11767         * @param {Roo.tree.TreePanel} this
11768         * @param {Roo.tree.TreeNode} node
11769         * @param {event} e The raw browser event
11770         */
11771        "enddrag" : true,
11772        /**
11773         * @event dragdrop
11774         * Fires when a dragged node is dropped on a valid DD target
11775         * @param {Roo.tree.TreePanel} this
11776         * @param {Roo.tree.TreeNode} node
11777         * @param {DD} dd The dd it was dropped on
11778         * @param {event} e The raw browser event
11779         */
11780        "dragdrop" : true,
11781        /**
11782         * @event beforenodedrop
11783         * Fires when a DD object is dropped on a node in this tree for preprocessing. Return false to cancel the drop. The dropEvent
11784         * passed to handlers has the following properties:<br />
11785         * <ul style="padding:5px;padding-left:16px;">
11786         * <li>tree - The TreePanel</li>
11787         * <li>target - The node being targeted for the drop</li>
11788         * <li>data - The drag data from the drag source</li>
11789         * <li>point - The point of the drop - append, above or below</li>
11790         * <li>source - The drag source</li>
11791         * <li>rawEvent - Raw mouse event</li>
11792         * <li>dropNode - Drop node(s) provided by the source <b>OR</b> you can supply node(s)
11793         * to be inserted by setting them on this object.</li>
11794         * <li>cancel - Set this to true to cancel the drop.</li>
11795         * </ul>
11796         * @param {Object} dropEvent
11797         */
11798        "beforenodedrop" : true,
11799        /**
11800         * @event nodedrop
11801         * Fires after a DD object is dropped on a node in this tree. The dropEvent
11802         * passed to handlers has the following properties:<br />
11803         * <ul style="padding:5px;padding-left:16px;">
11804         * <li>tree - The TreePanel</li>
11805         * <li>target - The node being targeted for the drop</li>
11806         * <li>data - The drag data from the drag source</li>
11807         * <li>point - The point of the drop - append, above or below</li>
11808         * <li>source - The drag source</li>
11809         * <li>rawEvent - Raw mouse event</li>
11810         * <li>dropNode - Dropped node(s).</li>
11811         * </ul>
11812         * @param {Object} dropEvent
11813         */
11814        "nodedrop" : true,
11815         /**
11816         * @event nodedragover
11817         * Fires when a tree node is being targeted for a drag drop, return false to signal drop not allowed. The dragOverEvent
11818         * passed to handlers has the following properties:<br />
11819         * <ul style="padding:5px;padding-left:16px;">
11820         * <li>tree - The TreePanel</li>
11821         * <li>target - The node being targeted for the drop</li>
11822         * <li>data - The drag data from the drag source</li>
11823         * <li>point - The point of the drop - append, above or below</li>
11824         * <li>source - The drag source</li>
11825         * <li>rawEvent - Raw mouse event</li>
11826         * <li>dropNode - Drop node(s) provided by the source.</li>
11827         * <li>cancel - Set this to true to signal drop not allowed.</li>
11828         * </ul>
11829         * @param {Object} dragOverEvent
11830         */
11831        "nodedragover" : true,
11832        /**
11833         * @event appendnode
11834         * Fires when append node to the tree
11835         * @param {Roo.tree.TreePanel} this
11836         * @param {Roo.tree.TreeNode} node
11837         * @param {Number} index The index of the newly appended node
11838         */
11839        "appendnode" : true
11840         
11841     });
11842     if(this.singleExpand){
11843        this.on("beforeexpand", this.restrictExpand, this);
11844     }
11845     if (this.editor) {
11846         this.editor.tree = this;
11847         this.editor = Roo.factory(this.editor, Roo.tree);
11848     }
11849     
11850     if (this.selModel) {
11851         this.selModel = Roo.factory(this.selModel, Roo.tree);
11852     }
11853    
11854 };
11855 Roo.extend(Roo.tree.TreePanel, Roo.data.Tree, {
11856     rootVisible : true,
11857     animate: Roo.enableFx,
11858     lines : true,
11859     enableDD : false,
11860     hlDrop : Roo.enableFx,
11861   
11862     renderer: false,
11863     
11864     rendererTip: false,
11865     // private
11866     restrictExpand : function(node){
11867         var p = node.parentNode;
11868         if(p){
11869             if(p.expandedChild && p.expandedChild.parentNode == p){
11870                 p.expandedChild.collapse();
11871             }
11872             p.expandedChild = node;
11873         }
11874     },
11875
11876     // private override
11877     setRootNode : function(node){
11878         Roo.tree.TreePanel.superclass.setRootNode.call(this, node);
11879         if(!this.rootVisible){
11880             node.ui = new Roo.tree.RootTreeNodeUI(node);
11881         }
11882         return node;
11883     },
11884
11885     /**
11886      * Returns the container element for this TreePanel
11887      */
11888     getEl : function(){
11889         return this.el;
11890     },
11891
11892     /**
11893      * Returns the default TreeLoader for this TreePanel
11894      */
11895     getLoader : function(){
11896         return this.loader;
11897     },
11898
11899     /**
11900      * Expand all nodes
11901      */
11902     expandAll : function(){
11903         this.root.expand(true);
11904     },
11905
11906     /**
11907      * Collapse all nodes
11908      */
11909     collapseAll : function(){
11910         this.root.collapse(true);
11911     },
11912
11913     /**
11914      * Returns the selection model used by this TreePanel
11915      */
11916     getSelectionModel : function(){
11917         if(!this.selModel){
11918             this.selModel = new Roo.tree.DefaultSelectionModel();
11919         }
11920         return this.selModel;
11921     },
11922
11923     /**
11924      * Retrieve an array of checked nodes, or an array of a specific attribute of checked nodes (e.g. "id")
11925      * @param {String} attribute (optional) Defaults to null (return the actual nodes)
11926      * @param {TreeNode} startNode (optional) The node to start from, defaults to the root
11927      * @return {Array}
11928      */
11929     getChecked : function(a, startNode){
11930         startNode = startNode || this.root;
11931         var r = [];
11932         var f = function(){
11933             if(this.attributes.checked){
11934                 r.push(!a ? this : (a == 'id' ? this.id : this.attributes[a]));
11935             }
11936         }
11937         startNode.cascade(f);
11938         return r;
11939     },
11940
11941     /**
11942      * Expands a specified path in this TreePanel. A path can be retrieved from a node with {@link Roo.data.Node#getPath}
11943      * @param {String} path
11944      * @param {String} attr (optional) The attribute used in the path (see {@link Roo.data.Node#getPath} for more info)
11945      * @param {Function} callback (optional) The callback to call when the expand is complete. The callback will be called with
11946      * (bSuccess, oLastNode) where bSuccess is if the expand was successful and oLastNode is the last node that was expanded.
11947      */
11948     expandPath : function(path, attr, callback){
11949         attr = attr || "id";
11950         var keys = path.split(this.pathSeparator);
11951         var curNode = this.root;
11952         if(curNode.attributes[attr] != keys[1]){ // invalid root
11953             if(callback){
11954                 callback(false, null);
11955             }
11956             return;
11957         }
11958         var index = 1;
11959         var f = function(){
11960             if(++index == keys.length){
11961                 if(callback){
11962                     callback(true, curNode);
11963                 }
11964                 return;
11965             }
11966             var c = curNode.findChild(attr, keys[index]);
11967             if(!c){
11968                 if(callback){
11969                     callback(false, curNode);
11970                 }
11971                 return;
11972             }
11973             curNode = c;
11974             c.expand(false, false, f);
11975         };
11976         curNode.expand(false, false, f);
11977     },
11978
11979     /**
11980      * Selects the node in this tree at the specified path. A path can be retrieved from a node with {@link Roo.data.Node#getPath}
11981      * @param {String} path
11982      * @param {String} attr (optional) The attribute used in the path (see {@link Roo.data.Node#getPath} for more info)
11983      * @param {Function} callback (optional) The callback to call when the selection is complete. The callback will be called with
11984      * (bSuccess, oSelNode) where bSuccess is if the selection was successful and oSelNode is the selected node.
11985      */
11986     selectPath : function(path, attr, callback){
11987         attr = attr || "id";
11988         var keys = path.split(this.pathSeparator);
11989         var v = keys.pop();
11990         if(keys.length > 0){
11991             var f = function(success, node){
11992                 if(success && node){
11993                     var n = node.findChild(attr, v);
11994                     if(n){
11995                         n.select();
11996                         if(callback){
11997                             callback(true, n);
11998                         }
11999                     }else if(callback){
12000                         callback(false, n);
12001                     }
12002                 }else{
12003                     if(callback){
12004                         callback(false, n);
12005                     }
12006                 }
12007             };
12008             this.expandPath(keys.join(this.pathSeparator), attr, f);
12009         }else{
12010             this.root.select();
12011             if(callback){
12012                 callback(true, this.root);
12013             }
12014         }
12015     },
12016
12017     getTreeEl : function(){
12018         return this.el;
12019     },
12020
12021     /**
12022      * Trigger rendering of this TreePanel
12023      */
12024     render : function(){
12025         if (this.innerCt) {
12026             return this; // stop it rendering more than once!!
12027         }
12028         
12029         this.innerCt = this.el.createChild({tag:"ul",
12030                cls:"x-tree-root-ct " +
12031                (this.lines ? "x-tree-lines" : "x-tree-no-lines")});
12032
12033         if(this.containerScroll){
12034             Roo.dd.ScrollManager.register(this.el);
12035         }
12036         if((this.enableDD || this.enableDrop) && !this.dropZone){
12037            /**
12038             * The dropZone used by this tree if drop is enabled
12039             * @type Roo.tree.TreeDropZone
12040             */
12041              this.dropZone = new Roo.tree.TreeDropZone(this, this.dropConfig || {
12042                ddGroup: this.ddGroup || "TreeDD", appendOnly: this.ddAppendOnly === true
12043            });
12044         }
12045         if((this.enableDD || this.enableDrag) && !this.dragZone){
12046            /**
12047             * The dragZone used by this tree if drag is enabled
12048             * @type Roo.tree.TreeDragZone
12049             */
12050             this.dragZone = new Roo.tree.TreeDragZone(this, this.dragConfig || {
12051                ddGroup: this.ddGroup || "TreeDD",
12052                scroll: this.ddScroll
12053            });
12054         }
12055         this.getSelectionModel().init(this);
12056         if (!this.root) {
12057             Roo.log("ROOT not set in tree");
12058             return this;
12059         }
12060         this.root.render();
12061         if(!this.rootVisible){
12062             this.root.renderChildren();
12063         }
12064         return this;
12065     }
12066 });/*
12067  * Based on:
12068  * Ext JS Library 1.1.1
12069  * Copyright(c) 2006-2007, Ext JS, LLC.
12070  *
12071  * Originally Released Under LGPL - original licence link has changed is not relivant.
12072  *
12073  * Fork - LGPL
12074  * <script type="text/javascript">
12075  */
12076  
12077
12078 /**
12079  * @class Roo.tree.DefaultSelectionModel
12080  * @extends Roo.util.Observable
12081  * The default single selection for a TreePanel.
12082  * @param {Object} cfg Configuration
12083  */
12084 Roo.tree.DefaultSelectionModel = function(cfg){
12085    this.selNode = null;
12086    
12087    
12088    
12089    this.addEvents({
12090        /**
12091         * @event selectionchange
12092         * Fires when the selected node changes
12093         * @param {DefaultSelectionModel} this
12094         * @param {TreeNode} node the new selection
12095         */
12096        "selectionchange" : true,
12097
12098        /**
12099         * @event beforeselect
12100         * Fires before the selected node changes, return false to cancel the change
12101         * @param {DefaultSelectionModel} this
12102         * @param {TreeNode} node the new selection
12103         * @param {TreeNode} node the old selection
12104         */
12105        "beforeselect" : true
12106    });
12107    
12108     Roo.tree.DefaultSelectionModel.superclass.constructor.call(this,cfg);
12109 };
12110
12111 Roo.extend(Roo.tree.DefaultSelectionModel, Roo.util.Observable, {
12112     init : function(tree){
12113         this.tree = tree;
12114         tree.getTreeEl().on("keydown", this.onKeyDown, this);
12115         tree.on("click", this.onNodeClick, this);
12116     },
12117     
12118     onNodeClick : function(node, e){
12119         if (e.ctrlKey && this.selNode == node)  {
12120             this.unselect(node);
12121             return;
12122         }
12123         this.select(node);
12124     },
12125     
12126     /**
12127      * Select a node.
12128      * @param {TreeNode} node The node to select
12129      * @return {TreeNode} The selected node
12130      */
12131     select : function(node){
12132         var last = this.selNode;
12133         if(last != node && this.fireEvent('beforeselect', this, node, last) !== false){
12134             if(last){
12135                 last.ui.onSelectedChange(false);
12136             }
12137             this.selNode = node;
12138             node.ui.onSelectedChange(true);
12139             this.fireEvent("selectionchange", this, node, last);
12140         }
12141         return node;
12142     },
12143     
12144     /**
12145      * Deselect a node.
12146      * @param {TreeNode} node The node to unselect
12147      */
12148     unselect : function(node){
12149         if(this.selNode == node){
12150             this.clearSelections();
12151         }    
12152     },
12153     
12154     /**
12155      * Clear all selections
12156      */
12157     clearSelections : function(){
12158         var n = this.selNode;
12159         if(n){
12160             n.ui.onSelectedChange(false);
12161             this.selNode = null;
12162             this.fireEvent("selectionchange", this, null);
12163         }
12164         return n;
12165     },
12166     
12167     /**
12168      * Get the selected node
12169      * @return {TreeNode} The selected node
12170      */
12171     getSelectedNode : function(){
12172         return this.selNode;    
12173     },
12174     
12175     /**
12176      * Returns true if the node is selected
12177      * @param {TreeNode} node The node to check
12178      * @return {Boolean}
12179      */
12180     isSelected : function(node){
12181         return this.selNode == node;  
12182     },
12183
12184     /**
12185      * Selects the node above the selected node in the tree, intelligently walking the nodes
12186      * @return TreeNode The new selection
12187      */
12188     selectPrevious : function(){
12189         var s = this.selNode || this.lastSelNode;
12190         if(!s){
12191             return null;
12192         }
12193         var ps = s.previousSibling;
12194         if(ps){
12195             if(!ps.isExpanded() || ps.childNodes.length < 1){
12196                 return this.select(ps);
12197             } else{
12198                 var lc = ps.lastChild;
12199                 while(lc && lc.isExpanded() && lc.childNodes.length > 0){
12200                     lc = lc.lastChild;
12201                 }
12202                 return this.select(lc);
12203             }
12204         } else if(s.parentNode && (this.tree.rootVisible || !s.parentNode.isRoot)){
12205             return this.select(s.parentNode);
12206         }
12207         return null;
12208     },
12209
12210     /**
12211      * Selects the node above the selected node in the tree, intelligently walking the nodes
12212      * @return TreeNode The new selection
12213      */
12214     selectNext : function(){
12215         var s = this.selNode || this.lastSelNode;
12216         if(!s){
12217             return null;
12218         }
12219         if(s.firstChild && s.isExpanded()){
12220              return this.select(s.firstChild);
12221          }else if(s.nextSibling){
12222              return this.select(s.nextSibling);
12223          }else if(s.parentNode){
12224             var newS = null;
12225             s.parentNode.bubble(function(){
12226                 if(this.nextSibling){
12227                     newS = this.getOwnerTree().selModel.select(this.nextSibling);
12228                     return false;
12229                 }
12230             });
12231             return newS;
12232          }
12233         return null;
12234     },
12235
12236     onKeyDown : function(e){
12237         var s = this.selNode || this.lastSelNode;
12238         // undesirable, but required
12239         var sm = this;
12240         if(!s){
12241             return;
12242         }
12243         var k = e.getKey();
12244         switch(k){
12245              case e.DOWN:
12246                  e.stopEvent();
12247                  this.selectNext();
12248              break;
12249              case e.UP:
12250                  e.stopEvent();
12251                  this.selectPrevious();
12252              break;
12253              case e.RIGHT:
12254                  e.preventDefault();
12255                  if(s.hasChildNodes()){
12256                      if(!s.isExpanded()){
12257                          s.expand();
12258                      }else if(s.firstChild){
12259                          this.select(s.firstChild, e);
12260                      }
12261                  }
12262              break;
12263              case e.LEFT:
12264                  e.preventDefault();
12265                  if(s.hasChildNodes() && s.isExpanded()){
12266                      s.collapse();
12267                  }else if(s.parentNode && (this.tree.rootVisible || s.parentNode != this.tree.getRootNode())){
12268                      this.select(s.parentNode, e);
12269                  }
12270              break;
12271         };
12272     }
12273 });
12274
12275 /**
12276  * @class Roo.tree.MultiSelectionModel
12277  * @extends Roo.util.Observable
12278  * Multi selection for a TreePanel.
12279  * @param {Object} cfg Configuration
12280  */
12281 Roo.tree.MultiSelectionModel = function(){
12282    this.selNodes = [];
12283    this.selMap = {};
12284    this.addEvents({
12285        /**
12286         * @event selectionchange
12287         * Fires when the selected nodes change
12288         * @param {MultiSelectionModel} this
12289         * @param {Array} nodes Array of the selected nodes
12290         */
12291        "selectionchange" : true
12292    });
12293    Roo.tree.MultiSelectionModel.superclass.constructor.call(this,cfg);
12294    
12295 };
12296
12297 Roo.extend(Roo.tree.MultiSelectionModel, Roo.util.Observable, {
12298     init : function(tree){
12299         this.tree = tree;
12300         tree.getTreeEl().on("keydown", this.onKeyDown, this);
12301         tree.on("click", this.onNodeClick, this);
12302     },
12303     
12304     onNodeClick : function(node, e){
12305         this.select(node, e, e.ctrlKey);
12306     },
12307     
12308     /**
12309      * Select a node.
12310      * @param {TreeNode} node The node to select
12311      * @param {EventObject} e (optional) An event associated with the selection
12312      * @param {Boolean} keepExisting True to retain existing selections
12313      * @return {TreeNode} The selected node
12314      */
12315     select : function(node, e, keepExisting){
12316         if(keepExisting !== true){
12317             this.clearSelections(true);
12318         }
12319         if(this.isSelected(node)){
12320             this.lastSelNode = node;
12321             return node;
12322         }
12323         this.selNodes.push(node);
12324         this.selMap[node.id] = node;
12325         this.lastSelNode = node;
12326         node.ui.onSelectedChange(true);
12327         this.fireEvent("selectionchange", this, this.selNodes);
12328         return node;
12329     },
12330     
12331     /**
12332      * Deselect a node.
12333      * @param {TreeNode} node The node to unselect
12334      */
12335     unselect : function(node){
12336         if(this.selMap[node.id]){
12337             node.ui.onSelectedChange(false);
12338             var sn = this.selNodes;
12339             var index = -1;
12340             if(sn.indexOf){
12341                 index = sn.indexOf(node);
12342             }else{
12343                 for(var i = 0, len = sn.length; i < len; i++){
12344                     if(sn[i] == node){
12345                         index = i;
12346                         break;
12347                     }
12348                 }
12349             }
12350             if(index != -1){
12351                 this.selNodes.splice(index, 1);
12352             }
12353             delete this.selMap[node.id];
12354             this.fireEvent("selectionchange", this, this.selNodes);
12355         }
12356     },
12357     
12358     /**
12359      * Clear all selections
12360      */
12361     clearSelections : function(suppressEvent){
12362         var sn = this.selNodes;
12363         if(sn.length > 0){
12364             for(var i = 0, len = sn.length; i < len; i++){
12365                 sn[i].ui.onSelectedChange(false);
12366             }
12367             this.selNodes = [];
12368             this.selMap = {};
12369             if(suppressEvent !== true){
12370                 this.fireEvent("selectionchange", this, this.selNodes);
12371             }
12372         }
12373     },
12374     
12375     /**
12376      * Returns true if the node is selected
12377      * @param {TreeNode} node The node to check
12378      * @return {Boolean}
12379      */
12380     isSelected : function(node){
12381         return this.selMap[node.id] ? true : false;  
12382     },
12383     
12384     /**
12385      * Returns an array of the selected nodes
12386      * @return {Array}
12387      */
12388     getSelectedNodes : function(){
12389         return this.selNodes;    
12390     },
12391
12392     onKeyDown : Roo.tree.DefaultSelectionModel.prototype.onKeyDown,
12393
12394     selectNext : Roo.tree.DefaultSelectionModel.prototype.selectNext,
12395
12396     selectPrevious : Roo.tree.DefaultSelectionModel.prototype.selectPrevious
12397 });/*
12398  * Based on:
12399  * Ext JS Library 1.1.1
12400  * Copyright(c) 2006-2007, Ext JS, LLC.
12401  *
12402  * Originally Released Under LGPL - original licence link has changed is not relivant.
12403  *
12404  * Fork - LGPL
12405  * <script type="text/javascript">
12406  */
12407  
12408 /**
12409  * @class Roo.tree.TreeNode
12410  * @extends Roo.data.Node
12411  * @cfg {String} text The text for this node
12412  * @cfg {Boolean} expanded true to start the node expanded
12413  * @cfg {Boolean} allowDrag false to make this node undraggable if DD is on (defaults to true)
12414  * @cfg {Boolean} allowDrop false if this node cannot be drop on
12415  * @cfg {Boolean} disabled true to start the node disabled
12416  * @cfg {String} icon The path to an icon for the node. The preferred way to do this
12417  *    is to use the cls or iconCls attributes and add the icon via a CSS background image.
12418  * @cfg {String} cls A css class to be added to the node
12419  * @cfg {String} iconCls A css class to be added to the nodes icon element for applying css background images
12420  * @cfg {String} href URL of the link used for the node (defaults to #)
12421  * @cfg {String} hrefTarget target frame for the link
12422  * @cfg {String} qtip An Ext QuickTip for the node
12423  * @cfg {String} qtipCfg An Ext QuickTip config for the node (used instead of qtip)
12424  * @cfg {Boolean} singleClickExpand True for single click expand on this node
12425  * @cfg {Function} uiProvider A UI <b>class</b> to use for this node (defaults to Roo.tree.TreeNodeUI)
12426  * @cfg {Boolean} checked True to render a checked checkbox for this node, false to render an unchecked checkbox
12427  * (defaults to undefined with no checkbox rendered)
12428  * @constructor
12429  * @param {Object/String} attributes The attributes/config for the node or just a string with the text for the node
12430  */
12431 Roo.tree.TreeNode = function(attributes){
12432     attributes = attributes || {};
12433     if(typeof attributes == "string"){
12434         attributes = {text: attributes};
12435     }
12436     this.childrenRendered = false;
12437     this.rendered = false;
12438     Roo.tree.TreeNode.superclass.constructor.call(this, attributes);
12439     this.expanded = attributes.expanded === true;
12440     this.isTarget = attributes.isTarget !== false;
12441     this.draggable = attributes.draggable !== false && attributes.allowDrag !== false;
12442     this.allowChildren = attributes.allowChildren !== false && attributes.allowDrop !== false;
12443
12444     /**
12445      * Read-only. The text for this node. To change it use setText().
12446      * @type String
12447      */
12448     this.text = attributes.text;
12449     /**
12450      * True if this node is disabled.
12451      * @type Boolean
12452      */
12453     this.disabled = attributes.disabled === true;
12454
12455     this.addEvents({
12456         /**
12457         * @event textchange
12458         * Fires when the text for this node is changed
12459         * @param {Node} this This node
12460         * @param {String} text The new text
12461         * @param {String} oldText The old text
12462         */
12463         "textchange" : true,
12464         /**
12465         * @event beforeexpand
12466         * Fires before this node is expanded, return false to cancel.
12467         * @param {Node} this This node
12468         * @param {Boolean} deep
12469         * @param {Boolean} anim
12470         */
12471         "beforeexpand" : true,
12472         /**
12473         * @event beforecollapse
12474         * Fires before this node is collapsed, return false to cancel.
12475         * @param {Node} this This node
12476         * @param {Boolean} deep
12477         * @param {Boolean} anim
12478         */
12479         "beforecollapse" : true,
12480         /**
12481         * @event expand
12482         * Fires when this node is expanded
12483         * @param {Node} this This node
12484         */
12485         "expand" : true,
12486         /**
12487         * @event disabledchange
12488         * Fires when the disabled status of this node changes
12489         * @param {Node} this This node
12490         * @param {Boolean} disabled
12491         */
12492         "disabledchange" : true,
12493         /**
12494         * @event collapse
12495         * Fires when this node is collapsed
12496         * @param {Node} this This node
12497         */
12498         "collapse" : true,
12499         /**
12500         * @event beforeclick
12501         * Fires before click processing. Return false to cancel the default action.
12502         * @param {Node} this This node
12503         * @param {Roo.EventObject} e The event object
12504         */
12505         "beforeclick":true,
12506         /**
12507         * @event checkchange
12508         * Fires when a node with a checkbox's checked property changes
12509         * @param {Node} this This node
12510         * @param {Boolean} checked
12511         */
12512         "checkchange":true,
12513         /**
12514         * @event click
12515         * Fires when this node is clicked
12516         * @param {Node} this This node
12517         * @param {Roo.EventObject} e The event object
12518         */
12519         "click":true,
12520         /**
12521         * @event dblclick
12522         * Fires when this node is double clicked
12523         * @param {Node} this This node
12524         * @param {Roo.EventObject} e The event object
12525         */
12526         "dblclick":true,
12527         /**
12528         * @event contextmenu
12529         * Fires when this node is right clicked
12530         * @param {Node} this This node
12531         * @param {Roo.EventObject} e The event object
12532         */
12533         "contextmenu":true,
12534         /**
12535         * @event beforechildrenrendered
12536         * Fires right before the child nodes for this node are rendered
12537         * @param {Node} this This node
12538         */
12539         "beforechildrenrendered":true
12540     });
12541
12542     var uiClass = this.attributes.uiProvider || Roo.tree.TreeNodeUI;
12543
12544     /**
12545      * Read-only. The UI for this node
12546      * @type TreeNodeUI
12547      */
12548     this.ui = new uiClass(this);
12549     
12550     // finally support items[]
12551     if (typeof(this.attributes.items) == 'undefined' || !this.attributes.items) {
12552         return;
12553     }
12554     
12555     
12556     Roo.each(this.attributes.items, function(c) {
12557         this.appendChild(Roo.factory(c,Roo.Tree));
12558     }, this);
12559     delete this.attributes.items;
12560     
12561     
12562     
12563 };
12564 Roo.extend(Roo.tree.TreeNode, Roo.data.Node, {
12565     preventHScroll: true,
12566     /**
12567      * Returns true if this node is expanded
12568      * @return {Boolean}
12569      */
12570     isExpanded : function(){
12571         return this.expanded;
12572     },
12573
12574     /**
12575      * Returns the UI object for this node
12576      * @return {TreeNodeUI}
12577      */
12578     getUI : function(){
12579         return this.ui;
12580     },
12581
12582     // private override
12583     setFirstChild : function(node){
12584         var of = this.firstChild;
12585         Roo.tree.TreeNode.superclass.setFirstChild.call(this, node);
12586         if(this.childrenRendered && of && node != of){
12587             of.renderIndent(true, true);
12588         }
12589         if(this.rendered){
12590             this.renderIndent(true, true);
12591         }
12592     },
12593
12594     // private override
12595     setLastChild : function(node){
12596         var ol = this.lastChild;
12597         Roo.tree.TreeNode.superclass.setLastChild.call(this, node);
12598         if(this.childrenRendered && ol && node != ol){
12599             ol.renderIndent(true, true);
12600         }
12601         if(this.rendered){
12602             this.renderIndent(true, true);
12603         }
12604     },
12605
12606     // these methods are overridden to provide lazy rendering support
12607     // private override
12608     appendChild : function()
12609     {
12610         var node = Roo.tree.TreeNode.superclass.appendChild.apply(this, arguments);
12611         if(node && this.childrenRendered){
12612             node.render();
12613         }
12614         this.ui.updateExpandIcon();
12615         return node;
12616     },
12617
12618     // private override
12619     removeChild : function(node){
12620         this.ownerTree.getSelectionModel().unselect(node);
12621         Roo.tree.TreeNode.superclass.removeChild.apply(this, arguments);
12622         // if it's been rendered remove dom node
12623         if(this.childrenRendered){
12624             node.ui.remove();
12625         }
12626         if(this.childNodes.length < 1){
12627             this.collapse(false, false);
12628         }else{
12629             this.ui.updateExpandIcon();
12630         }
12631         if(!this.firstChild) {
12632             this.childrenRendered = false;
12633         }
12634         return node;
12635     },
12636
12637     // private override
12638     insertBefore : function(node, refNode){
12639         var newNode = Roo.tree.TreeNode.superclass.insertBefore.apply(this, arguments);
12640         if(newNode && refNode && this.childrenRendered){
12641             node.render();
12642         }
12643         this.ui.updateExpandIcon();
12644         return newNode;
12645     },
12646
12647     /**
12648      * Sets the text for this node
12649      * @param {String} text
12650      */
12651     setText : function(text){
12652         var oldText = this.text;
12653         this.text = text;
12654         this.attributes.text = text;
12655         if(this.rendered){ // event without subscribing
12656             this.ui.onTextChange(this, text, oldText);
12657         }
12658         this.fireEvent("textchange", this, text, oldText);
12659     },
12660
12661     /**
12662      * Triggers selection of this node
12663      */
12664     select : function(){
12665         this.getOwnerTree().getSelectionModel().select(this);
12666     },
12667
12668     /**
12669      * Triggers deselection of this node
12670      */
12671     unselect : function(){
12672         this.getOwnerTree().getSelectionModel().unselect(this);
12673     },
12674
12675     /**
12676      * Returns true if this node is selected
12677      * @return {Boolean}
12678      */
12679     isSelected : function(){
12680         return this.getOwnerTree().getSelectionModel().isSelected(this);
12681     },
12682
12683     /**
12684      * Expand this node.
12685      * @param {Boolean} deep (optional) True to expand all children as well
12686      * @param {Boolean} anim (optional) false to cancel the default animation
12687      * @param {Function} callback (optional) A callback to be called when
12688      * expanding this node completes (does not wait for deep expand to complete).
12689      * Called with 1 parameter, this node.
12690      */
12691     expand : function(deep, anim, callback){
12692         if(!this.expanded){
12693             if(this.fireEvent("beforeexpand", this, deep, anim) === false){
12694                 return;
12695             }
12696             if(!this.childrenRendered){
12697                 this.renderChildren();
12698             }
12699             this.expanded = true;
12700             
12701             if(!this.isHiddenRoot() && (this.getOwnerTree() && this.getOwnerTree().animate && anim !== false) || anim){
12702                 this.ui.animExpand(function(){
12703                     this.fireEvent("expand", this);
12704                     if(typeof callback == "function"){
12705                         callback(this);
12706                     }
12707                     if(deep === true){
12708                         this.expandChildNodes(true);
12709                     }
12710                 }.createDelegate(this));
12711                 return;
12712             }else{
12713                 this.ui.expand();
12714                 this.fireEvent("expand", this);
12715                 if(typeof callback == "function"){
12716                     callback(this);
12717                 }
12718             }
12719         }else{
12720            if(typeof callback == "function"){
12721                callback(this);
12722            }
12723         }
12724         if(deep === true){
12725             this.expandChildNodes(true);
12726         }
12727     },
12728
12729     isHiddenRoot : function(){
12730         return this.isRoot && !this.getOwnerTree().rootVisible;
12731     },
12732
12733     /**
12734      * Collapse this node.
12735      * @param {Boolean} deep (optional) True to collapse all children as well
12736      * @param {Boolean} anim (optional) false to cancel the default animation
12737      */
12738     collapse : function(deep, anim){
12739         if(this.expanded && !this.isHiddenRoot()){
12740             if(this.fireEvent("beforecollapse", this, deep, anim) === false){
12741                 return;
12742             }
12743             this.expanded = false;
12744             if((this.getOwnerTree().animate && anim !== false) || anim){
12745                 this.ui.animCollapse(function(){
12746                     this.fireEvent("collapse", this);
12747                     if(deep === true){
12748                         this.collapseChildNodes(true);
12749                     }
12750                 }.createDelegate(this));
12751                 return;
12752             }else{
12753                 this.ui.collapse();
12754                 this.fireEvent("collapse", this);
12755             }
12756         }
12757         if(deep === true){
12758             var cs = this.childNodes;
12759             for(var i = 0, len = cs.length; i < len; i++) {
12760                 cs[i].collapse(true, false);
12761             }
12762         }
12763     },
12764
12765     // private
12766     delayedExpand : function(delay){
12767         if(!this.expandProcId){
12768             this.expandProcId = this.expand.defer(delay, this);
12769         }
12770     },
12771
12772     // private
12773     cancelExpand : function(){
12774         if(this.expandProcId){
12775             clearTimeout(this.expandProcId);
12776         }
12777         this.expandProcId = false;
12778     },
12779
12780     /**
12781      * Toggles expanded/collapsed state of the node
12782      */
12783     toggle : function(){
12784         if(this.expanded){
12785             this.collapse();
12786         }else{
12787             this.expand();
12788         }
12789     },
12790
12791     /**
12792      * Ensures all parent nodes are expanded
12793      */
12794     ensureVisible : function(callback){
12795         var tree = this.getOwnerTree();
12796         tree.expandPath(this.parentNode.getPath(), false, function(){
12797             tree.getTreeEl().scrollChildIntoView(this.ui.anchor);
12798             Roo.callback(callback);
12799         }.createDelegate(this));
12800     },
12801
12802     /**
12803      * Expand all child nodes
12804      * @param {Boolean} deep (optional) true if the child nodes should also expand their child nodes
12805      */
12806     expandChildNodes : function(deep){
12807         var cs = this.childNodes;
12808         for(var i = 0, len = cs.length; i < len; i++) {
12809                 cs[i].expand(deep);
12810         }
12811     },
12812
12813     /**
12814      * Collapse all child nodes
12815      * @param {Boolean} deep (optional) true if the child nodes should also collapse their child nodes
12816      */
12817     collapseChildNodes : function(deep){
12818         var cs = this.childNodes;
12819         for(var i = 0, len = cs.length; i < len; i++) {
12820                 cs[i].collapse(deep);
12821         }
12822     },
12823
12824     /**
12825      * Disables this node
12826      */
12827     disable : function(){
12828         this.disabled = true;
12829         this.unselect();
12830         if(this.rendered && this.ui.onDisableChange){ // event without subscribing
12831             this.ui.onDisableChange(this, true);
12832         }
12833         this.fireEvent("disabledchange", this, true);
12834     },
12835
12836     /**
12837      * Enables this node
12838      */
12839     enable : function(){
12840         this.disabled = false;
12841         if(this.rendered && this.ui.onDisableChange){ // event without subscribing
12842             this.ui.onDisableChange(this, false);
12843         }
12844         this.fireEvent("disabledchange", this, false);
12845     },
12846
12847     // private
12848     renderChildren : function(suppressEvent){
12849         if(suppressEvent !== false){
12850             this.fireEvent("beforechildrenrendered", this);
12851         }
12852         var cs = this.childNodes;
12853         for(var i = 0, len = cs.length; i < len; i++){
12854             cs[i].render(true);
12855         }
12856         this.childrenRendered = true;
12857     },
12858
12859     // private
12860     sort : function(fn, scope){
12861         Roo.tree.TreeNode.superclass.sort.apply(this, arguments);
12862         if(this.childrenRendered){
12863             var cs = this.childNodes;
12864             for(var i = 0, len = cs.length; i < len; i++){
12865                 cs[i].render(true);
12866             }
12867         }
12868     },
12869
12870     // private
12871     render : function(bulkRender){
12872         this.ui.render(bulkRender);
12873         if(!this.rendered){
12874             this.rendered = true;
12875             if(this.expanded){
12876                 this.expanded = false;
12877                 this.expand(false, false);
12878             }
12879         }
12880     },
12881
12882     // private
12883     renderIndent : function(deep, refresh){
12884         if(refresh){
12885             this.ui.childIndent = null;
12886         }
12887         this.ui.renderIndent();
12888         if(deep === true && this.childrenRendered){
12889             var cs = this.childNodes;
12890             for(var i = 0, len = cs.length; i < len; i++){
12891                 cs[i].renderIndent(true, refresh);
12892             }
12893         }
12894     }
12895 });/*
12896  * Based on:
12897  * Ext JS Library 1.1.1
12898  * Copyright(c) 2006-2007, Ext JS, LLC.
12899  *
12900  * Originally Released Under LGPL - original licence link has changed is not relivant.
12901  *
12902  * Fork - LGPL
12903  * <script type="text/javascript">
12904  */
12905  
12906 /**
12907  * @class Roo.tree.AsyncTreeNode
12908  * @extends Roo.tree.TreeNode
12909  * @cfg {TreeLoader} loader A TreeLoader to be used by this node (defaults to the loader defined on the tree)
12910  * @constructor
12911  * @param {Object/String} attributes The attributes/config for the node or just a string with the text for the node 
12912  */
12913  Roo.tree.AsyncTreeNode = function(config){
12914     this.loaded = false;
12915     this.loading = false;
12916     Roo.tree.AsyncTreeNode.superclass.constructor.apply(this, arguments);
12917     /**
12918     * @event beforeload
12919     * Fires before this node is loaded, return false to cancel
12920     * @param {Node} this This node
12921     */
12922     this.addEvents({'beforeload':true, 'load': true});
12923     /**
12924     * @event load
12925     * Fires when this node is loaded
12926     * @param {Node} this This node
12927     */
12928     /**
12929      * The loader used by this node (defaults to using the tree's defined loader)
12930      * @type TreeLoader
12931      * @property loader
12932      */
12933 };
12934 Roo.extend(Roo.tree.AsyncTreeNode, Roo.tree.TreeNode, {
12935     expand : function(deep, anim, callback){
12936         if(this.loading){ // if an async load is already running, waiting til it's done
12937             var timer;
12938             var f = function(){
12939                 if(!this.loading){ // done loading
12940                     clearInterval(timer);
12941                     this.expand(deep, anim, callback);
12942                 }
12943             }.createDelegate(this);
12944             timer = setInterval(f, 200);
12945             return;
12946         }
12947         if(!this.loaded){
12948             if(this.fireEvent("beforeload", this) === false){
12949                 return;
12950             }
12951             this.loading = true;
12952             this.ui.beforeLoad(this);
12953             var loader = this.loader || this.attributes.loader || this.getOwnerTree().getLoader();
12954             if(loader){
12955                 loader.load(this, this.loadComplete.createDelegate(this, [deep, anim, callback]));
12956                 return;
12957             }
12958         }
12959         Roo.tree.AsyncTreeNode.superclass.expand.call(this, deep, anim, callback);
12960     },
12961     
12962     /**
12963      * Returns true if this node is currently loading
12964      * @return {Boolean}
12965      */
12966     isLoading : function(){
12967         return this.loading;  
12968     },
12969     
12970     loadComplete : function(deep, anim, callback){
12971         this.loading = false;
12972         this.loaded = true;
12973         this.ui.afterLoad(this);
12974         this.fireEvent("load", this);
12975         this.expand(deep, anim, callback);
12976     },
12977     
12978     /**
12979      * Returns true if this node has been loaded
12980      * @return {Boolean}
12981      */
12982     isLoaded : function(){
12983         return this.loaded;
12984     },
12985     
12986     hasChildNodes : function(){
12987         if(!this.isLeaf() && !this.loaded){
12988             return true;
12989         }else{
12990             return Roo.tree.AsyncTreeNode.superclass.hasChildNodes.call(this);
12991         }
12992     },
12993
12994     /**
12995      * Trigger a reload for this node
12996      * @param {Function} callback
12997      */
12998     reload : function(callback){
12999         this.collapse(false, false);
13000         while(this.firstChild){
13001             this.removeChild(this.firstChild);
13002         }
13003         this.childrenRendered = false;
13004         this.loaded = false;
13005         if(this.isHiddenRoot()){
13006             this.expanded = false;
13007         }
13008         this.expand(false, false, callback);
13009     }
13010 });/*
13011  * Based on:
13012  * Ext JS Library 1.1.1
13013  * Copyright(c) 2006-2007, Ext JS, LLC.
13014  *
13015  * Originally Released Under LGPL - original licence link has changed is not relivant.
13016  *
13017  * Fork - LGPL
13018  * <script type="text/javascript">
13019  */
13020  
13021 /**
13022  * @class Roo.tree.TreeNodeUI
13023  * @constructor
13024  * @param {Object} node The node to render
13025  * The TreeNode UI implementation is separate from the
13026  * tree implementation. Unless you are customizing the tree UI,
13027  * you should never have to use this directly.
13028  */
13029 Roo.tree.TreeNodeUI = function(node){
13030     this.node = node;
13031     this.rendered = false;
13032     this.animating = false;
13033     this.emptyIcon = Roo.BLANK_IMAGE_URL;
13034 };
13035
13036 Roo.tree.TreeNodeUI.prototype = {
13037     removeChild : function(node){
13038         if(this.rendered){
13039             this.ctNode.removeChild(node.ui.getEl());
13040         }
13041     },
13042
13043     beforeLoad : function(){
13044          this.addClass("x-tree-node-loading");
13045     },
13046
13047     afterLoad : function(){
13048          this.removeClass("x-tree-node-loading");
13049     },
13050
13051     onTextChange : function(node, text, oldText){
13052         if(this.rendered){
13053             this.textNode.innerHTML = text;
13054         }
13055     },
13056
13057     onDisableChange : function(node, state){
13058         this.disabled = state;
13059         if(state){
13060             this.addClass("x-tree-node-disabled");
13061         }else{
13062             this.removeClass("x-tree-node-disabled");
13063         }
13064     },
13065
13066     onSelectedChange : function(state){
13067         if(state){
13068             this.focus();
13069             this.addClass("x-tree-selected");
13070         }else{
13071             //this.blur();
13072             this.removeClass("x-tree-selected");
13073         }
13074     },
13075
13076     onMove : function(tree, node, oldParent, newParent, index, refNode){
13077         this.childIndent = null;
13078         if(this.rendered){
13079             var targetNode = newParent.ui.getContainer();
13080             if(!targetNode){//target not rendered
13081                 this.holder = document.createElement("div");
13082                 this.holder.appendChild(this.wrap);
13083                 return;
13084             }
13085             var insertBefore = refNode ? refNode.ui.getEl() : null;
13086             if(insertBefore){
13087                 targetNode.insertBefore(this.wrap, insertBefore);
13088             }else{
13089                 targetNode.appendChild(this.wrap);
13090             }
13091             this.node.renderIndent(true);
13092         }
13093     },
13094
13095     addClass : function(cls){
13096         if(this.elNode){
13097             Roo.fly(this.elNode).addClass(cls);
13098         }
13099     },
13100
13101     removeClass : function(cls){
13102         if(this.elNode){
13103             Roo.fly(this.elNode).removeClass(cls);
13104         }
13105     },
13106
13107     remove : function(){
13108         if(this.rendered){
13109             this.holder = document.createElement("div");
13110             this.holder.appendChild(this.wrap);
13111         }
13112     },
13113
13114     fireEvent : function(){
13115         return this.node.fireEvent.apply(this.node, arguments);
13116     },
13117
13118     initEvents : function(){
13119         this.node.on("move", this.onMove, this);
13120         var E = Roo.EventManager;
13121         var a = this.anchor;
13122
13123         var el = Roo.fly(a, '_treeui');
13124
13125         if(Roo.isOpera){ // opera render bug ignores the CSS
13126             el.setStyle("text-decoration", "none");
13127         }
13128
13129         el.on("click", this.onClick, this);
13130         el.on("dblclick", this.onDblClick, this);
13131
13132         if(this.checkbox){
13133             Roo.EventManager.on(this.checkbox,
13134                     Roo.isIE ? 'click' : 'change', this.onCheckChange, this);
13135         }
13136
13137         el.on("contextmenu", this.onContextMenu, this);
13138
13139         var icon = Roo.fly(this.iconNode);
13140         icon.on("click", this.onClick, this);
13141         icon.on("dblclick", this.onDblClick, this);
13142         icon.on("contextmenu", this.onContextMenu, this);
13143         E.on(this.ecNode, "click", this.ecClick, this, true);
13144
13145         if(this.node.disabled){
13146             this.addClass("x-tree-node-disabled");
13147         }
13148         if(this.node.hidden){
13149             this.addClass("x-tree-node-disabled");
13150         }
13151         var ot = this.node.getOwnerTree();
13152         var dd = ot ? (ot.enableDD || ot.enableDrag || ot.enableDrop) : false;
13153         if(dd && (!this.node.isRoot || ot.rootVisible)){
13154             Roo.dd.Registry.register(this.elNode, {
13155                 node: this.node,
13156                 handles: this.getDDHandles(),
13157                 isHandle: false
13158             });
13159         }
13160     },
13161
13162     getDDHandles : function(){
13163         return [this.iconNode, this.textNode];
13164     },
13165
13166     hide : function(){
13167         if(this.rendered){
13168             this.wrap.style.display = "none";
13169         }
13170     },
13171
13172     show : function(){
13173         if(this.rendered){
13174             this.wrap.style.display = "";
13175         }
13176     },
13177
13178     onContextMenu : function(e){
13179         if (this.node.hasListener("contextmenu") || this.node.getOwnerTree().hasListener("contextmenu")) {
13180             e.preventDefault();
13181             this.focus();
13182             this.fireEvent("contextmenu", this.node, e);
13183         }
13184     },
13185
13186     onClick : function(e){
13187         if(this.dropping){
13188             e.stopEvent();
13189             return;
13190         }
13191         if(this.fireEvent("beforeclick", this.node, e) !== false){
13192             if(!this.disabled && this.node.attributes.href){
13193                 this.fireEvent("click", this.node, e);
13194                 return;
13195             }
13196             e.preventDefault();
13197             if(this.disabled){
13198                 return;
13199             }
13200
13201             if(this.node.attributes.singleClickExpand && !this.animating && this.node.hasChildNodes()){
13202                 this.node.toggle();
13203             }
13204
13205             this.fireEvent("click", this.node, e);
13206         }else{
13207             e.stopEvent();
13208         }
13209     },
13210
13211     onDblClick : function(e){
13212         e.preventDefault();
13213         if(this.disabled){
13214             return;
13215         }
13216         if(this.checkbox){
13217             this.toggleCheck();
13218         }
13219         if(!this.animating && this.node.hasChildNodes()){
13220             this.node.toggle();
13221         }
13222         this.fireEvent("dblclick", this.node, e);
13223     },
13224
13225     onCheckChange : function(){
13226         var checked = this.checkbox.checked;
13227         this.node.attributes.checked = checked;
13228         this.fireEvent('checkchange', this.node, checked);
13229     },
13230
13231     ecClick : function(e){
13232         if(!this.animating && this.node.hasChildNodes()){
13233             this.node.toggle();
13234         }
13235     },
13236
13237     startDrop : function(){
13238         this.dropping = true;
13239     },
13240
13241     // delayed drop so the click event doesn't get fired on a drop
13242     endDrop : function(){
13243        setTimeout(function(){
13244            this.dropping = false;
13245        }.createDelegate(this), 50);
13246     },
13247
13248     expand : function(){
13249         this.updateExpandIcon();
13250         this.ctNode.style.display = "";
13251     },
13252
13253     focus : function(){
13254         if(!this.node.preventHScroll){
13255             try{this.anchor.focus();
13256             }catch(e){}
13257         }else if(!Roo.isIE){
13258             try{
13259                 var noscroll = this.node.getOwnerTree().getTreeEl().dom;
13260                 var l = noscroll.scrollLeft;
13261                 this.anchor.focus();
13262                 noscroll.scrollLeft = l;
13263             }catch(e){}
13264         }
13265     },
13266
13267     toggleCheck : function(value){
13268         var cb = this.checkbox;
13269         if(cb){
13270             cb.checked = (value === undefined ? !cb.checked : value);
13271         }
13272     },
13273
13274     blur : function(){
13275         try{
13276             this.anchor.blur();
13277         }catch(e){}
13278     },
13279
13280     animExpand : function(callback){
13281         var ct = Roo.get(this.ctNode);
13282         ct.stopFx();
13283         if(!this.node.hasChildNodes()){
13284             this.updateExpandIcon();
13285             this.ctNode.style.display = "";
13286             Roo.callback(callback);
13287             return;
13288         }
13289         this.animating = true;
13290         this.updateExpandIcon();
13291
13292         ct.slideIn('t', {
13293            callback : function(){
13294                this.animating = false;
13295                Roo.callback(callback);
13296             },
13297             scope: this,
13298             duration: this.node.ownerTree.duration || .25
13299         });
13300     },
13301
13302     highlight : function(){
13303         var tree = this.node.getOwnerTree();
13304         Roo.fly(this.wrap).highlight(
13305             tree.hlColor || "C3DAF9",
13306             {endColor: tree.hlBaseColor}
13307         );
13308     },
13309
13310     collapse : function(){
13311         this.updateExpandIcon();
13312         this.ctNode.style.display = "none";
13313     },
13314
13315     animCollapse : function(callback){
13316         var ct = Roo.get(this.ctNode);
13317         ct.enableDisplayMode('block');
13318         ct.stopFx();
13319
13320         this.animating = true;
13321         this.updateExpandIcon();
13322
13323         ct.slideOut('t', {
13324             callback : function(){
13325                this.animating = false;
13326                Roo.callback(callback);
13327             },
13328             scope: this,
13329             duration: this.node.ownerTree.duration || .25
13330         });
13331     },
13332
13333     getContainer : function(){
13334         return this.ctNode;
13335     },
13336
13337     getEl : function(){
13338         return this.wrap;
13339     },
13340
13341     appendDDGhost : function(ghostNode){
13342         ghostNode.appendChild(this.elNode.cloneNode(true));
13343     },
13344
13345     getDDRepairXY : function(){
13346         return Roo.lib.Dom.getXY(this.iconNode);
13347     },
13348
13349     onRender : function(){
13350         this.render();
13351     },
13352
13353     render : function(bulkRender){
13354         var n = this.node, a = n.attributes;
13355         var targetNode = n.parentNode ?
13356               n.parentNode.ui.getContainer() : n.ownerTree.innerCt.dom;
13357
13358         if(!this.rendered){
13359             this.rendered = true;
13360
13361             this.renderElements(n, a, targetNode, bulkRender);
13362
13363             if(a.qtip){
13364                if(this.textNode.setAttributeNS){
13365                    this.textNode.setAttributeNS("ext", "qtip", a.qtip);
13366                    if(a.qtipTitle){
13367                        this.textNode.setAttributeNS("ext", "qtitle", a.qtipTitle);
13368                    }
13369                }else{
13370                    this.textNode.setAttribute("ext:qtip", a.qtip);
13371                    if(a.qtipTitle){
13372                        this.textNode.setAttribute("ext:qtitle", a.qtipTitle);
13373                    }
13374                }
13375             }else if(a.qtipCfg){
13376                 a.qtipCfg.target = Roo.id(this.textNode);
13377                 Roo.QuickTips.register(a.qtipCfg);
13378             }
13379             this.initEvents();
13380             if(!this.node.expanded){
13381                 this.updateExpandIcon();
13382             }
13383         }else{
13384             if(bulkRender === true) {
13385                 targetNode.appendChild(this.wrap);
13386             }
13387         }
13388     },
13389
13390     renderElements : function(n, a, targetNode, bulkRender)
13391     {
13392         // add some indent caching, this helps performance when rendering a large tree
13393         this.indentMarkup = n.parentNode ? n.parentNode.ui.getChildIndent() : '';
13394         var t = n.getOwnerTree();
13395         var txt = t && t.renderer ? t.renderer(n.attributes) : Roo.util.Format.htmlEncode(n.text);
13396         if (typeof(n.attributes.html) != 'undefined') {
13397             txt = n.attributes.html;
13398         }
13399         var tip = t && t.rendererTip ? t.rendererTip(n.attributes) : txt;
13400         var cb = typeof a.checked == 'boolean';
13401         var href = a.href ? a.href : Roo.isGecko ? "" : "#";
13402         var buf = ['<li class="x-tree-node"><div class="x-tree-node-el ', a.cls,'">',
13403             '<span class="x-tree-node-indent">',this.indentMarkup,"</span>",
13404             '<img src="', this.emptyIcon, '" class="x-tree-ec-icon" />',
13405             '<img src="', a.icon || this.emptyIcon, '" class="x-tree-node-icon',(a.icon ? " x-tree-node-inline-icon" : ""),(a.iconCls ? " "+a.iconCls : ""),'" unselectable="on" />',
13406             cb ? ('<input class="x-tree-node-cb" type="checkbox" ' + (a.checked ? 'checked="checked" />' : ' />')) : '',
13407             '<a hidefocus="on" href="',href,'" tabIndex="1" ',
13408              a.hrefTarget ? ' target="'+a.hrefTarget+'"' : "", 
13409                 '><span unselectable="on" qtip="' , tip ,'">',txt,"</span></a></div>",
13410             '<ul class="x-tree-node-ct" style="display:none;"></ul>',
13411             "</li>"];
13412
13413         if(bulkRender !== true && n.nextSibling && n.nextSibling.ui.getEl()){
13414             this.wrap = Roo.DomHelper.insertHtml("beforeBegin",
13415                                 n.nextSibling.ui.getEl(), buf.join(""));
13416         }else{
13417             this.wrap = Roo.DomHelper.insertHtml("beforeEnd", targetNode, buf.join(""));
13418         }
13419
13420         this.elNode = this.wrap.childNodes[0];
13421         this.ctNode = this.wrap.childNodes[1];
13422         var cs = this.elNode.childNodes;
13423         this.indentNode = cs[0];
13424         this.ecNode = cs[1];
13425         this.iconNode = cs[2];
13426         var index = 3;
13427         if(cb){
13428             this.checkbox = cs[3];
13429             index++;
13430         }
13431         this.anchor = cs[index];
13432         this.textNode = cs[index].firstChild;
13433     },
13434
13435     getAnchor : function(){
13436         return this.anchor;
13437     },
13438
13439     getTextEl : function(){
13440         return this.textNode;
13441     },
13442
13443     getIconEl : function(){
13444         return this.iconNode;
13445     },
13446
13447     isChecked : function(){
13448         return this.checkbox ? this.checkbox.checked : false;
13449     },
13450
13451     updateExpandIcon : function(){
13452         if(this.rendered){
13453             var n = this.node, c1, c2;
13454             var cls = n.isLast() ? "x-tree-elbow-end" : "x-tree-elbow";
13455             var hasChild = n.hasChildNodes();
13456             if(hasChild){
13457                 if(n.expanded){
13458                     cls += "-minus";
13459                     c1 = "x-tree-node-collapsed";
13460                     c2 = "x-tree-node-expanded";
13461                 }else{
13462                     cls += "-plus";
13463                     c1 = "x-tree-node-expanded";
13464                     c2 = "x-tree-node-collapsed";
13465                 }
13466                 if(this.wasLeaf){
13467                     this.removeClass("x-tree-node-leaf");
13468                     this.wasLeaf = false;
13469                 }
13470                 if(this.c1 != c1 || this.c2 != c2){
13471                     Roo.fly(this.elNode).replaceClass(c1, c2);
13472                     this.c1 = c1; this.c2 = c2;
13473                 }
13474             }else{
13475                 // this changes non-leafs into leafs if they have no children.
13476                 // it's not very rational behaviour..
13477                 
13478                 if(!this.wasLeaf && this.node.leaf){
13479                     Roo.fly(this.elNode).replaceClass("x-tree-node-expanded", "x-tree-node-leaf");
13480                     delete this.c1;
13481                     delete this.c2;
13482                     this.wasLeaf = true;
13483                 }
13484             }
13485             var ecc = "x-tree-ec-icon "+cls;
13486             if(this.ecc != ecc){
13487                 this.ecNode.className = ecc;
13488                 this.ecc = ecc;
13489             }
13490         }
13491     },
13492
13493     getChildIndent : function(){
13494         if(!this.childIndent){
13495             var buf = [];
13496             var p = this.node;
13497             while(p){
13498                 if(!p.isRoot || (p.isRoot && p.ownerTree.rootVisible)){
13499                     if(!p.isLast()) {
13500                         buf.unshift('<img src="'+this.emptyIcon+'" class="x-tree-elbow-line" />');
13501                     } else {
13502                         buf.unshift('<img src="'+this.emptyIcon+'" class="x-tree-icon" />');
13503                     }
13504                 }
13505                 p = p.parentNode;
13506             }
13507             this.childIndent = buf.join("");
13508         }
13509         return this.childIndent;
13510     },
13511
13512     renderIndent : function(){
13513         if(this.rendered){
13514             var indent = "";
13515             var p = this.node.parentNode;
13516             if(p){
13517                 indent = p.ui.getChildIndent();
13518             }
13519             if(this.indentMarkup != indent){ // don't rerender if not required
13520                 this.indentNode.innerHTML = indent;
13521                 this.indentMarkup = indent;
13522             }
13523             this.updateExpandIcon();
13524         }
13525     }
13526 };
13527
13528 Roo.tree.RootTreeNodeUI = function(){
13529     Roo.tree.RootTreeNodeUI.superclass.constructor.apply(this, arguments);
13530 };
13531 Roo.extend(Roo.tree.RootTreeNodeUI, Roo.tree.TreeNodeUI, {
13532     render : function(){
13533         if(!this.rendered){
13534             var targetNode = this.node.ownerTree.innerCt.dom;
13535             this.node.expanded = true;
13536             targetNode.innerHTML = '<div class="x-tree-root-node"></div>';
13537             this.wrap = this.ctNode = targetNode.firstChild;
13538         }
13539     },
13540     collapse : function(){
13541     },
13542     expand : function(){
13543     }
13544 });/*
13545  * Based on:
13546  * Ext JS Library 1.1.1
13547  * Copyright(c) 2006-2007, Ext JS, LLC.
13548  *
13549  * Originally Released Under LGPL - original licence link has changed is not relivant.
13550  *
13551  * Fork - LGPL
13552  * <script type="text/javascript">
13553  */
13554 /**
13555  * @class Roo.tree.TreeLoader
13556  * @extends Roo.util.Observable
13557  * A TreeLoader provides for lazy loading of an {@link Roo.tree.TreeNode}'s child
13558  * nodes from a specified URL. The response must be a javascript Array definition
13559  * who's elements are node definition objects. eg:
13560  * <pre><code>
13561 {  success : true,
13562    data :      [
13563    
13564     { 'id': 1, 'text': 'A folder Node', 'leaf': false },
13565     { 'id': 2, 'text': 'A leaf Node', 'leaf': true }
13566     ]
13567 }
13568
13569
13570 </code></pre>
13571  * <br><br>
13572  * The old style respose with just an array is still supported, but not recommended.
13573  * <br><br>
13574  *
13575  * A server request is sent, and child nodes are loaded only when a node is expanded.
13576  * The loading node's id is passed to the server under the parameter name "node" to
13577  * enable the server to produce the correct child nodes.
13578  * <br><br>
13579  * To pass extra parameters, an event handler may be attached to the "beforeload"
13580  * event, and the parameters specified in the TreeLoader's baseParams property:
13581  * <pre><code>
13582     myTreeLoader.on("beforeload", function(treeLoader, node) {
13583         this.baseParams.category = node.attributes.category;
13584     }, this);
13585     
13586 </code></pre>
13587  *
13588  * This would pass an HTTP parameter called "category" to the server containing
13589  * the value of the Node's "category" attribute.
13590  * @constructor
13591  * Creates a new Treeloader.
13592  * @param {Object} config A config object containing config properties.
13593  */
13594 Roo.tree.TreeLoader = function(config){
13595     this.baseParams = {};
13596     this.requestMethod = "POST";
13597     Roo.apply(this, config);
13598
13599     this.addEvents({
13600     
13601         /**
13602          * @event beforeload
13603          * Fires before a network request is made to retrieve the Json text which specifies a node's children.
13604          * @param {Object} This TreeLoader object.
13605          * @param {Object} node The {@link Roo.tree.TreeNode} object being loaded.
13606          * @param {Object} callback The callback function specified in the {@link #load} call.
13607          */
13608         beforeload : true,
13609         /**
13610          * @event load
13611          * Fires when the node has been successfuly loaded.
13612          * @param {Object} This TreeLoader object.
13613          * @param {Object} node The {@link Roo.tree.TreeNode} object being loaded.
13614          * @param {Object} response The response object containing the data from the server.
13615          */
13616         load : true,
13617         /**
13618          * @event loadexception
13619          * Fires if the network request failed.
13620          * @param {Object} This TreeLoader object.
13621          * @param {Object} node The {@link Roo.tree.TreeNode} object being loaded.
13622          * @param {Object} response The response object containing the data from the server.
13623          */
13624         loadexception : true,
13625         /**
13626          * @event create
13627          * Fires before a node is created, enabling you to return custom Node types 
13628          * @param {Object} This TreeLoader object.
13629          * @param {Object} attr - the data returned from the AJAX call (modify it to suit)
13630          */
13631         create : true
13632     });
13633
13634     Roo.tree.TreeLoader.superclass.constructor.call(this);
13635 };
13636
13637 Roo.extend(Roo.tree.TreeLoader, Roo.util.Observable, {
13638     /**
13639     * @cfg {String} dataUrl The URL from which to request a Json string which
13640     * specifies an array of node definition object representing the child nodes
13641     * to be loaded.
13642     */
13643     /**
13644     * @cfg {String} requestMethod either GET or POST
13645     * defaults to POST (due to BC)
13646     * to be loaded.
13647     */
13648     /**
13649     * @cfg {Object} baseParams (optional) An object containing properties which
13650     * specify HTTP parameters to be passed to each request for child nodes.
13651     */
13652     /**
13653     * @cfg {Object} baseAttrs (optional) An object containing attributes to be added to all nodes
13654     * created by this loader. If the attributes sent by the server have an attribute in this object,
13655     * they take priority.
13656     */
13657     /**
13658     * @cfg {Object} uiProviders (optional) An object containing properties which
13659     * 
13660     * DEPRECATED - use 'create' event handler to modify attributes - which affect creation.
13661     * specify custom {@link Roo.tree.TreeNodeUI} implementations. If the optional
13662     * <i>uiProvider</i> attribute of a returned child node is a string rather
13663     * than a reference to a TreeNodeUI implementation, this that string value
13664     * is used as a property name in the uiProviders object. You can define the provider named
13665     * 'default' , and this will be used for all nodes (if no uiProvider is delivered by the node data)
13666     */
13667     uiProviders : {},
13668
13669     /**
13670     * @cfg {Boolean} clearOnLoad (optional) Default to true. Remove previously existing
13671     * child nodes before loading.
13672     */
13673     clearOnLoad : true,
13674
13675     /**
13676     * @cfg {String} root (optional) Default to false. Use this to read data from an object 
13677     * property on loading, rather than expecting an array. (eg. more compatible to a standard
13678     * Grid query { data : [ .....] }
13679     */
13680     
13681     root : false,
13682      /**
13683     * @cfg {String} queryParam (optional) 
13684     * Name of the query as it will be passed on the querystring (defaults to 'node')
13685     * eg. the request will be ?node=[id]
13686     */
13687     
13688     
13689     queryParam: false,
13690     
13691     /**
13692      * Load an {@link Roo.tree.TreeNode} from the URL specified in the constructor.
13693      * This is called automatically when a node is expanded, but may be used to reload
13694      * a node (or append new children if the {@link #clearOnLoad} option is false.)
13695      * @param {Roo.tree.TreeNode} node
13696      * @param {Function} callback
13697      */
13698     load : function(node, callback){
13699         if(this.clearOnLoad){
13700             while(node.firstChild){
13701                 node.removeChild(node.firstChild);
13702             }
13703         }
13704         if(node.attributes.children){ // preloaded json children
13705             var cs = node.attributes.children;
13706             for(var i = 0, len = cs.length; i < len; i++){
13707                 node.appendChild(this.createNode(cs[i]));
13708             }
13709             if(typeof callback == "function"){
13710                 callback();
13711             }
13712         }else if(this.dataUrl){
13713             this.requestData(node, callback);
13714         }
13715     },
13716
13717     getParams: function(node){
13718         var buf = [], bp = this.baseParams;
13719         for(var key in bp){
13720             if(typeof bp[key] != "function"){
13721                 buf.push(encodeURIComponent(key), "=", encodeURIComponent(bp[key]), "&");
13722             }
13723         }
13724         var n = this.queryParam === false ? 'node' : this.queryParam;
13725         buf.push(n + "=", encodeURIComponent(node.id));
13726         return buf.join("");
13727     },
13728
13729     requestData : function(node, callback){
13730         if(this.fireEvent("beforeload", this, node, callback) !== false){
13731             this.transId = Roo.Ajax.request({
13732                 method:this.requestMethod,
13733                 url: this.dataUrl||this.url,
13734                 success: this.handleResponse,
13735                 failure: this.handleFailure,
13736                 scope: this,
13737                 argument: {callback: callback, node: node},
13738                 params: this.getParams(node)
13739             });
13740         }else{
13741             // if the load is cancelled, make sure we notify
13742             // the node that we are done
13743             if(typeof callback == "function"){
13744                 callback();
13745             }
13746         }
13747     },
13748
13749     isLoading : function(){
13750         return this.transId ? true : false;
13751     },
13752
13753     abort : function(){
13754         if(this.isLoading()){
13755             Roo.Ajax.abort(this.transId);
13756         }
13757     },
13758
13759     // private
13760     createNode : function(attr)
13761     {
13762         // apply baseAttrs, nice idea Corey!
13763         if(this.baseAttrs){
13764             Roo.applyIf(attr, this.baseAttrs);
13765         }
13766         if(this.applyLoader !== false){
13767             attr.loader = this;
13768         }
13769         // uiProvider = depreciated..
13770         
13771         if(typeof(attr.uiProvider) == 'string'){
13772            attr.uiProvider = this.uiProviders[attr.uiProvider] || 
13773                 /**  eval:var:attr */ eval(attr.uiProvider);
13774         }
13775         if(typeof(this.uiProviders['default']) != 'undefined') {
13776             attr.uiProvider = this.uiProviders['default'];
13777         }
13778         
13779         this.fireEvent('create', this, attr);
13780         
13781         attr.leaf  = typeof(attr.leaf) == 'string' ? attr.leaf * 1 : attr.leaf;
13782         return(attr.leaf ?
13783                         new Roo.tree.TreeNode(attr) :
13784                         new Roo.tree.AsyncTreeNode(attr));
13785     },
13786
13787     processResponse : function(response, node, callback)
13788     {
13789         var json = response.responseText;
13790         try {
13791             
13792             var o = Roo.decode(json);
13793             
13794             if (this.root === false && typeof(o.success) != undefined) {
13795                 this.root = 'data'; // the default behaviour for list like data..
13796                 }
13797                 
13798             if (this.root !== false &&  !o.success) {
13799                 // it's a failure condition.
13800                 var a = response.argument;
13801                 this.fireEvent("loadexception", this, a.node, response);
13802                 Roo.log("Load failed - should have a handler really");
13803                 return;
13804             }
13805             
13806             
13807             
13808             if (this.root !== false) {
13809                  o = o[this.root];
13810             }
13811             
13812             for(var i = 0, len = o.length; i < len; i++){
13813                 var n = this.createNode(o[i]);
13814                 if(n){
13815                     node.appendChild(n);
13816                 }
13817             }
13818             if(typeof callback == "function"){
13819                 callback(this, node);
13820             }
13821         }catch(e){
13822             this.handleFailure(response);
13823         }
13824     },
13825
13826     handleResponse : function(response){
13827         this.transId = false;
13828         var a = response.argument;
13829         this.processResponse(response, a.node, a.callback);
13830         this.fireEvent("load", this, a.node, response);
13831     },
13832
13833     handleFailure : function(response)
13834     {
13835         // should handle failure better..
13836         this.transId = false;
13837         var a = response.argument;
13838         this.fireEvent("loadexception", this, a.node, response);
13839         if(typeof a.callback == "function"){
13840             a.callback(this, a.node);
13841         }
13842     }
13843 });/*
13844  * Based on:
13845  * Ext JS Library 1.1.1
13846  * Copyright(c) 2006-2007, Ext JS, LLC.
13847  *
13848  * Originally Released Under LGPL - original licence link has changed is not relivant.
13849  *
13850  * Fork - LGPL
13851  * <script type="text/javascript">
13852  */
13853
13854 /**
13855 * @class Roo.tree.TreeFilter
13856 * Note this class is experimental and doesn't update the indent (lines) or expand collapse icons of the nodes
13857 * @param {TreePanel} tree
13858 * @param {Object} config (optional)
13859  */
13860 Roo.tree.TreeFilter = function(tree, config){
13861     this.tree = tree;
13862     this.filtered = {};
13863     Roo.apply(this, config);
13864 };
13865
13866 Roo.tree.TreeFilter.prototype = {
13867     clearBlank:false,
13868     reverse:false,
13869     autoClear:false,
13870     remove:false,
13871
13872      /**
13873      * Filter the data by a specific attribute.
13874      * @param {String/RegExp} value Either string that the attribute value
13875      * should start with or a RegExp to test against the attribute
13876      * @param {String} attr (optional) The attribute passed in your node's attributes collection. Defaults to "text".
13877      * @param {TreeNode} startNode (optional) The node to start the filter at.
13878      */
13879     filter : function(value, attr, startNode){
13880         attr = attr || "text";
13881         var f;
13882         if(typeof value == "string"){
13883             var vlen = value.length;
13884             // auto clear empty filter
13885             if(vlen == 0 && this.clearBlank){
13886                 this.clear();
13887                 return;
13888             }
13889             value = value.toLowerCase();
13890             f = function(n){
13891                 return n.attributes[attr].substr(0, vlen).toLowerCase() == value;
13892             };
13893         }else if(value.exec){ // regex?
13894             f = function(n){
13895                 return value.test(n.attributes[attr]);
13896             };
13897         }else{
13898             throw 'Illegal filter type, must be string or regex';
13899         }
13900         this.filterBy(f, null, startNode);
13901         },
13902
13903     /**
13904      * Filter by a function. The passed function will be called with each
13905      * node in the tree (or from the startNode). If the function returns true, the node is kept
13906      * otherwise it is filtered. If a node is filtered, its children are also filtered.
13907      * @param {Function} fn The filter function
13908      * @param {Object} scope (optional) The scope of the function (defaults to the current node)
13909      */
13910     filterBy : function(fn, scope, startNode){
13911         startNode = startNode || this.tree.root;
13912         if(this.autoClear){
13913             this.clear();
13914         }
13915         var af = this.filtered, rv = this.reverse;
13916         var f = function(n){
13917             if(n == startNode){
13918                 return true;
13919             }
13920             if(af[n.id]){
13921                 return false;
13922             }
13923             var m = fn.call(scope || n, n);
13924             if(!m || rv){
13925                 af[n.id] = n;
13926                 n.ui.hide();
13927                 return false;
13928             }
13929             return true;
13930         };
13931         startNode.cascade(f);
13932         if(this.remove){
13933            for(var id in af){
13934                if(typeof id != "function"){
13935                    var n = af[id];
13936                    if(n && n.parentNode){
13937                        n.parentNode.removeChild(n);
13938                    }
13939                }
13940            }
13941         }
13942     },
13943
13944     /**
13945      * Clears the current filter. Note: with the "remove" option
13946      * set a filter cannot be cleared.
13947      */
13948     clear : function(){
13949         var t = this.tree;
13950         var af = this.filtered;
13951         for(var id in af){
13952             if(typeof id != "function"){
13953                 var n = af[id];
13954                 if(n){
13955                     n.ui.show();
13956                 }
13957             }
13958         }
13959         this.filtered = {};
13960     }
13961 };
13962 /*
13963  * Based on:
13964  * Ext JS Library 1.1.1
13965  * Copyright(c) 2006-2007, Ext JS, LLC.
13966  *
13967  * Originally Released Under LGPL - original licence link has changed is not relivant.
13968  *
13969  * Fork - LGPL
13970  * <script type="text/javascript">
13971  */
13972  
13973
13974 /**
13975  * @class Roo.tree.TreeSorter
13976  * Provides sorting of nodes in a TreePanel
13977  * 
13978  * @cfg {Boolean} folderSort True to sort leaf nodes under non leaf nodes
13979  * @cfg {String} property The named attribute on the node to sort by (defaults to text)
13980  * @cfg {String} dir The direction to sort (asc or desc) (defaults to asc)
13981  * @cfg {String} leafAttr The attribute used to determine leaf nodes in folder sort (defaults to "leaf")
13982  * @cfg {Boolean} caseSensitive true for case sensitive sort (defaults to false)
13983  * @cfg {Function} sortType A custom "casting" function used to convert node values before sorting
13984  * @constructor
13985  * @param {TreePanel} tree
13986  * @param {Object} config
13987  */
13988 Roo.tree.TreeSorter = function(tree, config){
13989     Roo.apply(this, config);
13990     tree.on("beforechildrenrendered", this.doSort, this);
13991     tree.on("append", this.updateSort, this);
13992     tree.on("insert", this.updateSort, this);
13993     
13994     var dsc = this.dir && this.dir.toLowerCase() == "desc";
13995     var p = this.property || "text";
13996     var sortType = this.sortType;
13997     var fs = this.folderSort;
13998     var cs = this.caseSensitive === true;
13999     var leafAttr = this.leafAttr || 'leaf';
14000
14001     this.sortFn = function(n1, n2){
14002         if(fs){
14003             if(n1.attributes[leafAttr] && !n2.attributes[leafAttr]){
14004                 return 1;
14005             }
14006             if(!n1.attributes[leafAttr] && n2.attributes[leafAttr]){
14007                 return -1;
14008             }
14009         }
14010         var v1 = sortType ? sortType(n1) : (cs ? n1.attributes[p] : n1.attributes[p].toUpperCase());
14011         var v2 = sortType ? sortType(n2) : (cs ? n2.attributes[p] : n2.attributes[p].toUpperCase());
14012         if(v1 < v2){
14013                         return dsc ? +1 : -1;
14014                 }else if(v1 > v2){
14015                         return dsc ? -1 : +1;
14016         }else{
14017                 return 0;
14018         }
14019     };
14020 };
14021
14022 Roo.tree.TreeSorter.prototype = {
14023     doSort : function(node){
14024         node.sort(this.sortFn);
14025     },
14026     
14027     compareNodes : function(n1, n2){
14028         return (n1.text.toUpperCase() > n2.text.toUpperCase() ? 1 : -1);
14029     },
14030     
14031     updateSort : function(tree, node){
14032         if(node.childrenRendered){
14033             this.doSort.defer(1, this, [node]);
14034         }
14035     }
14036 };/*
14037  * Based on:
14038  * Ext JS Library 1.1.1
14039  * Copyright(c) 2006-2007, Ext JS, LLC.
14040  *
14041  * Originally Released Under LGPL - original licence link has changed is not relivant.
14042  *
14043  * Fork - LGPL
14044  * <script type="text/javascript">
14045  */
14046
14047 if(Roo.dd.DropZone){
14048     
14049 Roo.tree.TreeDropZone = function(tree, config){
14050     this.allowParentInsert = false;
14051     this.allowContainerDrop = false;
14052     this.appendOnly = false;
14053     Roo.tree.TreeDropZone.superclass.constructor.call(this, tree.innerCt, config);
14054     this.tree = tree;
14055     this.lastInsertClass = "x-tree-no-status";
14056     this.dragOverData = {};
14057 };
14058
14059 Roo.extend(Roo.tree.TreeDropZone, Roo.dd.DropZone, {
14060     ddGroup : "TreeDD",
14061     scroll:  true,
14062     
14063     expandDelay : 1000,
14064     
14065     expandNode : function(node){
14066         if(node.hasChildNodes() && !node.isExpanded()){
14067             node.expand(false, null, this.triggerCacheRefresh.createDelegate(this));
14068         }
14069     },
14070     
14071     queueExpand : function(node){
14072         this.expandProcId = this.expandNode.defer(this.expandDelay, this, [node]);
14073     },
14074     
14075     cancelExpand : function(){
14076         if(this.expandProcId){
14077             clearTimeout(this.expandProcId);
14078             this.expandProcId = false;
14079         }
14080     },
14081     
14082     isValidDropPoint : function(n, pt, dd, e, data){
14083         if(!n || !data){ return false; }
14084         var targetNode = n.node;
14085         var dropNode = data.node;
14086         // default drop rules
14087         if(!(targetNode && targetNode.isTarget && pt)){
14088             return false;
14089         }
14090         if(pt == "append" && targetNode.allowChildren === false){
14091             return false;
14092         }
14093         if((pt == "above" || pt == "below") && (targetNode.parentNode && targetNode.parentNode.allowChildren === false)){
14094             return false;
14095         }
14096         if(dropNode && (targetNode == dropNode || dropNode.contains(targetNode))){
14097             return false;
14098         }
14099         // reuse the object
14100         var overEvent = this.dragOverData;
14101         overEvent.tree = this.tree;
14102         overEvent.target = targetNode;
14103         overEvent.data = data;
14104         overEvent.point = pt;
14105         overEvent.source = dd;
14106         overEvent.rawEvent = e;
14107         overEvent.dropNode = dropNode;
14108         overEvent.cancel = false;  
14109         var result = this.tree.fireEvent("nodedragover", overEvent);
14110         return overEvent.cancel === false && result !== false;
14111     },
14112     
14113     getDropPoint : function(e, n, dd)
14114     {
14115         var tn = n.node;
14116         if(tn.isRoot){
14117             return tn.allowChildren !== false ? "append" : false; // always append for root
14118         }
14119         var dragEl = n.ddel;
14120         var t = Roo.lib.Dom.getY(dragEl), b = t + dragEl.offsetHeight;
14121         var y = Roo.lib.Event.getPageY(e);
14122         //var noAppend = tn.allowChildren === false || tn.isLeaf();
14123         
14124         // we may drop nodes anywhere, as long as allowChildren has not been set to false..
14125         var noAppend = tn.allowChildren === false;
14126         if(this.appendOnly || tn.parentNode.allowChildren === false){
14127             return noAppend ? false : "append";
14128         }
14129         var noBelow = false;
14130         if(!this.allowParentInsert){
14131             noBelow = tn.hasChildNodes() && tn.isExpanded();
14132         }
14133         var q = (b - t) / (noAppend ? 2 : 3);
14134         if(y >= t && y < (t + q)){
14135             return "above";
14136         }else if(!noBelow && (noAppend || y >= b-q && y <= b)){
14137             return "below";
14138         }else{
14139             return "append";
14140         }
14141     },
14142     
14143     onNodeEnter : function(n, dd, e, data)
14144     {
14145         this.cancelExpand();
14146     },
14147     
14148     onNodeOver : function(n, dd, e, data)
14149     {
14150        
14151         var pt = this.getDropPoint(e, n, dd);
14152         var node = n.node;
14153         
14154         // auto node expand check
14155         if(!this.expandProcId && pt == "append" && node.hasChildNodes() && !n.node.isExpanded()){
14156             this.queueExpand(node);
14157         }else if(pt != "append"){
14158             this.cancelExpand();
14159         }
14160         
14161         // set the insert point style on the target node
14162         var returnCls = this.dropNotAllowed;
14163         if(this.isValidDropPoint(n, pt, dd, e, data)){
14164            if(pt){
14165                var el = n.ddel;
14166                var cls;
14167                if(pt == "above"){
14168                    returnCls = n.node.isFirst() ? "x-tree-drop-ok-above" : "x-tree-drop-ok-between";
14169                    cls = "x-tree-drag-insert-above";
14170                }else if(pt == "below"){
14171                    returnCls = n.node.isLast() ? "x-tree-drop-ok-below" : "x-tree-drop-ok-between";
14172                    cls = "x-tree-drag-insert-below";
14173                }else{
14174                    returnCls = "x-tree-drop-ok-append";
14175                    cls = "x-tree-drag-append";
14176                }
14177                if(this.lastInsertClass != cls){
14178                    Roo.fly(el).replaceClass(this.lastInsertClass, cls);
14179                    this.lastInsertClass = cls;
14180                }
14181            }
14182        }
14183        return returnCls;
14184     },
14185     
14186     onNodeOut : function(n, dd, e, data){
14187         
14188         this.cancelExpand();
14189         this.removeDropIndicators(n);
14190     },
14191     
14192     onNodeDrop : function(n, dd, e, data){
14193         var point = this.getDropPoint(e, n, dd);
14194         var targetNode = n.node;
14195         targetNode.ui.startDrop();
14196         if(!this.isValidDropPoint(n, point, dd, e, data)){
14197             targetNode.ui.endDrop();
14198             return false;
14199         }
14200         // first try to find the drop node
14201         var dropNode = data.node || (dd.getTreeNode ? dd.getTreeNode(data, targetNode, point, e) : null);
14202         var dropEvent = {
14203             tree : this.tree,
14204             target: targetNode,
14205             data: data,
14206             point: point,
14207             source: dd,
14208             rawEvent: e,
14209             dropNode: dropNode,
14210             cancel: !dropNode   
14211         };
14212         var retval = this.tree.fireEvent("beforenodedrop", dropEvent);
14213         if(retval === false || dropEvent.cancel === true || !dropEvent.dropNode){
14214             targetNode.ui.endDrop();
14215             return false;
14216         }
14217         // allow target changing
14218         targetNode = dropEvent.target;
14219         if(point == "append" && !targetNode.isExpanded()){
14220             targetNode.expand(false, null, function(){
14221                 this.completeDrop(dropEvent);
14222             }.createDelegate(this));
14223         }else{
14224             this.completeDrop(dropEvent);
14225         }
14226         return true;
14227     },
14228     
14229     completeDrop : function(de){
14230         var ns = de.dropNode, p = de.point, t = de.target;
14231         if(!(ns instanceof Array)){
14232             ns = [ns];
14233         }
14234         var n;
14235         for(var i = 0, len = ns.length; i < len; i++){
14236             n = ns[i];
14237             if(p == "above"){
14238                 t.parentNode.insertBefore(n, t);
14239             }else if(p == "below"){
14240                 t.parentNode.insertBefore(n, t.nextSibling);
14241             }else{
14242                 t.appendChild(n);
14243             }
14244         }
14245         n.ui.focus();
14246         if(this.tree.hlDrop){
14247             n.ui.highlight();
14248         }
14249         t.ui.endDrop();
14250         this.tree.fireEvent("nodedrop", de);
14251     },
14252     
14253     afterNodeMoved : function(dd, data, e, targetNode, dropNode){
14254         if(this.tree.hlDrop){
14255             dropNode.ui.focus();
14256             dropNode.ui.highlight();
14257         }
14258         this.tree.fireEvent("nodedrop", this.tree, targetNode, data, dd, e);
14259     },
14260     
14261     getTree : function(){
14262         return this.tree;
14263     },
14264     
14265     removeDropIndicators : function(n){
14266         if(n && n.ddel){
14267             var el = n.ddel;
14268             Roo.fly(el).removeClass([
14269                     "x-tree-drag-insert-above",
14270                     "x-tree-drag-insert-below",
14271                     "x-tree-drag-append"]);
14272             this.lastInsertClass = "_noclass";
14273         }
14274     },
14275     
14276     beforeDragDrop : function(target, e, id){
14277         this.cancelExpand();
14278         return true;
14279     },
14280     
14281     afterRepair : function(data){
14282         if(data && Roo.enableFx){
14283             data.node.ui.highlight();
14284         }
14285         this.hideProxy();
14286     } 
14287     
14288 });
14289
14290 }
14291 /*
14292  * Based on:
14293  * Ext JS Library 1.1.1
14294  * Copyright(c) 2006-2007, Ext JS, LLC.
14295  *
14296  * Originally Released Under LGPL - original licence link has changed is not relivant.
14297  *
14298  * Fork - LGPL
14299  * <script type="text/javascript">
14300  */
14301  
14302
14303 if(Roo.dd.DragZone){
14304 Roo.tree.TreeDragZone = function(tree, config){
14305     Roo.tree.TreeDragZone.superclass.constructor.call(this, tree.getTreeEl(), config);
14306     this.tree = tree;
14307 };
14308
14309 Roo.extend(Roo.tree.TreeDragZone, Roo.dd.DragZone, {
14310     ddGroup : "TreeDD",
14311    
14312     onBeforeDrag : function(data, e){
14313         var n = data.node;
14314         return n && n.draggable && !n.disabled;
14315     },
14316      
14317     
14318     onInitDrag : function(e){
14319         var data = this.dragData;
14320         this.tree.getSelectionModel().select(data.node);
14321         this.proxy.update("");
14322         data.node.ui.appendDDGhost(this.proxy.ghost.dom);
14323         this.tree.fireEvent("startdrag", this.tree, data.node, e);
14324     },
14325     
14326     getRepairXY : function(e, data){
14327         return data.node.ui.getDDRepairXY();
14328     },
14329     
14330     onEndDrag : function(data, e){
14331         this.tree.fireEvent("enddrag", this.tree, data.node, e);
14332         
14333         
14334     },
14335     
14336     onValidDrop : function(dd, e, id){
14337         this.tree.fireEvent("dragdrop", this.tree, this.dragData.node, dd, e);
14338         this.hideProxy();
14339     },
14340     
14341     beforeInvalidDrop : function(e, id){
14342         // this scrolls the original position back into view
14343         var sm = this.tree.getSelectionModel();
14344         sm.clearSelections();
14345         sm.select(this.dragData.node);
14346     }
14347 });
14348 }/*
14349  * Based on:
14350  * Ext JS Library 1.1.1
14351  * Copyright(c) 2006-2007, Ext JS, LLC.
14352  *
14353  * Originally Released Under LGPL - original licence link has changed is not relivant.
14354  *
14355  * Fork - LGPL
14356  * <script type="text/javascript">
14357  */
14358 /**
14359  * @class Roo.tree.TreeEditor
14360  * @extends Roo.Editor
14361  * Provides editor functionality for inline tree node editing.  Any valid {@link Roo.form.Field} can be used
14362  * as the editor field.
14363  * @constructor
14364  * @param {Object} config (used to be the tree panel.)
14365  * @param {Object} oldconfig DEPRECIATED Either a prebuilt {@link Roo.form.Field} instance or a Field config object
14366  * 
14367  * @cfg {Roo.tree.TreePanel} tree The tree to bind to.
14368  * @cfg {Roo.form.TextField|Object} field The field configuration
14369  *
14370  * 
14371  */
14372 Roo.tree.TreeEditor = function(config, oldconfig) { // was -- (tree, config){
14373     var tree = config;
14374     var field;
14375     if (oldconfig) { // old style..
14376         field = oldconfig.events ? oldconfig : new Roo.form.TextField(oldconfig);
14377     } else {
14378         // new style..
14379         tree = config.tree;
14380         config.field = config.field  || {};
14381         config.field.xtype = 'TextField';
14382         field = Roo.factory(config.field, Roo.form);
14383     }
14384     config = config || {};
14385     
14386     
14387     this.addEvents({
14388         /**
14389          * @event beforenodeedit
14390          * Fires when editing is initiated, but before the value changes.  Editing can be canceled by returning
14391          * false from the handler of this event.
14392          * @param {Editor} this
14393          * @param {Roo.tree.Node} node 
14394          */
14395         "beforenodeedit" : true
14396     });
14397     
14398     //Roo.log(config);
14399     Roo.tree.TreeEditor.superclass.constructor.call(this, field, config);
14400
14401     this.tree = tree;
14402
14403     tree.on('beforeclick', this.beforeNodeClick, this);
14404     tree.getTreeEl().on('mousedown', this.hide, this);
14405     this.on('complete', this.updateNode, this);
14406     this.on('beforestartedit', this.fitToTree, this);
14407     this.on('startedit', this.bindScroll, this, {delay:10});
14408     this.on('specialkey', this.onSpecialKey, this);
14409 };
14410
14411 Roo.extend(Roo.tree.TreeEditor, Roo.Editor, {
14412     /**
14413      * @cfg {String} alignment
14414      * The position to align to (see {@link Roo.Element#alignTo} for more details, defaults to "l-l").
14415      */
14416     alignment: "l-l",
14417     // inherit
14418     autoSize: false,
14419     /**
14420      * @cfg {Boolean} hideEl
14421      * True to hide the bound element while the editor is displayed (defaults to false)
14422      */
14423     hideEl : false,
14424     /**
14425      * @cfg {String} cls
14426      * CSS class to apply to the editor (defaults to "x-small-editor x-tree-editor")
14427      */
14428     cls: "x-small-editor x-tree-editor",
14429     /**
14430      * @cfg {Boolean} shim
14431      * True to shim the editor if selects/iframes could be displayed beneath it (defaults to false)
14432      */
14433     shim:false,
14434     // inherit
14435     shadow:"frame",
14436     /**
14437      * @cfg {Number} maxWidth
14438      * The maximum width in pixels of the editor field (defaults to 250).  Note that if the maxWidth would exceed
14439      * the containing tree element's size, it will be automatically limited for you to the container width, taking
14440      * scroll and client offsets into account prior to each edit.
14441      */
14442     maxWidth: 250,
14443
14444     editDelay : 350,
14445
14446     // private
14447     fitToTree : function(ed, el){
14448         var td = this.tree.getTreeEl().dom, nd = el.dom;
14449         if(td.scrollLeft >  nd.offsetLeft){ // ensure the node left point is visible
14450             td.scrollLeft = nd.offsetLeft;
14451         }
14452         var w = Math.min(
14453                 this.maxWidth,
14454                 (td.clientWidth > 20 ? td.clientWidth : td.offsetWidth) - Math.max(0, nd.offsetLeft-td.scrollLeft) - /*cushion*/5);
14455         this.setSize(w, '');
14456         
14457         return this.fireEvent('beforenodeedit', this, this.editNode);
14458         
14459     },
14460
14461     // private
14462     triggerEdit : function(node){
14463         this.completeEdit();
14464         this.editNode = node;
14465         this.startEdit(node.ui.textNode, node.text);
14466     },
14467
14468     // private
14469     bindScroll : function(){
14470         this.tree.getTreeEl().on('scroll', this.cancelEdit, this);
14471     },
14472
14473     // private
14474     beforeNodeClick : function(node, e){
14475         var sinceLast = (this.lastClick ? this.lastClick.getElapsed() : 0);
14476         this.lastClick = new Date();
14477         if(sinceLast > this.editDelay && this.tree.getSelectionModel().isSelected(node)){
14478             e.stopEvent();
14479             this.triggerEdit(node);
14480             return false;
14481         }
14482         return true;
14483     },
14484
14485     // private
14486     updateNode : function(ed, value){
14487         this.tree.getTreeEl().un('scroll', this.cancelEdit, this);
14488         this.editNode.setText(value);
14489     },
14490
14491     // private
14492     onHide : function(){
14493         Roo.tree.TreeEditor.superclass.onHide.call(this);
14494         if(this.editNode){
14495             this.editNode.ui.focus();
14496         }
14497     },
14498
14499     // private
14500     onSpecialKey : function(field, e){
14501         var k = e.getKey();
14502         if(k == e.ESC){
14503             e.stopEvent();
14504             this.cancelEdit();
14505         }else if(k == e.ENTER && !e.hasModifier()){
14506             e.stopEvent();
14507             this.completeEdit();
14508         }
14509     }
14510 });//<Script type="text/javascript">
14511 /*
14512  * Based on:
14513  * Ext JS Library 1.1.1
14514  * Copyright(c) 2006-2007, Ext JS, LLC.
14515  *
14516  * Originally Released Under LGPL - original licence link has changed is not relivant.
14517  *
14518  * Fork - LGPL
14519  * <script type="text/javascript">
14520  */
14521  
14522 /**
14523  * Not documented??? - probably should be...
14524  */
14525
14526 Roo.tree.ColumnNodeUI = Roo.extend(Roo.tree.TreeNodeUI, {
14527     //focus: Roo.emptyFn, // prevent odd scrolling behavior
14528     
14529     renderElements : function(n, a, targetNode, bulkRender){
14530         //consel.log("renderElements?");
14531         this.indentMarkup = n.parentNode ? n.parentNode.ui.getChildIndent() : '';
14532
14533         var t = n.getOwnerTree();
14534         var tid = Pman.Tab.Document_TypesTree.tree.el.id;
14535         
14536         var cols = t.columns;
14537         var bw = t.borderWidth;
14538         var c = cols[0];
14539         var href = a.href ? a.href : Roo.isGecko ? "" : "#";
14540          var cb = typeof a.checked == "boolean";
14541         var tx = String.format('{0}',n.text || (c.renderer ? c.renderer(a[c.dataIndex], n, a) : a[c.dataIndex]));
14542         var colcls = 'x-t-' + tid + '-c0';
14543         var buf = [
14544             '<li class="x-tree-node">',
14545             
14546                 
14547                 '<div class="x-tree-node-el ', a.cls,'">',
14548                     // extran...
14549                     '<div class="x-tree-col ', colcls, '" style="width:', c.width-bw, 'px;">',
14550                 
14551                 
14552                         '<span class="x-tree-node-indent">',this.indentMarkup,'</span>',
14553                         '<img src="', this.emptyIcon, '" class="x-tree-ec-icon  " />',
14554                         '<img src="', a.icon || this.emptyIcon, '" class="x-tree-node-icon',
14555                            (a.icon ? ' x-tree-node-inline-icon' : ''),
14556                            (a.iconCls ? ' '+a.iconCls : ''),
14557                            '" unselectable="on" />',
14558                         (cb ? ('<input class="x-tree-node-cb" type="checkbox" ' + 
14559                              (a.checked ? 'checked="checked" />' : ' />')) : ''),
14560                              
14561                         '<a class="x-tree-node-anchor" hidefocus="on" href="',href,'" tabIndex="1" ',
14562                             (a.hrefTarget ? ' target="' +a.hrefTarget + '"' : ''), '>',
14563                             '<span unselectable="on" qtip="' + tx + '">',
14564                              tx,
14565                              '</span></a>' ,
14566                     '</div>',
14567                      '<a class="x-tree-node-anchor" hidefocus="on" href="',href,'" tabIndex="1" ',
14568                             (a.hrefTarget ? ' target="' +a.hrefTarget + '"' : ''), '>'
14569                  ];
14570         for(var i = 1, len = cols.length; i < len; i++){
14571             c = cols[i];
14572             colcls = 'x-t-' + tid + '-c' +i;
14573             tx = String.format('{0}', (c.renderer ? c.renderer(a[c.dataIndex], n, a) : a[c.dataIndex]));
14574             buf.push('<div class="x-tree-col ', colcls, ' ' ,(c.cls?c.cls:''),'" style="width:',c.width-bw,'px;">',
14575                         '<div class="x-tree-col-text" qtip="' + tx +'">',tx,"</div>",
14576                       "</div>");
14577          }
14578          
14579          buf.push(
14580             '</a>',
14581             '<div class="x-clear"></div></div>',
14582             '<ul class="x-tree-node-ct" style="display:none;"></ul>',
14583             "</li>");
14584         
14585         if(bulkRender !== true && n.nextSibling && n.nextSibling.ui.getEl()){
14586             this.wrap = Roo.DomHelper.insertHtml("beforeBegin",
14587                                 n.nextSibling.ui.getEl(), buf.join(""));
14588         }else{
14589             this.wrap = Roo.DomHelper.insertHtml("beforeEnd", targetNode, buf.join(""));
14590         }
14591         var el = this.wrap.firstChild;
14592         this.elRow = el;
14593         this.elNode = el.firstChild;
14594         this.ranchor = el.childNodes[1];
14595         this.ctNode = this.wrap.childNodes[1];
14596         var cs = el.firstChild.childNodes;
14597         this.indentNode = cs[0];
14598         this.ecNode = cs[1];
14599         this.iconNode = cs[2];
14600         var index = 3;
14601         if(cb){
14602             this.checkbox = cs[3];
14603             index++;
14604         }
14605         this.anchor = cs[index];
14606         
14607         this.textNode = cs[index].firstChild;
14608         
14609         //el.on("click", this.onClick, this);
14610         //el.on("dblclick", this.onDblClick, this);
14611         
14612         
14613        // console.log(this);
14614     },
14615     initEvents : function(){
14616         Roo.tree.ColumnNodeUI.superclass.initEvents.call(this);
14617         
14618             
14619         var a = this.ranchor;
14620
14621         var el = Roo.get(a);
14622
14623         if(Roo.isOpera){ // opera render bug ignores the CSS
14624             el.setStyle("text-decoration", "none");
14625         }
14626
14627         el.on("click", this.onClick, this);
14628         el.on("dblclick", this.onDblClick, this);
14629         el.on("contextmenu", this.onContextMenu, this);
14630         
14631     },
14632     
14633     /*onSelectedChange : function(state){
14634         if(state){
14635             this.focus();
14636             this.addClass("x-tree-selected");
14637         }else{
14638             //this.blur();
14639             this.removeClass("x-tree-selected");
14640         }
14641     },*/
14642     addClass : function(cls){
14643         if(this.elRow){
14644             Roo.fly(this.elRow).addClass(cls);
14645         }
14646         
14647     },
14648     
14649     
14650     removeClass : function(cls){
14651         if(this.elRow){
14652             Roo.fly(this.elRow).removeClass(cls);
14653         }
14654     }
14655
14656     
14657     
14658 });//<Script type="text/javascript">
14659
14660 /*
14661  * Based on:
14662  * Ext JS Library 1.1.1
14663  * Copyright(c) 2006-2007, Ext JS, LLC.
14664  *
14665  * Originally Released Under LGPL - original licence link has changed is not relivant.
14666  *
14667  * Fork - LGPL
14668  * <script type="text/javascript">
14669  */
14670  
14671
14672 /**
14673  * @class Roo.tree.ColumnTree
14674  * @extends Roo.data.TreePanel
14675  * @cfg {Object} columns  Including width, header, renderer, cls, dataIndex 
14676  * @cfg {int} borderWidth  compined right/left border allowance
14677  * @constructor
14678  * @param {String/HTMLElement/Element} el The container element
14679  * @param {Object} config
14680  */
14681 Roo.tree.ColumnTree =  function(el, config)
14682 {
14683    Roo.tree.ColumnTree.superclass.constructor.call(this, el , config);
14684    this.addEvents({
14685         /**
14686         * @event resize
14687         * Fire this event on a container when it resizes
14688         * @param {int} w Width
14689         * @param {int} h Height
14690         */
14691        "resize" : true
14692     });
14693     this.on('resize', this.onResize, this);
14694 };
14695
14696 Roo.extend(Roo.tree.ColumnTree, Roo.tree.TreePanel, {
14697     //lines:false,
14698     
14699     
14700     borderWidth: Roo.isBorderBox ? 0 : 2, 
14701     headEls : false,
14702     
14703     render : function(){
14704         // add the header.....
14705        
14706         Roo.tree.ColumnTree.superclass.render.apply(this);
14707         
14708         this.el.addClass('x-column-tree');
14709         
14710         this.headers = this.el.createChild(
14711             {cls:'x-tree-headers'},this.innerCt.dom);
14712    
14713         var cols = this.columns, c;
14714         var totalWidth = 0;
14715         this.headEls = [];
14716         var  len = cols.length;
14717         for(var i = 0; i < len; i++){
14718              c = cols[i];
14719              totalWidth += c.width;
14720             this.headEls.push(this.headers.createChild({
14721                  cls:'x-tree-hd ' + (c.cls?c.cls+'-hd':''),
14722                  cn: {
14723                      cls:'x-tree-hd-text',
14724                      html: c.header
14725                  },
14726                  style:'width:'+(c.width-this.borderWidth)+'px;'
14727              }));
14728         }
14729         this.headers.createChild({cls:'x-clear'});
14730         // prevent floats from wrapping when clipped
14731         this.headers.setWidth(totalWidth);
14732         //this.innerCt.setWidth(totalWidth);
14733         this.innerCt.setStyle({ overflow: 'auto' });
14734         this.onResize(this.width, this.height);
14735              
14736         
14737     },
14738     onResize : function(w,h)
14739     {
14740         this.height = h;
14741         this.width = w;
14742         // resize cols..
14743         this.innerCt.setWidth(this.width);
14744         this.innerCt.setHeight(this.height-20);
14745         
14746         // headers...
14747         var cols = this.columns, c;
14748         var totalWidth = 0;
14749         var expEl = false;
14750         var len = cols.length;
14751         for(var i = 0; i < len; i++){
14752             c = cols[i];
14753             if (this.autoExpandColumn !== false && c.dataIndex == this.autoExpandColumn) {
14754                 // it's the expander..
14755                 expEl  = this.headEls[i];
14756                 continue;
14757             }
14758             totalWidth += c.width;
14759             
14760         }
14761         if (expEl) {
14762             expEl.setWidth(  ((w - totalWidth)-this.borderWidth - 20));
14763         }
14764         this.headers.setWidth(w-20);
14765
14766         
14767         
14768         
14769     }
14770 });
14771 /*
14772  * Based on:
14773  * Ext JS Library 1.1.1
14774  * Copyright(c) 2006-2007, Ext JS, LLC.
14775  *
14776  * Originally Released Under LGPL - original licence link has changed is not relivant.
14777  *
14778  * Fork - LGPL
14779  * <script type="text/javascript">
14780  */
14781  
14782 /**
14783  * @class Roo.menu.Menu
14784  * @extends Roo.util.Observable
14785  * A menu object.  This is the container to which you add all other menu items.  Menu can also serve a as a base class
14786  * when you want a specialzed menu based off of another component (like {@link Roo.menu.DateMenu} for example).
14787  * @constructor
14788  * Creates a new Menu
14789  * @param {Object} config Configuration options
14790  */
14791 Roo.menu.Menu = function(config){
14792     
14793     Roo.menu.Menu.superclass.constructor.call(this, config);
14794     
14795     this.id = this.id || Roo.id();
14796     this.addEvents({
14797         /**
14798          * @event beforeshow
14799          * Fires before this menu is displayed
14800          * @param {Roo.menu.Menu} this
14801          */
14802         beforeshow : true,
14803         /**
14804          * @event beforehide
14805          * Fires before this menu is hidden
14806          * @param {Roo.menu.Menu} this
14807          */
14808         beforehide : true,
14809         /**
14810          * @event show
14811          * Fires after this menu is displayed
14812          * @param {Roo.menu.Menu} this
14813          */
14814         show : true,
14815         /**
14816          * @event hide
14817          * Fires after this menu is hidden
14818          * @param {Roo.menu.Menu} this
14819          */
14820         hide : true,
14821         /**
14822          * @event click
14823          * Fires when this menu is clicked (or when the enter key is pressed while it is active)
14824          * @param {Roo.menu.Menu} this
14825          * @param {Roo.menu.Item} menuItem The menu item that was clicked
14826          * @param {Roo.EventObject} e
14827          */
14828         click : true,
14829         /**
14830          * @event mouseover
14831          * Fires when the mouse is hovering over this menu
14832          * @param {Roo.menu.Menu} this
14833          * @param {Roo.EventObject} e
14834          * @param {Roo.menu.Item} menuItem The menu item that was clicked
14835          */
14836         mouseover : true,
14837         /**
14838          * @event mouseout
14839          * Fires when the mouse exits this menu
14840          * @param {Roo.menu.Menu} this
14841          * @param {Roo.EventObject} e
14842          * @param {Roo.menu.Item} menuItem The menu item that was clicked
14843          */
14844         mouseout : true,
14845         /**
14846          * @event itemclick
14847          * Fires when a menu item contained in this menu is clicked
14848          * @param {Roo.menu.BaseItem} baseItem The BaseItem that was clicked
14849          * @param {Roo.EventObject} e
14850          */
14851         itemclick: true
14852     });
14853     if (this.registerMenu) {
14854         Roo.menu.MenuMgr.register(this);
14855     }
14856     
14857     var mis = this.items;
14858     this.items = new Roo.util.MixedCollection();
14859     if(mis){
14860         this.add.apply(this, mis);
14861     }
14862 };
14863
14864 Roo.extend(Roo.menu.Menu, Roo.util.Observable, {
14865     /**
14866      * @cfg {Number} minWidth The minimum width of the menu in pixels (defaults to 120)
14867      */
14868     minWidth : 120,
14869     /**
14870      * @cfg {Boolean/String} shadow True or "sides" for the default effect, "frame" for 4-way shadow, and "drop"
14871      * for bottom-right shadow (defaults to "sides")
14872      */
14873     shadow : "sides",
14874     /**
14875      * @cfg {String} subMenuAlign The {@link Roo.Element#alignTo} anchor position value to use for submenus of
14876      * this menu (defaults to "tl-tr?")
14877      */
14878     subMenuAlign : "tl-tr?",
14879     /**
14880      * @cfg {String} defaultAlign The default {@link Roo.Element#alignTo) anchor position value for this menu
14881      * relative to its element of origin (defaults to "tl-bl?")
14882      */
14883     defaultAlign : "tl-bl?",
14884     /**
14885      * @cfg {Boolean} allowOtherMenus True to allow multiple menus to be displayed at the same time (defaults to false)
14886      */
14887     allowOtherMenus : false,
14888     /**
14889      * @cfg {Boolean} registerMenu True (default) - means that clicking on screen etc. hides it.
14890      */
14891     registerMenu : true,
14892
14893     hidden:true,
14894
14895     // private
14896     render : function(){
14897         if(this.el){
14898             return;
14899         }
14900         var el = this.el = new Roo.Layer({
14901             cls: "x-menu",
14902             shadow:this.shadow,
14903             constrain: false,
14904             parentEl: this.parentEl || document.body,
14905             zindex:15000
14906         });
14907
14908         this.keyNav = new Roo.menu.MenuNav(this);
14909
14910         if(this.plain){
14911             el.addClass("x-menu-plain");
14912         }
14913         if(this.cls){
14914             el.addClass(this.cls);
14915         }
14916         // generic focus element
14917         this.focusEl = el.createChild({
14918             tag: "a", cls: "x-menu-focus", href: "#", onclick: "return false;", tabIndex:"-1"
14919         });
14920         var ul = el.createChild({tag: "ul", cls: "x-menu-list"});
14921         //disabling touch- as it's causing issues ..
14922         //ul.on(Roo.isTouch ? 'touchstart' : 'click'   , this.onClick, this);
14923         ul.on('click'   , this.onClick, this);
14924         
14925         
14926         ul.on("mouseover", this.onMouseOver, this);
14927         ul.on("mouseout", this.onMouseOut, this);
14928         this.items.each(function(item){
14929             if (item.hidden) {
14930                 return;
14931             }
14932             
14933             var li = document.createElement("li");
14934             li.className = "x-menu-list-item";
14935             ul.dom.appendChild(li);
14936             item.render(li, this);
14937         }, this);
14938         this.ul = ul;
14939         this.autoWidth();
14940     },
14941
14942     // private
14943     autoWidth : function(){
14944         var el = this.el, ul = this.ul;
14945         if(!el){
14946             return;
14947         }
14948         var w = this.width;
14949         if(w){
14950             el.setWidth(w);
14951         }else if(Roo.isIE){
14952             el.setWidth(this.minWidth);
14953             var t = el.dom.offsetWidth; // force recalc
14954             el.setWidth(ul.getWidth()+el.getFrameWidth("lr"));
14955         }
14956     },
14957
14958     // private
14959     delayAutoWidth : function(){
14960         if(this.rendered){
14961             if(!this.awTask){
14962                 this.awTask = new Roo.util.DelayedTask(this.autoWidth, this);
14963             }
14964             this.awTask.delay(20);
14965         }
14966     },
14967
14968     // private
14969     findTargetItem : function(e){
14970         var t = e.getTarget(".x-menu-list-item", this.ul,  true);
14971         if(t && t.menuItemId){
14972             return this.items.get(t.menuItemId);
14973         }
14974     },
14975
14976     // private
14977     onClick : function(e){
14978         Roo.log("menu.onClick");
14979         var t = this.findTargetItem(e);
14980         if(!t){
14981             return;
14982         }
14983         Roo.log(e);
14984         if (Roo.isTouch && e.type == 'touchstart' && t.menu  && !t.disabled) {
14985             if(t == this.activeItem && t.shouldDeactivate(e)){
14986                 this.activeItem.deactivate();
14987                 delete this.activeItem;
14988                 return;
14989             }
14990             if(t.canActivate){
14991                 this.setActiveItem(t, true);
14992             }
14993             return;
14994             
14995             
14996         }
14997         
14998         t.onClick(e);
14999         this.fireEvent("click", this, t, e);
15000     },
15001
15002     // private
15003     setActiveItem : function(item, autoExpand){
15004         if(item != this.activeItem){
15005             if(this.activeItem){
15006                 this.activeItem.deactivate();
15007             }
15008             this.activeItem = item;
15009             item.activate(autoExpand);
15010         }else if(autoExpand){
15011             item.expandMenu();
15012         }
15013     },
15014
15015     // private
15016     tryActivate : function(start, step){
15017         var items = this.items;
15018         for(var i = start, len = items.length; i >= 0 && i < len; i+= step){
15019             var item = items.get(i);
15020             if(!item.disabled && item.canActivate){
15021                 this.setActiveItem(item, false);
15022                 return item;
15023             }
15024         }
15025         return false;
15026     },
15027
15028     // private
15029     onMouseOver : function(e){
15030         var t;
15031         if(t = this.findTargetItem(e)){
15032             if(t.canActivate && !t.disabled){
15033                 this.setActiveItem(t, true);
15034             }
15035         }
15036         this.fireEvent("mouseover", this, e, t);
15037     },
15038
15039     // private
15040     onMouseOut : function(e){
15041         var t;
15042         if(t = this.findTargetItem(e)){
15043             if(t == this.activeItem && t.shouldDeactivate(e)){
15044                 this.activeItem.deactivate();
15045                 delete this.activeItem;
15046             }
15047         }
15048         this.fireEvent("mouseout", this, e, t);
15049     },
15050
15051     /**
15052      * Read-only.  Returns true if the menu is currently displayed, else false.
15053      * @type Boolean
15054      */
15055     isVisible : function(){
15056         return this.el && !this.hidden;
15057     },
15058
15059     /**
15060      * Displays this menu relative to another element
15061      * @param {String/HTMLElement/Roo.Element} element The element to align to
15062      * @param {String} position (optional) The {@link Roo.Element#alignTo} anchor position to use in aligning to
15063      * the element (defaults to this.defaultAlign)
15064      * @param {Roo.menu.Menu} parentMenu (optional) This menu's parent menu, if applicable (defaults to undefined)
15065      */
15066     show : function(el, pos, parentMenu){
15067         this.parentMenu = parentMenu;
15068         if(!this.el){
15069             this.render();
15070         }
15071         this.fireEvent("beforeshow", this);
15072         this.showAt(this.el.getAlignToXY(el, pos || this.defaultAlign), parentMenu, false);
15073     },
15074
15075     /**
15076      * Displays this menu at a specific xy position
15077      * @param {Array} xyPosition Contains X & Y [x, y] values for the position at which to show the menu (coordinates are page-based)
15078      * @param {Roo.menu.Menu} parentMenu (optional) This menu's parent menu, if applicable (defaults to undefined)
15079      */
15080     showAt : function(xy, parentMenu, /* private: */_e){
15081         this.parentMenu = parentMenu;
15082         if(!this.el){
15083             this.render();
15084         }
15085         if(_e !== false){
15086             this.fireEvent("beforeshow", this);
15087             xy = this.el.adjustForConstraints(xy);
15088         }
15089         this.el.setXY(xy);
15090         this.el.show();
15091         this.hidden = false;
15092         this.focus();
15093         this.fireEvent("show", this);
15094     },
15095
15096     focus : function(){
15097         if(!this.hidden){
15098             this.doFocus.defer(50, this);
15099         }
15100     },
15101
15102     doFocus : function(){
15103         if(!this.hidden){
15104             this.focusEl.focus();
15105         }
15106     },
15107
15108     /**
15109      * Hides this menu and optionally all parent menus
15110      * @param {Boolean} deep (optional) True to hide all parent menus recursively, if any (defaults to false)
15111      */
15112     hide : function(deep){
15113         if(this.el && this.isVisible()){
15114             this.fireEvent("beforehide", this);
15115             if(this.activeItem){
15116                 this.activeItem.deactivate();
15117                 this.activeItem = null;
15118             }
15119             this.el.hide();
15120             this.hidden = true;
15121             this.fireEvent("hide", this);
15122         }
15123         if(deep === true && this.parentMenu){
15124             this.parentMenu.hide(true);
15125         }
15126     },
15127
15128     /**
15129      * Addds one or more items of any type supported by the Menu class, or that can be converted into menu items.
15130      * Any of the following are valid:
15131      * <ul>
15132      * <li>Any menu item object based on {@link Roo.menu.Item}</li>
15133      * <li>An HTMLElement object which will be converted to a menu item</li>
15134      * <li>A menu item config object that will be created as a new menu item</li>
15135      * <li>A string, which can either be '-' or 'separator' to add a menu separator, otherwise
15136      * it will be converted into a {@link Roo.menu.TextItem} and added</li>
15137      * </ul>
15138      * Usage:
15139      * <pre><code>
15140 // Create the menu
15141 var menu = new Roo.menu.Menu();
15142
15143 // Create a menu item to add by reference
15144 var menuItem = new Roo.menu.Item({ text: 'New Item!' });
15145
15146 // Add a bunch of items at once using different methods.
15147 // Only the last item added will be returned.
15148 var item = menu.add(
15149     menuItem,                // add existing item by ref
15150     'Dynamic Item',          // new TextItem
15151     '-',                     // new separator
15152     { text: 'Config Item' }  // new item by config
15153 );
15154 </code></pre>
15155      * @param {Mixed} args One or more menu items, menu item configs or other objects that can be converted to menu items
15156      * @return {Roo.menu.Item} The menu item that was added, or the last one if multiple items were added
15157      */
15158     add : function(){
15159         var a = arguments, l = a.length, item;
15160         for(var i = 0; i < l; i++){
15161             var el = a[i];
15162             if ((typeof(el) == "object") && el.xtype && el.xns) {
15163                 el = Roo.factory(el, Roo.menu);
15164             }
15165             
15166             if(el.render){ // some kind of Item
15167                 item = this.addItem(el);
15168             }else if(typeof el == "string"){ // string
15169                 if(el == "separator" || el == "-"){
15170                     item = this.addSeparator();
15171                 }else{
15172                     item = this.addText(el);
15173                 }
15174             }else if(el.tagName || el.el){ // element
15175                 item = this.addElement(el);
15176             }else if(typeof el == "object"){ // must be menu item config?
15177                 item = this.addMenuItem(el);
15178             }
15179         }
15180         return item;
15181     },
15182
15183     /**
15184      * Returns this menu's underlying {@link Roo.Element} object
15185      * @return {Roo.Element} The element
15186      */
15187     getEl : function(){
15188         if(!this.el){
15189             this.render();
15190         }
15191         return this.el;
15192     },
15193
15194     /**
15195      * Adds a separator bar to the menu
15196      * @return {Roo.menu.Item} The menu item that was added
15197      */
15198     addSeparator : function(){
15199         return this.addItem(new Roo.menu.Separator());
15200     },
15201
15202     /**
15203      * Adds an {@link Roo.Element} object to the menu
15204      * @param {String/HTMLElement/Roo.Element} el The element or DOM node to add, or its id
15205      * @return {Roo.menu.Item} The menu item that was added
15206      */
15207     addElement : function(el){
15208         return this.addItem(new Roo.menu.BaseItem(el));
15209     },
15210
15211     /**
15212      * Adds an existing object based on {@link Roo.menu.Item} to the menu
15213      * @param {Roo.menu.Item} item The menu item to add
15214      * @return {Roo.menu.Item} The menu item that was added
15215      */
15216     addItem : function(item){
15217         this.items.add(item);
15218         if(this.ul){
15219             var li = document.createElement("li");
15220             li.className = "x-menu-list-item";
15221             this.ul.dom.appendChild(li);
15222             item.render(li, this);
15223             this.delayAutoWidth();
15224         }
15225         return item;
15226     },
15227
15228     /**
15229      * Creates a new {@link Roo.menu.Item} based an the supplied config object and adds it to the menu
15230      * @param {Object} config A MenuItem config object
15231      * @return {Roo.menu.Item} The menu item that was added
15232      */
15233     addMenuItem : function(config){
15234         if(!(config instanceof Roo.menu.Item)){
15235             if(typeof config.checked == "boolean"){ // must be check menu item config?
15236                 config = new Roo.menu.CheckItem(config);
15237             }else{
15238                 config = new Roo.menu.Item(config);
15239             }
15240         }
15241         return this.addItem(config);
15242     },
15243
15244     /**
15245      * Creates a new {@link Roo.menu.TextItem} with the supplied text and adds it to the menu
15246      * @param {String} text The text to display in the menu item
15247      * @return {Roo.menu.Item} The menu item that was added
15248      */
15249     addText : function(text){
15250         return this.addItem(new Roo.menu.TextItem({ text : text }));
15251     },
15252
15253     /**
15254      * Inserts an existing object based on {@link Roo.menu.Item} to the menu at a specified index
15255      * @param {Number} index The index in the menu's list of current items where the new item should be inserted
15256      * @param {Roo.menu.Item} item The menu item to add
15257      * @return {Roo.menu.Item} The menu item that was added
15258      */
15259     insert : function(index, item){
15260         this.items.insert(index, item);
15261         if(this.ul){
15262             var li = document.createElement("li");
15263             li.className = "x-menu-list-item";
15264             this.ul.dom.insertBefore(li, this.ul.dom.childNodes[index]);
15265             item.render(li, this);
15266             this.delayAutoWidth();
15267         }
15268         return item;
15269     },
15270
15271     /**
15272      * Removes an {@link Roo.menu.Item} from the menu and destroys the object
15273      * @param {Roo.menu.Item} item The menu item to remove
15274      */
15275     remove : function(item){
15276         this.items.removeKey(item.id);
15277         item.destroy();
15278     },
15279
15280     /**
15281      * Removes and destroys all items in the menu
15282      */
15283     removeAll : function(){
15284         var f;
15285         while(f = this.items.first()){
15286             this.remove(f);
15287         }
15288     }
15289 });
15290
15291 // MenuNav is a private utility class used internally by the Menu
15292 Roo.menu.MenuNav = function(menu){
15293     Roo.menu.MenuNav.superclass.constructor.call(this, menu.el);
15294     this.scope = this.menu = menu;
15295 };
15296
15297 Roo.extend(Roo.menu.MenuNav, Roo.KeyNav, {
15298     doRelay : function(e, h){
15299         var k = e.getKey();
15300         if(!this.menu.activeItem && e.isNavKeyPress() && k != e.SPACE && k != e.RETURN){
15301             this.menu.tryActivate(0, 1);
15302             return false;
15303         }
15304         return h.call(this.scope || this, e, this.menu);
15305     },
15306
15307     up : function(e, m){
15308         if(!m.tryActivate(m.items.indexOf(m.activeItem)-1, -1)){
15309             m.tryActivate(m.items.length-1, -1);
15310         }
15311     },
15312
15313     down : function(e, m){
15314         if(!m.tryActivate(m.items.indexOf(m.activeItem)+1, 1)){
15315             m.tryActivate(0, 1);
15316         }
15317     },
15318
15319     right : function(e, m){
15320         if(m.activeItem){
15321             m.activeItem.expandMenu(true);
15322         }
15323     },
15324
15325     left : function(e, m){
15326         m.hide();
15327         if(m.parentMenu && m.parentMenu.activeItem){
15328             m.parentMenu.activeItem.activate();
15329         }
15330     },
15331
15332     enter : function(e, m){
15333         if(m.activeItem){
15334             e.stopPropagation();
15335             m.activeItem.onClick(e);
15336             m.fireEvent("click", this, m.activeItem);
15337             return true;
15338         }
15339     }
15340 });/*
15341  * Based on:
15342  * Ext JS Library 1.1.1
15343  * Copyright(c) 2006-2007, Ext JS, LLC.
15344  *
15345  * Originally Released Under LGPL - original licence link has changed is not relivant.
15346  *
15347  * Fork - LGPL
15348  * <script type="text/javascript">
15349  */
15350  
15351 /**
15352  * @class Roo.menu.MenuMgr
15353  * Provides a common registry of all menu items on a page so that they can be easily accessed by id.
15354  * @singleton
15355  */
15356 Roo.menu.MenuMgr = function(){
15357    var menus, active, groups = {}, attached = false, lastShow = new Date();
15358
15359    // private - called when first menu is created
15360    function init(){
15361        menus = {};
15362        active = new Roo.util.MixedCollection();
15363        Roo.get(document).addKeyListener(27, function(){
15364            if(active.length > 0){
15365                hideAll();
15366            }
15367        });
15368    }
15369
15370    // private
15371    function hideAll(){
15372        if(active && active.length > 0){
15373            var c = active.clone();
15374            c.each(function(m){
15375                m.hide();
15376            });
15377        }
15378    }
15379
15380    // private
15381    function onHide(m){
15382        active.remove(m);
15383        if(active.length < 1){
15384            Roo.get(document).un("mousedown", onMouseDown);
15385            attached = false;
15386        }
15387    }
15388
15389    // private
15390    function onShow(m){
15391        var last = active.last();
15392        lastShow = new Date();
15393        active.add(m);
15394        if(!attached){
15395            Roo.get(document).on("mousedown", onMouseDown);
15396            attached = true;
15397        }
15398        if(m.parentMenu){
15399           m.getEl().setZIndex(parseInt(m.parentMenu.getEl().getStyle("z-index"), 10) + 3);
15400           m.parentMenu.activeChild = m;
15401        }else if(last && last.isVisible()){
15402           m.getEl().setZIndex(parseInt(last.getEl().getStyle("z-index"), 10) + 3);
15403        }
15404    }
15405
15406    // private
15407    function onBeforeHide(m){
15408        if(m.activeChild){
15409            m.activeChild.hide();
15410        }
15411        if(m.autoHideTimer){
15412            clearTimeout(m.autoHideTimer);
15413            delete m.autoHideTimer;
15414        }
15415    }
15416
15417    // private
15418    function onBeforeShow(m){
15419        var pm = m.parentMenu;
15420        if(!pm && !m.allowOtherMenus){
15421            hideAll();
15422        }else if(pm && pm.activeChild && active != m){
15423            pm.activeChild.hide();
15424        }
15425    }
15426
15427    // private
15428    function onMouseDown(e){
15429        if(lastShow.getElapsed() > 50 && active.length > 0 && !e.getTarget(".x-menu")){
15430            hideAll();
15431        }
15432    }
15433
15434    // private
15435    function onBeforeCheck(mi, state){
15436        if(state){
15437            var g = groups[mi.group];
15438            for(var i = 0, l = g.length; i < l; i++){
15439                if(g[i] != mi){
15440                    g[i].setChecked(false);
15441                }
15442            }
15443        }
15444    }
15445
15446    return {
15447
15448        /**
15449         * Hides all menus that are currently visible
15450         */
15451        hideAll : function(){
15452             hideAll();  
15453        },
15454
15455        // private
15456        register : function(menu){
15457            if(!menus){
15458                init();
15459            }
15460            menus[menu.id] = menu;
15461            menu.on("beforehide", onBeforeHide);
15462            menu.on("hide", onHide);
15463            menu.on("beforeshow", onBeforeShow);
15464            menu.on("show", onShow);
15465            var g = menu.group;
15466            if(g && menu.events["checkchange"]){
15467                if(!groups[g]){
15468                    groups[g] = [];
15469                }
15470                groups[g].push(menu);
15471                menu.on("checkchange", onCheck);
15472            }
15473        },
15474
15475         /**
15476          * Returns a {@link Roo.menu.Menu} object
15477          * @param {String/Object} menu The string menu id, an existing menu object reference, or a Menu config that will
15478          * be used to generate and return a new Menu instance.
15479          */
15480        get : function(menu){
15481            if(typeof menu == "string"){ // menu id
15482                return menus[menu];
15483            }else if(menu.events){  // menu instance
15484                return menu;
15485            }else if(typeof menu.length == 'number'){ // array of menu items?
15486                return new Roo.menu.Menu({items:menu});
15487            }else{ // otherwise, must be a config
15488                return new Roo.menu.Menu(menu);
15489            }
15490        },
15491
15492        // private
15493        unregister : function(menu){
15494            delete menus[menu.id];
15495            menu.un("beforehide", onBeforeHide);
15496            menu.un("hide", onHide);
15497            menu.un("beforeshow", onBeforeShow);
15498            menu.un("show", onShow);
15499            var g = menu.group;
15500            if(g && menu.events["checkchange"]){
15501                groups[g].remove(menu);
15502                menu.un("checkchange", onCheck);
15503            }
15504        },
15505
15506        // private
15507        registerCheckable : function(menuItem){
15508            var g = menuItem.group;
15509            if(g){
15510                if(!groups[g]){
15511                    groups[g] = [];
15512                }
15513                groups[g].push(menuItem);
15514                menuItem.on("beforecheckchange", onBeforeCheck);
15515            }
15516        },
15517
15518        // private
15519        unregisterCheckable : function(menuItem){
15520            var g = menuItem.group;
15521            if(g){
15522                groups[g].remove(menuItem);
15523                menuItem.un("beforecheckchange", onBeforeCheck);
15524            }
15525        }
15526    };
15527 }();/*
15528  * Based on:
15529  * Ext JS Library 1.1.1
15530  * Copyright(c) 2006-2007, Ext JS, LLC.
15531  *
15532  * Originally Released Under LGPL - original licence link has changed is not relivant.
15533  *
15534  * Fork - LGPL
15535  * <script type="text/javascript">
15536  */
15537  
15538
15539 /**
15540  * @class Roo.menu.BaseItem
15541  * @extends Roo.Component
15542  * The base class for all items that render into menus.  BaseItem provides default rendering, activated state
15543  * management and base configuration options shared by all menu components.
15544  * @constructor
15545  * Creates a new BaseItem
15546  * @param {Object} config Configuration options
15547  */
15548 Roo.menu.BaseItem = function(config){
15549     Roo.menu.BaseItem.superclass.constructor.call(this, config);
15550
15551     this.addEvents({
15552         /**
15553          * @event click
15554          * Fires when this item is clicked
15555          * @param {Roo.menu.BaseItem} this
15556          * @param {Roo.EventObject} e
15557          */
15558         click: true,
15559         /**
15560          * @event activate
15561          * Fires when this item is activated
15562          * @param {Roo.menu.BaseItem} this
15563          */
15564         activate : true,
15565         /**
15566          * @event deactivate
15567          * Fires when this item is deactivated
15568          * @param {Roo.menu.BaseItem} this
15569          */
15570         deactivate : true
15571     });
15572
15573     if(this.handler){
15574         this.on("click", this.handler, this.scope, true);
15575     }
15576 };
15577
15578 Roo.extend(Roo.menu.BaseItem, Roo.Component, {
15579     /**
15580      * @cfg {Function} handler
15581      * A function that will handle the click event of this menu item (defaults to undefined)
15582      */
15583     /**
15584      * @cfg {Boolean} canActivate True if this item can be visually activated (defaults to false)
15585      */
15586     canActivate : false,
15587     
15588      /**
15589      * @cfg {Boolean} hidden True to prevent creation of this menu item (defaults to false)
15590      */
15591     hidden: false,
15592     
15593     /**
15594      * @cfg {String} activeClass The CSS class to use when the item becomes activated (defaults to "x-menu-item-active")
15595      */
15596     activeClass : "x-menu-item-active",
15597     /**
15598      * @cfg {Boolean} hideOnClick True to hide the containing menu after this item is clicked (defaults to true)
15599      */
15600     hideOnClick : true,
15601     /**
15602      * @cfg {Number} hideDelay Length of time in milliseconds to wait before hiding after a click (defaults to 100)
15603      */
15604     hideDelay : 100,
15605
15606     // private
15607     ctype: "Roo.menu.BaseItem",
15608
15609     // private
15610     actionMode : "container",
15611
15612     // private
15613     render : function(container, parentMenu){
15614         this.parentMenu = parentMenu;
15615         Roo.menu.BaseItem.superclass.render.call(this, container);
15616         this.container.menuItemId = this.id;
15617     },
15618
15619     // private
15620     onRender : function(container, position){
15621         this.el = Roo.get(this.el);
15622         container.dom.appendChild(this.el.dom);
15623     },
15624
15625     // private
15626     onClick : function(e){
15627         if(!this.disabled && this.fireEvent("click", this, e) !== false
15628                 && this.parentMenu.fireEvent("itemclick", this, e) !== false){
15629             this.handleClick(e);
15630         }else{
15631             e.stopEvent();
15632         }
15633     },
15634
15635     // private
15636     activate : function(){
15637         if(this.disabled){
15638             return false;
15639         }
15640         var li = this.container;
15641         li.addClass(this.activeClass);
15642         this.region = li.getRegion().adjust(2, 2, -2, -2);
15643         this.fireEvent("activate", this);
15644         return true;
15645     },
15646
15647     // private
15648     deactivate : function(){
15649         this.container.removeClass(this.activeClass);
15650         this.fireEvent("deactivate", this);
15651     },
15652
15653     // private
15654     shouldDeactivate : function(e){
15655         return !this.region || !this.region.contains(e.getPoint());
15656     },
15657
15658     // private
15659     handleClick : function(e){
15660         if(this.hideOnClick){
15661             this.parentMenu.hide.defer(this.hideDelay, this.parentMenu, [true]);
15662         }
15663     },
15664
15665     // private
15666     expandMenu : function(autoActivate){
15667         // do nothing
15668     },
15669
15670     // private
15671     hideMenu : function(){
15672         // do nothing
15673     }
15674 });/*
15675  * Based on:
15676  * Ext JS Library 1.1.1
15677  * Copyright(c) 2006-2007, Ext JS, LLC.
15678  *
15679  * Originally Released Under LGPL - original licence link has changed is not relivant.
15680  *
15681  * Fork - LGPL
15682  * <script type="text/javascript">
15683  */
15684  
15685 /**
15686  * @class Roo.menu.Adapter
15687  * @extends Roo.menu.BaseItem
15688  * 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.
15689  * It provides basic rendering, activation management and enable/disable logic required to work in menus.
15690  * @constructor
15691  * Creates a new Adapter
15692  * @param {Object} config Configuration options
15693  */
15694 Roo.menu.Adapter = function(component, config){
15695     Roo.menu.Adapter.superclass.constructor.call(this, config);
15696     this.component = component;
15697 };
15698 Roo.extend(Roo.menu.Adapter, Roo.menu.BaseItem, {
15699     // private
15700     canActivate : true,
15701
15702     // private
15703     onRender : function(container, position){
15704         this.component.render(container);
15705         this.el = this.component.getEl();
15706     },
15707
15708     // private
15709     activate : function(){
15710         if(this.disabled){
15711             return false;
15712         }
15713         this.component.focus();
15714         this.fireEvent("activate", this);
15715         return true;
15716     },
15717
15718     // private
15719     deactivate : function(){
15720         this.fireEvent("deactivate", this);
15721     },
15722
15723     // private
15724     disable : function(){
15725         this.component.disable();
15726         Roo.menu.Adapter.superclass.disable.call(this);
15727     },
15728
15729     // private
15730     enable : function(){
15731         this.component.enable();
15732         Roo.menu.Adapter.superclass.enable.call(this);
15733     }
15734 });/*
15735  * Based on:
15736  * Ext JS Library 1.1.1
15737  * Copyright(c) 2006-2007, Ext JS, LLC.
15738  *
15739  * Originally Released Under LGPL - original licence link has changed is not relivant.
15740  *
15741  * Fork - LGPL
15742  * <script type="text/javascript">
15743  */
15744
15745 /**
15746  * @class Roo.menu.TextItem
15747  * @extends Roo.menu.BaseItem
15748  * Adds a static text string to a menu, usually used as either a heading or group separator.
15749  * Note: old style constructor with text is still supported.
15750  * 
15751  * @constructor
15752  * Creates a new TextItem
15753  * @param {Object} cfg Configuration
15754  */
15755 Roo.menu.TextItem = function(cfg){
15756     if (typeof(cfg) == 'string') {
15757         this.text = cfg;
15758     } else {
15759         Roo.apply(this,cfg);
15760     }
15761     
15762     Roo.menu.TextItem.superclass.constructor.call(this);
15763 };
15764
15765 Roo.extend(Roo.menu.TextItem, Roo.menu.BaseItem, {
15766     /**
15767      * @cfg {Boolean} text Text to show on item.
15768      */
15769     text : '',
15770     
15771     /**
15772      * @cfg {Boolean} hideOnClick True to hide the containing menu after this item is clicked (defaults to false)
15773      */
15774     hideOnClick : false,
15775     /**
15776      * @cfg {String} itemCls The default CSS class to use for text items (defaults to "x-menu-text")
15777      */
15778     itemCls : "x-menu-text",
15779
15780     // private
15781     onRender : function(){
15782         var s = document.createElement("span");
15783         s.className = this.itemCls;
15784         s.innerHTML = this.text;
15785         this.el = s;
15786         Roo.menu.TextItem.superclass.onRender.apply(this, arguments);
15787     }
15788 });/*
15789  * Based on:
15790  * Ext JS Library 1.1.1
15791  * Copyright(c) 2006-2007, Ext JS, LLC.
15792  *
15793  * Originally Released Under LGPL - original licence link has changed is not relivant.
15794  *
15795  * Fork - LGPL
15796  * <script type="text/javascript">
15797  */
15798
15799 /**
15800  * @class Roo.menu.Separator
15801  * @extends Roo.menu.BaseItem
15802  * Adds a separator bar to a menu, used to divide logical groups of menu items. Generally you will
15803  * add one of these by using "-" in you call to add() or in your items config rather than creating one directly.
15804  * @constructor
15805  * @param {Object} config Configuration options
15806  */
15807 Roo.menu.Separator = function(config){
15808     Roo.menu.Separator.superclass.constructor.call(this, config);
15809 };
15810
15811 Roo.extend(Roo.menu.Separator, Roo.menu.BaseItem, {
15812     /**
15813      * @cfg {String} itemCls The default CSS class to use for separators (defaults to "x-menu-sep")
15814      */
15815     itemCls : "x-menu-sep",
15816     /**
15817      * @cfg {Boolean} hideOnClick True to hide the containing menu after this item is clicked (defaults to false)
15818      */
15819     hideOnClick : false,
15820
15821     // private
15822     onRender : function(li){
15823         var s = document.createElement("span");
15824         s.className = this.itemCls;
15825         s.innerHTML = "&#160;";
15826         this.el = s;
15827         li.addClass("x-menu-sep-li");
15828         Roo.menu.Separator.superclass.onRender.apply(this, arguments);
15829     }
15830 });/*
15831  * Based on:
15832  * Ext JS Library 1.1.1
15833  * Copyright(c) 2006-2007, Ext JS, LLC.
15834  *
15835  * Originally Released Under LGPL - original licence link has changed is not relivant.
15836  *
15837  * Fork - LGPL
15838  * <script type="text/javascript">
15839  */
15840 /**
15841  * @class Roo.menu.Item
15842  * @extends Roo.menu.BaseItem
15843  * A base class for all menu items that require menu-related functionality (like sub-menus) and are not static
15844  * display items.  Item extends the base functionality of {@link Roo.menu.BaseItem} by adding menu-specific
15845  * activation and click handling.
15846  * @constructor
15847  * Creates a new Item
15848  * @param {Object} config Configuration options
15849  */
15850 Roo.menu.Item = function(config){
15851     Roo.menu.Item.superclass.constructor.call(this, config);
15852     if(this.menu){
15853         this.menu = Roo.menu.MenuMgr.get(this.menu);
15854     }
15855 };
15856 Roo.extend(Roo.menu.Item, Roo.menu.BaseItem, {
15857     
15858     /**
15859      * @cfg {String} text
15860      * The text to show on the menu item.
15861      */
15862     text: '',
15863      /**
15864      * @cfg {String} HTML to render in menu
15865      * The text to show on the menu item (HTML version).
15866      */
15867     html: '',
15868     /**
15869      * @cfg {String} icon
15870      * The path to an icon to display in this menu item (defaults to Roo.BLANK_IMAGE_URL)
15871      */
15872     icon: undefined,
15873     /**
15874      * @cfg {String} itemCls The default CSS class to use for menu items (defaults to "x-menu-item")
15875      */
15876     itemCls : "x-menu-item",
15877     /**
15878      * @cfg {Boolean} canActivate True if this item can be visually activated (defaults to true)
15879      */
15880     canActivate : true,
15881     /**
15882      * @cfg {Number} showDelay Length of time in milliseconds to wait before showing this item (defaults to 200)
15883      */
15884     showDelay: 200,
15885     // doc'd in BaseItem
15886     hideDelay: 200,
15887
15888     // private
15889     ctype: "Roo.menu.Item",
15890     
15891     // private
15892     onRender : function(container, position){
15893         var el = document.createElement("a");
15894         el.hideFocus = true;
15895         el.unselectable = "on";
15896         el.href = this.href || "#";
15897         if(this.hrefTarget){
15898             el.target = this.hrefTarget;
15899         }
15900         el.className = this.itemCls + (this.menu ?  " x-menu-item-arrow" : "") + (this.cls ?  " " + this.cls : "");
15901         
15902         var html = this.html.length ? this.html  : String.format('{0}',this.text);
15903         
15904         el.innerHTML = String.format(
15905                 '<img src="{0}" class="x-menu-item-icon {1}" />' + html,
15906                 this.icon || Roo.BLANK_IMAGE_URL, this.iconCls || '');
15907         this.el = el;
15908         Roo.menu.Item.superclass.onRender.call(this, container, position);
15909     },
15910
15911     /**
15912      * Sets the text to display in this menu item
15913      * @param {String} text The text to display
15914      * @param {Boolean} isHTML true to indicate text is pure html.
15915      */
15916     setText : function(text, isHTML){
15917         if (isHTML) {
15918             this.html = text;
15919         } else {
15920             this.text = text;
15921             this.html = '';
15922         }
15923         if(this.rendered){
15924             var html = this.html.length ? this.html  : String.format('{0}',this.text);
15925      
15926             this.el.update(String.format(
15927                 '<img src="{0}" class="x-menu-item-icon {2}">' + html,
15928                 this.icon || Roo.BLANK_IMAGE_URL, this.text, this.iconCls || ''));
15929             this.parentMenu.autoWidth();
15930         }
15931     },
15932
15933     // private
15934     handleClick : function(e){
15935         if(!this.href){ // if no link defined, stop the event automatically
15936             e.stopEvent();
15937         }
15938         Roo.menu.Item.superclass.handleClick.apply(this, arguments);
15939     },
15940
15941     // private
15942     activate : function(autoExpand){
15943         if(Roo.menu.Item.superclass.activate.apply(this, arguments)){
15944             this.focus();
15945             if(autoExpand){
15946                 this.expandMenu();
15947             }
15948         }
15949         return true;
15950     },
15951
15952     // private
15953     shouldDeactivate : function(e){
15954         if(Roo.menu.Item.superclass.shouldDeactivate.call(this, e)){
15955             if(this.menu && this.menu.isVisible()){
15956                 return !this.menu.getEl().getRegion().contains(e.getPoint());
15957             }
15958             return true;
15959         }
15960         return false;
15961     },
15962
15963     // private
15964     deactivate : function(){
15965         Roo.menu.Item.superclass.deactivate.apply(this, arguments);
15966         this.hideMenu();
15967     },
15968
15969     // private
15970     expandMenu : function(autoActivate){
15971         if(!this.disabled && this.menu){
15972             clearTimeout(this.hideTimer);
15973             delete this.hideTimer;
15974             if(!this.menu.isVisible() && !this.showTimer){
15975                 this.showTimer = this.deferExpand.defer(this.showDelay, this, [autoActivate]);
15976             }else if (this.menu.isVisible() && autoActivate){
15977                 this.menu.tryActivate(0, 1);
15978             }
15979         }
15980     },
15981
15982     // private
15983     deferExpand : function(autoActivate){
15984         delete this.showTimer;
15985         this.menu.show(this.container, this.parentMenu.subMenuAlign || "tl-tr?", this.parentMenu);
15986         if(autoActivate){
15987             this.menu.tryActivate(0, 1);
15988         }
15989     },
15990
15991     // private
15992     hideMenu : function(){
15993         clearTimeout(this.showTimer);
15994         delete this.showTimer;
15995         if(!this.hideTimer && this.menu && this.menu.isVisible()){
15996             this.hideTimer = this.deferHide.defer(this.hideDelay, this);
15997         }
15998     },
15999
16000     // private
16001     deferHide : function(){
16002         delete this.hideTimer;
16003         this.menu.hide();
16004     }
16005 });/*
16006  * Based on:
16007  * Ext JS Library 1.1.1
16008  * Copyright(c) 2006-2007, Ext JS, LLC.
16009  *
16010  * Originally Released Under LGPL - original licence link has changed is not relivant.
16011  *
16012  * Fork - LGPL
16013  * <script type="text/javascript">
16014  */
16015  
16016 /**
16017  * @class Roo.menu.CheckItem
16018  * @extends Roo.menu.Item
16019  * Adds a menu item that contains a checkbox by default, but can also be part of a radio group.
16020  * @constructor
16021  * Creates a new CheckItem
16022  * @param {Object} config Configuration options
16023  */
16024 Roo.menu.CheckItem = function(config){
16025     Roo.menu.CheckItem.superclass.constructor.call(this, config);
16026     this.addEvents({
16027         /**
16028          * @event beforecheckchange
16029          * Fires before the checked value is set, providing an opportunity to cancel if needed
16030          * @param {Roo.menu.CheckItem} this
16031          * @param {Boolean} checked The new checked value that will be set
16032          */
16033         "beforecheckchange" : true,
16034         /**
16035          * @event checkchange
16036          * Fires after the checked value has been set
16037          * @param {Roo.menu.CheckItem} this
16038          * @param {Boolean} checked The checked value that was set
16039          */
16040         "checkchange" : true
16041     });
16042     if(this.checkHandler){
16043         this.on('checkchange', this.checkHandler, this.scope);
16044     }
16045 };
16046 Roo.extend(Roo.menu.CheckItem, Roo.menu.Item, {
16047     /**
16048      * @cfg {String} group
16049      * All check items with the same group name will automatically be grouped into a single-select
16050      * radio button group (defaults to '')
16051      */
16052     /**
16053      * @cfg {String} itemCls The default CSS class to use for check items (defaults to "x-menu-item x-menu-check-item")
16054      */
16055     itemCls : "x-menu-item x-menu-check-item",
16056     /**
16057      * @cfg {String} groupClass The default CSS class to use for radio group check items (defaults to "x-menu-group-item")
16058      */
16059     groupClass : "x-menu-group-item",
16060
16061     /**
16062      * @cfg {Boolean} checked True to initialize this checkbox as checked (defaults to false).  Note that
16063      * if this checkbox is part of a radio group (group = true) only the last item in the group that is
16064      * initialized with checked = true will be rendered as checked.
16065      */
16066     checked: false,
16067
16068     // private
16069     ctype: "Roo.menu.CheckItem",
16070
16071     // private
16072     onRender : function(c){
16073         Roo.menu.CheckItem.superclass.onRender.apply(this, arguments);
16074         if(this.group){
16075             this.el.addClass(this.groupClass);
16076         }
16077         Roo.menu.MenuMgr.registerCheckable(this);
16078         if(this.checked){
16079             this.checked = false;
16080             this.setChecked(true, true);
16081         }
16082     },
16083
16084     // private
16085     destroy : function(){
16086         if(this.rendered){
16087             Roo.menu.MenuMgr.unregisterCheckable(this);
16088         }
16089         Roo.menu.CheckItem.superclass.destroy.apply(this, arguments);
16090     },
16091
16092     /**
16093      * Set the checked state of this item
16094      * @param {Boolean} checked The new checked value
16095      * @param {Boolean} suppressEvent (optional) True to prevent the checkchange event from firing (defaults to false)
16096      */
16097     setChecked : function(state, suppressEvent){
16098         if(this.checked != state && this.fireEvent("beforecheckchange", this, state) !== false){
16099             if(this.container){
16100                 this.container[state ? "addClass" : "removeClass"]("x-menu-item-checked");
16101             }
16102             this.checked = state;
16103             if(suppressEvent !== true){
16104                 this.fireEvent("checkchange", this, state);
16105             }
16106         }
16107     },
16108
16109     // private
16110     handleClick : function(e){
16111        if(!this.disabled && !(this.checked && this.group)){// disable unselect on radio item
16112            this.setChecked(!this.checked);
16113        }
16114        Roo.menu.CheckItem.superclass.handleClick.apply(this, arguments);
16115     }
16116 });/*
16117  * Based on:
16118  * Ext JS Library 1.1.1
16119  * Copyright(c) 2006-2007, Ext JS, LLC.
16120  *
16121  * Originally Released Under LGPL - original licence link has changed is not relivant.
16122  *
16123  * Fork - LGPL
16124  * <script type="text/javascript">
16125  */
16126  
16127 /**
16128  * @class Roo.menu.DateItem
16129  * @extends Roo.menu.Adapter
16130  * A menu item that wraps the {@link Roo.DatPicker} component.
16131  * @constructor
16132  * Creates a new DateItem
16133  * @param {Object} config Configuration options
16134  */
16135 Roo.menu.DateItem = function(config){
16136     Roo.menu.DateItem.superclass.constructor.call(this, new Roo.DatePicker(config), config);
16137     /** The Roo.DatePicker object @type Roo.DatePicker */
16138     this.picker = this.component;
16139     this.addEvents({select: true});
16140     
16141     this.picker.on("render", function(picker){
16142         picker.getEl().swallowEvent("click");
16143         picker.container.addClass("x-menu-date-item");
16144     });
16145
16146     this.picker.on("select", this.onSelect, this);
16147 };
16148
16149 Roo.extend(Roo.menu.DateItem, Roo.menu.Adapter, {
16150     // private
16151     onSelect : function(picker, date){
16152         this.fireEvent("select", this, date, picker);
16153         Roo.menu.DateItem.superclass.handleClick.call(this);
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.ColorItem
16168  * @extends Roo.menu.Adapter
16169  * A menu item that wraps the {@link Roo.ColorPalette} component.
16170  * @constructor
16171  * Creates a new ColorItem
16172  * @param {Object} config Configuration options
16173  */
16174 Roo.menu.ColorItem = function(config){
16175     Roo.menu.ColorItem.superclass.constructor.call(this, new Roo.ColorPalette(config), config);
16176     /** The Roo.ColorPalette object @type Roo.ColorPalette */
16177     this.palette = this.component;
16178     this.relayEvents(this.palette, ["select"]);
16179     if(this.selectHandler){
16180         this.on('select', this.selectHandler, this.scope);
16181     }
16182 };
16183 Roo.extend(Roo.menu.ColorItem, Roo.menu.Adapter);/*
16184  * Based on:
16185  * Ext JS Library 1.1.1
16186  * Copyright(c) 2006-2007, Ext JS, LLC.
16187  *
16188  * Originally Released Under LGPL - original licence link has changed is not relivant.
16189  *
16190  * Fork - LGPL
16191  * <script type="text/javascript">
16192  */
16193  
16194
16195 /**
16196  * @class Roo.menu.DateMenu
16197  * @extends Roo.menu.Menu
16198  * A menu containing a {@link Roo.menu.DateItem} component (which provides a date picker).
16199  * @constructor
16200  * Creates a new DateMenu
16201  * @param {Object} config Configuration options
16202  */
16203 Roo.menu.DateMenu = function(config){
16204     Roo.menu.DateMenu.superclass.constructor.call(this, config);
16205     this.plain = true;
16206     var di = new Roo.menu.DateItem(config);
16207     this.add(di);
16208     /**
16209      * The {@link Roo.DatePicker} instance for this DateMenu
16210      * @type DatePicker
16211      */
16212     this.picker = di.picker;
16213     /**
16214      * @event select
16215      * @param {DatePicker} picker
16216      * @param {Date} date
16217      */
16218     this.relayEvents(di, ["select"]);
16219     this.on('beforeshow', function(){
16220         if(this.picker){
16221             this.picker.hideMonthPicker(false);
16222         }
16223     }, this);
16224 };
16225 Roo.extend(Roo.menu.DateMenu, Roo.menu.Menu, {
16226     cls:'x-date-menu'
16227 });/*
16228  * Based on:
16229  * Ext JS Library 1.1.1
16230  * Copyright(c) 2006-2007, Ext JS, LLC.
16231  *
16232  * Originally Released Under LGPL - original licence link has changed is not relivant.
16233  *
16234  * Fork - LGPL
16235  * <script type="text/javascript">
16236  */
16237  
16238
16239 /**
16240  * @class Roo.menu.ColorMenu
16241  * @extends Roo.menu.Menu
16242  * A menu containing a {@link Roo.menu.ColorItem} component (which provides a basic color picker).
16243  * @constructor
16244  * Creates a new ColorMenu
16245  * @param {Object} config Configuration options
16246  */
16247 Roo.menu.ColorMenu = function(config){
16248     Roo.menu.ColorMenu.superclass.constructor.call(this, config);
16249     this.plain = true;
16250     var ci = new Roo.menu.ColorItem(config);
16251     this.add(ci);
16252     /**
16253      * The {@link Roo.ColorPalette} instance for this ColorMenu
16254      * @type ColorPalette
16255      */
16256     this.palette = ci.palette;
16257     /**
16258      * @event select
16259      * @param {ColorPalette} palette
16260      * @param {String} color
16261      */
16262     this.relayEvents(ci, ["select"]);
16263 };
16264 Roo.extend(Roo.menu.ColorMenu, Roo.menu.Menu);/*
16265  * Based on:
16266  * Ext JS Library 1.1.1
16267  * Copyright(c) 2006-2007, Ext JS, LLC.
16268  *
16269  * Originally Released Under LGPL - original licence link has changed is not relivant.
16270  *
16271  * Fork - LGPL
16272  * <script type="text/javascript">
16273  */
16274  
16275 /**
16276  * @class Roo.form.TextItem
16277  * @extends Roo.BoxComponent
16278  * Base class for form fields that provides default event handling, sizing, value handling and other functionality.
16279  * @constructor
16280  * Creates a new TextItem
16281  * @param {Object} config Configuration options
16282  */
16283 Roo.form.TextItem = function(config){
16284     Roo.form.TextItem.superclass.constructor.call(this, config);
16285 };
16286
16287 Roo.extend(Roo.form.TextItem, Roo.BoxComponent,  {
16288     
16289     /**
16290      * @cfg {String} tag the tag for this item (default div)
16291      */
16292     tag : 'div',
16293     /**
16294      * @cfg {String} html the content for this item
16295      */
16296     html : '',
16297     
16298     getAutoCreate : function()
16299     {
16300         var cfg = {
16301             id: this.id,
16302             tag: this.tag,
16303             html: this.html,
16304             cls: 'x-form-item'
16305         };
16306         
16307         return cfg;
16308         
16309     },
16310     
16311     onRender : function(ct, position)
16312     {
16313         Roo.form.TextItem.superclass.onRender.call(this, ct, position);
16314         
16315         if(!this.el){
16316             var cfg = this.getAutoCreate();
16317             if(!cfg.name){
16318                 cfg.name = typeof(this.name) == 'undefined' ? this.id : this.name;
16319             }
16320             if (!cfg.name.length) {
16321                 delete cfg.name;
16322             }
16323             this.el = ct.createChild(cfg, position);
16324         }
16325     }
16326     
16327 });/*
16328  * Based on:
16329  * Ext JS Library 1.1.1
16330  * Copyright(c) 2006-2007, Ext JS, LLC.
16331  *
16332  * Originally Released Under LGPL - original licence link has changed is not relivant.
16333  *
16334  * Fork - LGPL
16335  * <script type="text/javascript">
16336  */
16337  
16338 /**
16339  * @class Roo.form.Field
16340  * @extends Roo.BoxComponent
16341  * Base class for form fields that provides default event handling, sizing, value handling and other functionality.
16342  * @constructor
16343  * Creates a new Field
16344  * @param {Object} config Configuration options
16345  */
16346 Roo.form.Field = function(config){
16347     Roo.form.Field.superclass.constructor.call(this, config);
16348 };
16349
16350 Roo.extend(Roo.form.Field, Roo.BoxComponent,  {
16351     /**
16352      * @cfg {String} fieldLabel Label to use when rendering a form.
16353      */
16354        /**
16355      * @cfg {String} qtip Mouse over tip
16356      */
16357      
16358     /**
16359      * @cfg {String} invalidClass The CSS class to use when marking a field invalid (defaults to "x-form-invalid")
16360      */
16361     invalidClass : "x-form-invalid",
16362     /**
16363      * @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")
16364      */
16365     invalidText : "The value in this field is invalid",
16366     /**
16367      * @cfg {String} focusClass The CSS class to use when the field receives focus (defaults to "x-form-focus")
16368      */
16369     focusClass : "x-form-focus",
16370     /**
16371      * @cfg {String/Boolean} validationEvent The event that should initiate field validation. Set to false to disable
16372       automatic validation (defaults to "keyup").
16373      */
16374     validationEvent : "keyup",
16375     /**
16376      * @cfg {Boolean} validateOnBlur Whether the field should validate when it loses focus (defaults to true).
16377      */
16378     validateOnBlur : true,
16379     /**
16380      * @cfg {Number} validationDelay The length of time in milliseconds after user input begins until validation is initiated (defaults to 250)
16381      */
16382     validationDelay : 250,
16383     /**
16384      * @cfg {String/Object} autoCreate A DomHelper element spec, or true for a default element spec (defaults to
16385      * {tag: "input", type: "text", size: "20", autocomplete: "off"})
16386      */
16387     defaultAutoCreate : {tag: "input", type: "text", size: "20", autocomplete: "new-password"},
16388     /**
16389      * @cfg {String} fieldClass The default CSS class for the field (defaults to "x-form-field")
16390      */
16391     fieldClass : "x-form-field",
16392     /**
16393      * @cfg {String} msgTarget The location where error text should display.  Should be one of the following values (defaults to 'qtip'):
16394      *<pre>
16395 Value         Description
16396 -----------   ----------------------------------------------------------------------
16397 qtip          Display a quick tip when the user hovers over the field
16398 title         Display a default browser title attribute popup
16399 under         Add a block div beneath the field containing the error text
16400 side          Add an error icon to the right of the field with a popup on hover
16401 [element id]  Add the error text directly to the innerHTML of the specified element
16402 </pre>
16403      */
16404     msgTarget : 'qtip',
16405     /**
16406      * @cfg {String} msgFx <b>Experimental</b> The effect used when displaying a validation message under the field (defaults to 'normal').
16407      */
16408     msgFx : 'normal',
16409
16410     /**
16411      * @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.
16412      */
16413     readOnly : false,
16414
16415     /**
16416      * @cfg {Boolean} disabled True to disable the field (defaults to false).
16417      */
16418     disabled : false,
16419
16420     /**
16421      * @cfg {String} inputType The type attribute for input fields -- e.g. radio, text, password (defaults to "text").
16422      */
16423     inputType : undefined,
16424     
16425     /**
16426      * @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).
16427          */
16428         tabIndex : undefined,
16429         
16430     // private
16431     isFormField : true,
16432
16433     // private
16434     hasFocus : false,
16435     /**
16436      * @property {Roo.Element} fieldEl
16437      * Element Containing the rendered Field (with label etc.)
16438      */
16439     /**
16440      * @cfg {Mixed} value A value to initialize this field with.
16441      */
16442     value : undefined,
16443
16444     /**
16445      * @cfg {String} name The field's HTML name attribute.
16446      */
16447     /**
16448      * @cfg {String} cls A CSS class to apply to the field's underlying element.
16449      */
16450     // private
16451     loadedValue : false,
16452      
16453      
16454         // private ??
16455         initComponent : function(){
16456         Roo.form.Field.superclass.initComponent.call(this);
16457         this.addEvents({
16458             /**
16459              * @event focus
16460              * Fires when this field receives input focus.
16461              * @param {Roo.form.Field} this
16462              */
16463             focus : true,
16464             /**
16465              * @event blur
16466              * Fires when this field loses input focus.
16467              * @param {Roo.form.Field} this
16468              */
16469             blur : true,
16470             /**
16471              * @event specialkey
16472              * Fires when any key related to navigation (arrows, tab, enter, esc, etc.) is pressed.  You can check
16473              * {@link Roo.EventObject#getKey} to determine which key was pressed.
16474              * @param {Roo.form.Field} this
16475              * @param {Roo.EventObject} e The event object
16476              */
16477             specialkey : true,
16478             /**
16479              * @event change
16480              * Fires just before the field blurs if the field value has changed.
16481              * @param {Roo.form.Field} this
16482              * @param {Mixed} newValue The new value
16483              * @param {Mixed} oldValue The original value
16484              */
16485             change : true,
16486             /**
16487              * @event invalid
16488              * Fires after the field has been marked as invalid.
16489              * @param {Roo.form.Field} this
16490              * @param {String} msg The validation message
16491              */
16492             invalid : true,
16493             /**
16494              * @event valid
16495              * Fires after the field has been validated with no errors.
16496              * @param {Roo.form.Field} this
16497              */
16498             valid : true,
16499              /**
16500              * @event keyup
16501              * Fires after the key up
16502              * @param {Roo.form.Field} this
16503              * @param {Roo.EventObject}  e The event Object
16504              */
16505             keyup : true
16506         });
16507     },
16508
16509     /**
16510      * Returns the name attribute of the field if available
16511      * @return {String} name The field name
16512      */
16513     getName: function(){
16514          return this.rendered && this.el.dom.name ? this.el.dom.name : (this.hiddenName || '');
16515     },
16516
16517     // private
16518     onRender : function(ct, position){
16519         Roo.form.Field.superclass.onRender.call(this, ct, position);
16520         if(!this.el){
16521             var cfg = this.getAutoCreate();
16522             if(!cfg.name){
16523                 cfg.name = typeof(this.name) == 'undefined' ? this.id : this.name;
16524             }
16525             if (!cfg.name.length) {
16526                 delete cfg.name;
16527             }
16528             if(this.inputType){
16529                 cfg.type = this.inputType;
16530             }
16531             this.el = ct.createChild(cfg, position);
16532         }
16533         var type = this.el.dom.type;
16534         if(type){
16535             if(type == 'password'){
16536                 type = 'text';
16537             }
16538             this.el.addClass('x-form-'+type);
16539         }
16540         if(this.readOnly){
16541             this.el.dom.readOnly = true;
16542         }
16543         if(this.tabIndex !== undefined){
16544             this.el.dom.setAttribute('tabIndex', this.tabIndex);
16545         }
16546
16547         this.el.addClass([this.fieldClass, this.cls]);
16548         this.initValue();
16549     },
16550
16551     /**
16552      * Apply the behaviors of this component to an existing element. <b>This is used instead of render().</b>
16553      * @param {String/HTMLElement/Element} el The id of the node, a DOM node or an existing Element
16554      * @return {Roo.form.Field} this
16555      */
16556     applyTo : function(target){
16557         this.allowDomMove = false;
16558         this.el = Roo.get(target);
16559         this.render(this.el.dom.parentNode);
16560         return this;
16561     },
16562
16563     // private
16564     initValue : function(){
16565         if(this.value !== undefined){
16566             this.setValue(this.value);
16567         }else if(this.el.dom.value.length > 0){
16568             this.setValue(this.el.dom.value);
16569         }
16570     },
16571
16572     /**
16573      * Returns true if this field has been changed since it was originally loaded and is not disabled.
16574      * DEPRICATED  - it never worked well - use hasChanged/resetHasChanged.
16575      */
16576     isDirty : function() {
16577         if(this.disabled) {
16578             return false;
16579         }
16580         return String(this.getValue()) !== String(this.originalValue);
16581     },
16582
16583     /**
16584      * stores the current value in loadedValue
16585      */
16586     resetHasChanged : function()
16587     {
16588         this.loadedValue = String(this.getValue());
16589     },
16590     /**
16591      * checks the current value against the 'loaded' value.
16592      * Note - will return false if 'resetHasChanged' has not been called first.
16593      */
16594     hasChanged : function()
16595     {
16596         if(this.disabled || this.readOnly) {
16597             return false;
16598         }
16599         return this.loadedValue !== false && String(this.getValue()) !== this.loadedValue;
16600     },
16601     
16602     
16603     
16604     // private
16605     afterRender : function(){
16606         Roo.form.Field.superclass.afterRender.call(this);
16607         this.initEvents();
16608     },
16609
16610     // private
16611     fireKey : function(e){
16612         //Roo.log('field ' + e.getKey());
16613         if(e.isNavKeyPress()){
16614             this.fireEvent("specialkey", this, e);
16615         }
16616     },
16617
16618     /**
16619      * Resets the current field value to the originally loaded value and clears any validation messages
16620      */
16621     reset : function(){
16622         this.setValue(this.resetValue);
16623         this.originalValue = this.getValue();
16624         this.clearInvalid();
16625     },
16626
16627     // private
16628     initEvents : function(){
16629         // safari killled keypress - so keydown is now used..
16630         this.el.on("keydown" , this.fireKey,  this);
16631         this.el.on("focus", this.onFocus,  this);
16632         this.el.on("blur", this.onBlur,  this);
16633         this.el.relayEvent('keyup', this);
16634
16635         // reference to original value for reset
16636         this.originalValue = this.getValue();
16637         this.resetValue =  this.getValue();
16638     },
16639
16640     // private
16641     onFocus : function(){
16642         if(!Roo.isOpera && this.focusClass){ // don't touch in Opera
16643             this.el.addClass(this.focusClass);
16644         }
16645         if(!this.hasFocus){
16646             this.hasFocus = true;
16647             this.startValue = this.getValue();
16648             this.fireEvent("focus", this);
16649         }
16650     },
16651
16652     beforeBlur : Roo.emptyFn,
16653
16654     // private
16655     onBlur : function(){
16656         this.beforeBlur();
16657         if(!Roo.isOpera && this.focusClass){ // don't touch in Opera
16658             this.el.removeClass(this.focusClass);
16659         }
16660         this.hasFocus = false;
16661         if(this.validationEvent !== false && this.validateOnBlur && this.validationEvent != "blur"){
16662             this.validate();
16663         }
16664         var v = this.getValue();
16665         if(String(v) !== String(this.startValue)){
16666             this.fireEvent('change', this, v, this.startValue);
16667         }
16668         this.fireEvent("blur", this);
16669     },
16670
16671     /**
16672      * Returns whether or not the field value is currently valid
16673      * @param {Boolean} preventMark True to disable marking the field invalid
16674      * @return {Boolean} True if the value is valid, else false
16675      */
16676     isValid : function(preventMark){
16677         if(this.disabled){
16678             return true;
16679         }
16680         var restore = this.preventMark;
16681         this.preventMark = preventMark === true;
16682         var v = this.validateValue(this.processValue(this.getRawValue()));
16683         this.preventMark = restore;
16684         return v;
16685     },
16686
16687     /**
16688      * Validates the field value
16689      * @return {Boolean} True if the value is valid, else false
16690      */
16691     validate : function(){
16692         if(this.disabled || this.validateValue(this.processValue(this.getRawValue()))){
16693             this.clearInvalid();
16694             return true;
16695         }
16696         return false;
16697     },
16698
16699     processValue : function(value){
16700         return value;
16701     },
16702
16703     // private
16704     // Subclasses should provide the validation implementation by overriding this
16705     validateValue : function(value){
16706         return true;
16707     },
16708
16709     /**
16710      * Mark this field as invalid
16711      * @param {String} msg The validation message
16712      */
16713     markInvalid : function(msg){
16714         if(!this.rendered || this.preventMark){ // not rendered
16715             return;
16716         }
16717         
16718         var obj = (typeof(this.combo) != 'undefined') ? this.combo : this; // fix the combox array!!
16719         
16720         obj.el.addClass(this.invalidClass);
16721         msg = msg || this.invalidText;
16722         switch(this.msgTarget){
16723             case 'qtip':
16724                 obj.el.dom.qtip = msg;
16725                 obj.el.dom.qclass = 'x-form-invalid-tip';
16726                 if(Roo.QuickTips){ // fix for floating editors interacting with DND
16727                     Roo.QuickTips.enable();
16728                 }
16729                 break;
16730             case 'title':
16731                 this.el.dom.title = msg;
16732                 break;
16733             case 'under':
16734                 if(!this.errorEl){
16735                     var elp = this.el.findParent('.x-form-element', 5, true);
16736                     this.errorEl = elp.createChild({cls:'x-form-invalid-msg'});
16737                     this.errorEl.setWidth(elp.getWidth(true)-20);
16738                 }
16739                 this.errorEl.update(msg);
16740                 Roo.form.Field.msgFx[this.msgFx].show(this.errorEl, this);
16741                 break;
16742             case 'side':
16743                 if(!this.errorIcon){
16744                     var elp = this.el.findParent('.x-form-element', 5, true);
16745                     this.errorIcon = elp.createChild({cls:'x-form-invalid-icon'});
16746                 }
16747                 this.alignErrorIcon();
16748                 this.errorIcon.dom.qtip = msg;
16749                 this.errorIcon.dom.qclass = 'x-form-invalid-tip';
16750                 this.errorIcon.show();
16751                 this.on('resize', this.alignErrorIcon, this);
16752                 break;
16753             default:
16754                 var t = Roo.getDom(this.msgTarget);
16755                 t.innerHTML = msg;
16756                 t.style.display = this.msgDisplay;
16757                 break;
16758         }
16759         this.fireEvent('invalid', this, msg);
16760     },
16761
16762     // private
16763     alignErrorIcon : function(){
16764         this.errorIcon.alignTo(this.el, 'tl-tr', [2, 0]);
16765     },
16766
16767     /**
16768      * Clear any invalid styles/messages for this field
16769      */
16770     clearInvalid : function(){
16771         if(!this.rendered || this.preventMark){ // not rendered
16772             return;
16773         }
16774         var obj = (typeof(this.combo) != 'undefined') ? this.combo : this; // fix the combox array!!
16775         
16776         obj.el.removeClass(this.invalidClass);
16777         switch(this.msgTarget){
16778             case 'qtip':
16779                 obj.el.dom.qtip = '';
16780                 break;
16781             case 'title':
16782                 this.el.dom.title = '';
16783                 break;
16784             case 'under':
16785                 if(this.errorEl){
16786                     Roo.form.Field.msgFx[this.msgFx].hide(this.errorEl, this);
16787                 }
16788                 break;
16789             case 'side':
16790                 if(this.errorIcon){
16791                     this.errorIcon.dom.qtip = '';
16792                     this.errorIcon.hide();
16793                     this.un('resize', this.alignErrorIcon, this);
16794                 }
16795                 break;
16796             default:
16797                 var t = Roo.getDom(this.msgTarget);
16798                 t.innerHTML = '';
16799                 t.style.display = 'none';
16800                 break;
16801         }
16802         this.fireEvent('valid', this);
16803     },
16804
16805     /**
16806      * Returns the raw data value which may or may not be a valid, defined value.  To return a normalized value see {@link #getValue}.
16807      * @return {Mixed} value The field value
16808      */
16809     getRawValue : function(){
16810         var v = this.el.getValue();
16811         
16812         return v;
16813     },
16814
16815     /**
16816      * Returns the normalized data value (undefined or emptyText will be returned as '').  To return the raw value see {@link #getRawValue}.
16817      * @return {Mixed} value The field value
16818      */
16819     getValue : function(){
16820         var v = this.el.getValue();
16821          
16822         return v;
16823     },
16824
16825     /**
16826      * Sets the underlying DOM field's value directly, bypassing validation.  To set the value with validation see {@link #setValue}.
16827      * @param {Mixed} value The value to set
16828      */
16829     setRawValue : function(v){
16830         return this.el.dom.value = (v === null || v === undefined ? '' : v);
16831     },
16832
16833     /**
16834      * Sets a data value into the field and validates it.  To set the value directly without validation see {@link #setRawValue}.
16835      * @param {Mixed} value The value to set
16836      */
16837     setValue : function(v){
16838         this.value = v;
16839         if(this.rendered){
16840             this.el.dom.value = (v === null || v === undefined ? '' : v);
16841              this.validate();
16842         }
16843     },
16844
16845     adjustSize : function(w, h){
16846         var s = Roo.form.Field.superclass.adjustSize.call(this, w, h);
16847         s.width = this.adjustWidth(this.el.dom.tagName, s.width);
16848         return s;
16849     },
16850
16851     adjustWidth : function(tag, w){
16852         tag = tag.toLowerCase();
16853         if(typeof w == 'number' && Roo.isStrict && !Roo.isSafari){
16854             if(Roo.isIE && (tag == 'input' || tag == 'textarea')){
16855                 if(tag == 'input'){
16856                     return w + 2;
16857                 }
16858                 if(tag == 'textarea'){
16859                     return w-2;
16860                 }
16861             }else if(Roo.isOpera){
16862                 if(tag == 'input'){
16863                     return w + 2;
16864                 }
16865                 if(tag == 'textarea'){
16866                     return w-2;
16867                 }
16868             }
16869         }
16870         return w;
16871     }
16872 });
16873
16874
16875 // anything other than normal should be considered experimental
16876 Roo.form.Field.msgFx = {
16877     normal : {
16878         show: function(msgEl, f){
16879             msgEl.setDisplayed('block');
16880         },
16881
16882         hide : function(msgEl, f){
16883             msgEl.setDisplayed(false).update('');
16884         }
16885     },
16886
16887     slide : {
16888         show: function(msgEl, f){
16889             msgEl.slideIn('t', {stopFx:true});
16890         },
16891
16892         hide : function(msgEl, f){
16893             msgEl.slideOut('t', {stopFx:true,useDisplay:true});
16894         }
16895     },
16896
16897     slideRight : {
16898         show: function(msgEl, f){
16899             msgEl.fixDisplay();
16900             msgEl.alignTo(f.el, 'tl-tr');
16901             msgEl.slideIn('l', {stopFx:true});
16902         },
16903
16904         hide : function(msgEl, f){
16905             msgEl.slideOut('l', {stopFx:true,useDisplay:true});
16906         }
16907     }
16908 };/*
16909  * Based on:
16910  * Ext JS Library 1.1.1
16911  * Copyright(c) 2006-2007, Ext JS, LLC.
16912  *
16913  * Originally Released Under LGPL - original licence link has changed is not relivant.
16914  *
16915  * Fork - LGPL
16916  * <script type="text/javascript">
16917  */
16918  
16919
16920 /**
16921  * @class Roo.form.TextField
16922  * @extends Roo.form.Field
16923  * Basic text field.  Can be used as a direct replacement for traditional text inputs, or as the base
16924  * class for more sophisticated input controls (like {@link Roo.form.TextArea} and {@link Roo.form.ComboBox}).
16925  * @constructor
16926  * Creates a new TextField
16927  * @param {Object} config Configuration options
16928  */
16929 Roo.form.TextField = function(config){
16930     Roo.form.TextField.superclass.constructor.call(this, config);
16931     this.addEvents({
16932         /**
16933          * @event autosize
16934          * Fires when the autosize function is triggered.  The field may or may not have actually changed size
16935          * according to the default logic, but this event provides a hook for the developer to apply additional
16936          * logic at runtime to resize the field if needed.
16937              * @param {Roo.form.Field} this This text field
16938              * @param {Number} width The new field width
16939              */
16940         autosize : true
16941     });
16942 };
16943
16944 Roo.extend(Roo.form.TextField, Roo.form.Field,  {
16945     /**
16946      * @cfg {Boolean} grow True if this field should automatically grow and shrink to its content
16947      */
16948     grow : false,
16949     /**
16950      * @cfg {Number} growMin The minimum width to allow when grow = true (defaults to 30)
16951      */
16952     growMin : 30,
16953     /**
16954      * @cfg {Number} growMax The maximum width to allow when grow = true (defaults to 800)
16955      */
16956     growMax : 800,
16957     /**
16958      * @cfg {String} vtype A validation type name as defined in {@link Roo.form.VTypes} (defaults to null)
16959      */
16960     vtype : null,
16961     /**
16962      * @cfg {String} maskRe An input mask regular expression that will be used to filter keystrokes that don't match (defaults to null)
16963      */
16964     maskRe : null,
16965     /**
16966      * @cfg {Boolean} disableKeyFilter True to disable input keystroke filtering (defaults to false)
16967      */
16968     disableKeyFilter : false,
16969     /**
16970      * @cfg {Boolean} allowBlank False to validate that the value length > 0 (defaults to true)
16971      */
16972     allowBlank : true,
16973     /**
16974      * @cfg {Number} minLength Minimum input field length required (defaults to 0)
16975      */
16976     minLength : 0,
16977     /**
16978      * @cfg {Number} maxLength Maximum input field length allowed (defaults to Number.MAX_VALUE)
16979      */
16980     maxLength : Number.MAX_VALUE,
16981     /**
16982      * @cfg {String} minLengthText Error text to display if the minimum length validation fails (defaults to "The minimum length for this field is {minLength}")
16983      */
16984     minLengthText : "The minimum length for this field is {0}",
16985     /**
16986      * @cfg {String} maxLengthText Error text to display if the maximum length validation fails (defaults to "The maximum length for this field is {maxLength}")
16987      */
16988     maxLengthText : "The maximum length for this field is {0}",
16989     /**
16990      * @cfg {Boolean} selectOnFocus True to automatically select any existing field text when the field receives input focus (defaults to false)
16991      */
16992     selectOnFocus : false,
16993     /**
16994      * @cfg {Boolean} allowLeadingSpace True to prevent the stripping of leading white space 
16995      */    
16996     allowLeadingSpace : false,
16997     /**
16998      * @cfg {String} blankText Error text to display if the allow blank validation fails (defaults to "This field is required")
16999      */
17000     blankText : "This field is required",
17001     /**
17002      * @cfg {Function} validator A custom validation function to be called during field validation (defaults to null).
17003      * If available, this function will be called only after the basic validators all return true, and will be passed the
17004      * current field value and expected to return boolean true if the value is valid or a string error message if invalid.
17005      */
17006     validator : null,
17007     /**
17008      * @cfg {RegExp} regex A JavaScript RegExp object to be tested against the field value during validation (defaults to null).
17009      * If available, this regex will be evaluated only after the basic validators all return true, and will be passed the
17010      * current field value.  If the test fails, the field will be marked invalid using {@link #regexText}.
17011      */
17012     regex : null,
17013     /**
17014      * @cfg {String} regexText The error text to display if {@link #regex} is used and the test fails during validation (defaults to "")
17015      */
17016     regexText : "",
17017     /**
17018      * @cfg {String} emptyText The default text to display in an empty field - placeholder... (defaults to null).
17019      */
17020     emptyText : null,
17021    
17022
17023     // private
17024     initEvents : function()
17025     {
17026         if (this.emptyText) {
17027             this.el.attr('placeholder', this.emptyText);
17028         }
17029         
17030         Roo.form.TextField.superclass.initEvents.call(this);
17031         if(this.validationEvent == 'keyup'){
17032             this.validationTask = new Roo.util.DelayedTask(this.validate, this);
17033             this.el.on('keyup', this.filterValidation, this);
17034         }
17035         else if(this.validationEvent !== false){
17036             this.el.on(this.validationEvent, this.validate, this, {buffer: this.validationDelay});
17037         }
17038         
17039         if(this.selectOnFocus){
17040             this.on("focus", this.preFocus, this);
17041         }
17042         if (!this.allowLeadingSpace) {
17043             this.on('blur', this.cleanLeadingSpace, this);
17044         }
17045         
17046         if(this.maskRe || (this.vtype && this.disableKeyFilter !== true && (this.maskRe = Roo.form.VTypes[this.vtype+'Mask']))){
17047             this.el.on("keypress", this.filterKeys, this);
17048         }
17049         if(this.grow){
17050             this.el.on("keyup", this.onKeyUp,  this, {buffer:50});
17051             this.el.on("click", this.autoSize,  this);
17052         }
17053         if(this.el.is('input[type=password]') && Roo.isSafari){
17054             this.el.on('keydown', this.SafariOnKeyDown, this);
17055         }
17056     },
17057
17058     processValue : function(value){
17059         if(this.stripCharsRe){
17060             var newValue = value.replace(this.stripCharsRe, '');
17061             if(newValue !== value){
17062                 this.setRawValue(newValue);
17063                 return newValue;
17064             }
17065         }
17066         return value;
17067     },
17068
17069     filterValidation : function(e){
17070         if(!e.isNavKeyPress()){
17071             this.validationTask.delay(this.validationDelay);
17072         }
17073     },
17074
17075     // private
17076     onKeyUp : function(e){
17077         if(!e.isNavKeyPress()){
17078             this.autoSize();
17079         }
17080     },
17081     // private - clean the leading white space
17082     cleanLeadingSpace : function(e)
17083     {
17084         if ( this.inputType == 'file') {
17085             return;
17086         }
17087         
17088         this.setValue((this.getValue() + '').replace(/^\s+/,''));
17089     },
17090     /**
17091      * Resets the current field value to the originally-loaded value and clears any validation messages.
17092      *  
17093      */
17094     reset : function(){
17095         Roo.form.TextField.superclass.reset.call(this);
17096        
17097     }, 
17098     // private
17099     preFocus : function(){
17100         
17101         if(this.selectOnFocus){
17102             this.el.dom.select();
17103         }
17104     },
17105
17106     
17107     // private
17108     filterKeys : function(e){
17109         var k = e.getKey();
17110         if(!Roo.isIE && (e.isNavKeyPress() || k == e.BACKSPACE || (k == e.DELETE && e.button == -1))){
17111             return;
17112         }
17113         var c = e.getCharCode(), cc = String.fromCharCode(c);
17114         if(Roo.isIE && (e.isSpecialKey() || !cc)){
17115             return;
17116         }
17117         if(!this.maskRe.test(cc)){
17118             e.stopEvent();
17119         }
17120     },
17121
17122     setValue : function(v){
17123         
17124         Roo.form.TextField.superclass.setValue.apply(this, arguments);
17125         
17126         this.autoSize();
17127     },
17128
17129     /**
17130      * Validates a value according to the field's validation rules and marks the field as invalid
17131      * if the validation fails
17132      * @param {Mixed} value The value to validate
17133      * @return {Boolean} True if the value is valid, else false
17134      */
17135     validateValue : function(value){
17136         if(value.length < 1)  { // if it's blank
17137              if(this.allowBlank){
17138                 this.clearInvalid();
17139                 return true;
17140              }else{
17141                 this.markInvalid(this.blankText);
17142                 return false;
17143              }
17144         }
17145         if(value.length < this.minLength){
17146             this.markInvalid(String.format(this.minLengthText, this.minLength));
17147             return false;
17148         }
17149         if(value.length > this.maxLength){
17150             this.markInvalid(String.format(this.maxLengthText, this.maxLength));
17151             return false;
17152         }
17153         if(this.vtype){
17154             var vt = Roo.form.VTypes;
17155             if(!vt[this.vtype](value, this)){
17156                 this.markInvalid(this.vtypeText || vt[this.vtype +'Text']);
17157                 return false;
17158             }
17159         }
17160         if(typeof this.validator == "function"){
17161             var msg = this.validator(value);
17162             if(msg !== true){
17163                 this.markInvalid(msg);
17164                 return false;
17165             }
17166         }
17167         if(this.regex && !this.regex.test(value)){
17168             this.markInvalid(this.regexText);
17169             return false;
17170         }
17171         return true;
17172     },
17173
17174     /**
17175      * Selects text in this field
17176      * @param {Number} start (optional) The index where the selection should start (defaults to 0)
17177      * @param {Number} end (optional) The index where the selection should end (defaults to the text length)
17178      */
17179     selectText : function(start, end){
17180         var v = this.getRawValue();
17181         if(v.length > 0){
17182             start = start === undefined ? 0 : start;
17183             end = end === undefined ? v.length : end;
17184             var d = this.el.dom;
17185             if(d.setSelectionRange){
17186                 d.setSelectionRange(start, end);
17187             }else if(d.createTextRange){
17188                 var range = d.createTextRange();
17189                 range.moveStart("character", start);
17190                 range.moveEnd("character", v.length-end);
17191                 range.select();
17192             }
17193         }
17194     },
17195
17196     /**
17197      * Automatically grows the field to accomodate the width of the text up to the maximum field width allowed.
17198      * This only takes effect if grow = true, and fires the autosize event.
17199      */
17200     autoSize : function(){
17201         if(!this.grow || !this.rendered){
17202             return;
17203         }
17204         if(!this.metrics){
17205             this.metrics = Roo.util.TextMetrics.createInstance(this.el);
17206         }
17207         var el = this.el;
17208         var v = el.dom.value;
17209         var d = document.createElement('div');
17210         d.appendChild(document.createTextNode(v));
17211         v = d.innerHTML;
17212         d = null;
17213         v += "&#160;";
17214         var w = Math.min(this.growMax, Math.max(this.metrics.getWidth(v) + /* add extra padding */ 10, this.growMin));
17215         this.el.setWidth(w);
17216         this.fireEvent("autosize", this, w);
17217     },
17218     
17219     // private
17220     SafariOnKeyDown : function(event)
17221     {
17222         // this is a workaround for a password hang bug on chrome/ webkit.
17223         
17224         var isSelectAll = false;
17225         
17226         if(this.el.dom.selectionEnd > 0){
17227             isSelectAll = (this.el.dom.selectionEnd - this.el.dom.selectionStart - this.getValue().length == 0) ? true : false;
17228         }
17229         if(((event.getKey() == 8 || event.getKey() == 46) && this.getValue().length ==1)){ // backspace and delete key
17230             event.preventDefault();
17231             this.setValue('');
17232             return;
17233         }
17234         
17235         if(isSelectAll && event.getCharCode() > 31){ // backspace and delete key
17236             
17237             event.preventDefault();
17238             // this is very hacky as keydown always get's upper case.
17239             
17240             var cc = String.fromCharCode(event.getCharCode());
17241             
17242             
17243             this.setValue( event.shiftKey ?  cc : cc.toLowerCase());
17244             
17245         }
17246         
17247         
17248     }
17249 });/*
17250  * Based on:
17251  * Ext JS Library 1.1.1
17252  * Copyright(c) 2006-2007, Ext JS, LLC.
17253  *
17254  * Originally Released Under LGPL - original licence link has changed is not relivant.
17255  *
17256  * Fork - LGPL
17257  * <script type="text/javascript">
17258  */
17259  
17260 /**
17261  * @class Roo.form.Hidden
17262  * @extends Roo.form.TextField
17263  * Simple Hidden element used on forms 
17264  * 
17265  * usage: form.add(new Roo.form.HiddenField({ 'name' : 'test1' }));
17266  * 
17267  * @constructor
17268  * Creates a new Hidden form element.
17269  * @param {Object} config Configuration options
17270  */
17271
17272
17273
17274 // easy hidden field...
17275 Roo.form.Hidden = function(config){
17276     Roo.form.Hidden.superclass.constructor.call(this, config);
17277 };
17278   
17279 Roo.extend(Roo.form.Hidden, Roo.form.TextField, {
17280     fieldLabel:      '',
17281     inputType:      'hidden',
17282     width:          50,
17283     allowBlank:     true,
17284     labelSeparator: '',
17285     hidden:         true,
17286     itemCls :       'x-form-item-display-none'
17287
17288
17289 });
17290
17291
17292 /*
17293  * Based on:
17294  * Ext JS Library 1.1.1
17295  * Copyright(c) 2006-2007, Ext JS, LLC.
17296  *
17297  * Originally Released Under LGPL - original licence link has changed is not relivant.
17298  *
17299  * Fork - LGPL
17300  * <script type="text/javascript">
17301  */
17302  
17303 /**
17304  * @class Roo.form.TriggerField
17305  * @extends Roo.form.TextField
17306  * Provides a convenient wrapper for TextFields that adds a clickable trigger button (looks like a combobox by default).
17307  * The trigger has no default action, so you must assign a function to implement the trigger click handler by
17308  * overriding {@link #onTriggerClick}. You can create a TriggerField directly, as it renders exactly like a combobox
17309  * for which you can provide a custom implementation.  For example:
17310  * <pre><code>
17311 var trigger = new Roo.form.TriggerField();
17312 trigger.onTriggerClick = myTriggerFn;
17313 trigger.applyTo('my-field');
17314 </code></pre>
17315  *
17316  * However, in general you will most likely want to use TriggerField as the base class for a reusable component.
17317  * {@link Roo.form.DateField} and {@link Roo.form.ComboBox} are perfect examples of this.
17318  * @cfg {String} triggerClass An additional CSS class used to style the trigger button.  The trigger will always get the
17319  * class 'x-form-trigger' by default and triggerClass will be <b>appended</b> if specified.
17320  * @constructor
17321  * Create a new TriggerField.
17322  * @param {Object} config Configuration options (valid {@Roo.form.TextField} config options will also be applied
17323  * to the base TextField)
17324  */
17325 Roo.form.TriggerField = function(config){
17326     this.mimicing = false;
17327     Roo.form.TriggerField.superclass.constructor.call(this, config);
17328 };
17329
17330 Roo.extend(Roo.form.TriggerField, Roo.form.TextField,  {
17331     /**
17332      * @cfg {String} triggerClass A CSS class to apply to the trigger
17333      */
17334     /**
17335      * @cfg {String/Object} autoCreate A DomHelper element spec, or true for a default element spec (defaults to
17336      * {tag: "input", type: "text", size: "16", autocomplete: "off"})
17337      */
17338     defaultAutoCreate : {tag: "input", type: "text", size: "16", autocomplete: "new-password"},
17339     /**
17340      * @cfg {Boolean} hideTrigger True to hide the trigger element and display only the base text field (defaults to false)
17341      */
17342     hideTrigger:false,
17343
17344     /** @cfg {Boolean} grow @hide */
17345     /** @cfg {Number} growMin @hide */
17346     /** @cfg {Number} growMax @hide */
17347
17348     /**
17349      * @hide 
17350      * @method
17351      */
17352     autoSize: Roo.emptyFn,
17353     // private
17354     monitorTab : true,
17355     // private
17356     deferHeight : true,
17357
17358     
17359     actionMode : 'wrap',
17360     // private
17361     onResize : function(w, h){
17362         Roo.form.TriggerField.superclass.onResize.apply(this, arguments);
17363         if(typeof w == 'number'){
17364             var x = w - this.trigger.getWidth();
17365             this.el.setWidth(this.adjustWidth('input', x));
17366             this.trigger.setStyle('left', x+'px');
17367         }
17368     },
17369
17370     // private
17371     adjustSize : Roo.BoxComponent.prototype.adjustSize,
17372
17373     // private
17374     getResizeEl : function(){
17375         return this.wrap;
17376     },
17377
17378     // private
17379     getPositionEl : function(){
17380         return this.wrap;
17381     },
17382
17383     // private
17384     alignErrorIcon : function(){
17385         this.errorIcon.alignTo(this.wrap, 'tl-tr', [2, 0]);
17386     },
17387
17388     // private
17389     onRender : function(ct, position){
17390         Roo.form.TriggerField.superclass.onRender.call(this, ct, position);
17391         this.wrap = this.el.wrap({cls: "x-form-field-wrap"});
17392         this.trigger = this.wrap.createChild(this.triggerConfig ||
17393                 {tag: "img", src: Roo.BLANK_IMAGE_URL, cls: "x-form-trigger " + this.triggerClass});
17394         if(this.hideTrigger){
17395             this.trigger.setDisplayed(false);
17396         }
17397         this.initTrigger();
17398         if(!this.width){
17399             this.wrap.setWidth(this.el.getWidth()+this.trigger.getWidth());
17400         }
17401     },
17402
17403     // private
17404     initTrigger : function(){
17405         this.trigger.on("click", this.onTriggerClick, this, {preventDefault:true});
17406         this.trigger.addClassOnOver('x-form-trigger-over');
17407         this.trigger.addClassOnClick('x-form-trigger-click');
17408     },
17409
17410     // private
17411     onDestroy : function(){
17412         if(this.trigger){
17413             this.trigger.removeAllListeners();
17414             this.trigger.remove();
17415         }
17416         if(this.wrap){
17417             this.wrap.remove();
17418         }
17419         Roo.form.TriggerField.superclass.onDestroy.call(this);
17420     },
17421
17422     // private
17423     onFocus : function(){
17424         Roo.form.TriggerField.superclass.onFocus.call(this);
17425         if(!this.mimicing){
17426             this.wrap.addClass('x-trigger-wrap-focus');
17427             this.mimicing = true;
17428             Roo.get(Roo.isIE ? document.body : document).on("mousedown", this.mimicBlur, this);
17429             if(this.monitorTab){
17430                 this.el.on("keydown", this.checkTab, this);
17431             }
17432         }
17433     },
17434
17435     // private
17436     checkTab : function(e){
17437         if(e.getKey() == e.TAB){
17438             this.triggerBlur();
17439         }
17440     },
17441
17442     // private
17443     onBlur : function(){
17444         // do nothing
17445     },
17446
17447     // private
17448     mimicBlur : function(e, t){
17449         if(!this.wrap.contains(t) && this.validateBlur()){
17450             this.triggerBlur();
17451         }
17452     },
17453
17454     // private
17455     triggerBlur : function(){
17456         this.mimicing = false;
17457         Roo.get(Roo.isIE ? document.body : document).un("mousedown", this.mimicBlur);
17458         if(this.monitorTab){
17459             this.el.un("keydown", this.checkTab, this);
17460         }
17461         this.wrap.removeClass('x-trigger-wrap-focus');
17462         Roo.form.TriggerField.superclass.onBlur.call(this);
17463     },
17464
17465     // private
17466     // This should be overriden by any subclass that needs to check whether or not the field can be blurred.
17467     validateBlur : function(e, t){
17468         return true;
17469     },
17470
17471     // private
17472     onDisable : function(){
17473         Roo.form.TriggerField.superclass.onDisable.call(this);
17474         if(this.wrap){
17475             this.wrap.addClass('x-item-disabled');
17476         }
17477     },
17478
17479     // private
17480     onEnable : function(){
17481         Roo.form.TriggerField.superclass.onEnable.call(this);
17482         if(this.wrap){
17483             this.wrap.removeClass('x-item-disabled');
17484         }
17485     },
17486
17487     // private
17488     onShow : function(){
17489         var ae = this.getActionEl();
17490         
17491         if(ae){
17492             ae.dom.style.display = '';
17493             ae.dom.style.visibility = 'visible';
17494         }
17495     },
17496
17497     // private
17498     
17499     onHide : function(){
17500         var ae = this.getActionEl();
17501         ae.dom.style.display = 'none';
17502     },
17503
17504     /**
17505      * The function that should handle the trigger's click event.  This method does nothing by default until overridden
17506      * by an implementing function.
17507      * @method
17508      * @param {EventObject} e
17509      */
17510     onTriggerClick : Roo.emptyFn
17511 });
17512
17513 // TwinTriggerField is not a public class to be used directly.  It is meant as an abstract base class
17514 // to be extended by an implementing class.  For an example of implementing this class, see the custom
17515 // SearchField implementation here: http://extjs.com/deploy/ext/examples/form/custom.html
17516 Roo.form.TwinTriggerField = Roo.extend(Roo.form.TriggerField, {
17517     initComponent : function(){
17518         Roo.form.TwinTriggerField.superclass.initComponent.call(this);
17519
17520         this.triggerConfig = {
17521             tag:'span', cls:'x-form-twin-triggers', cn:[
17522             {tag: "img", src: Roo.BLANK_IMAGE_URL, cls: "x-form-trigger " + this.trigger1Class},
17523             {tag: "img", src: Roo.BLANK_IMAGE_URL, cls: "x-form-trigger " + this.trigger2Class}
17524         ]};
17525     },
17526
17527     getTrigger : function(index){
17528         return this.triggers[index];
17529     },
17530
17531     initTrigger : function(){
17532         var ts = this.trigger.select('.x-form-trigger', true);
17533         this.wrap.setStyle('overflow', 'hidden');
17534         var triggerField = this;
17535         ts.each(function(t, all, index){
17536             t.hide = function(){
17537                 var w = triggerField.wrap.getWidth();
17538                 this.dom.style.display = 'none';
17539                 triggerField.el.setWidth(w-triggerField.trigger.getWidth());
17540             };
17541             t.show = function(){
17542                 var w = triggerField.wrap.getWidth();
17543                 this.dom.style.display = '';
17544                 triggerField.el.setWidth(w-triggerField.trigger.getWidth());
17545             };
17546             var triggerIndex = 'Trigger'+(index+1);
17547
17548             if(this['hide'+triggerIndex]){
17549                 t.dom.style.display = 'none';
17550             }
17551             t.on("click", this['on'+triggerIndex+'Click'], this, {preventDefault:true});
17552             t.addClassOnOver('x-form-trigger-over');
17553             t.addClassOnClick('x-form-trigger-click');
17554         }, this);
17555         this.triggers = ts.elements;
17556     },
17557
17558     onTrigger1Click : Roo.emptyFn,
17559     onTrigger2Click : Roo.emptyFn
17560 });/*
17561  * Based on:
17562  * Ext JS Library 1.1.1
17563  * Copyright(c) 2006-2007, Ext JS, LLC.
17564  *
17565  * Originally Released Under LGPL - original licence link has changed is not relivant.
17566  *
17567  * Fork - LGPL
17568  * <script type="text/javascript">
17569  */
17570  
17571 /**
17572  * @class Roo.form.TextArea
17573  * @extends Roo.form.TextField
17574  * Multiline text field.  Can be used as a direct replacement for traditional textarea fields, plus adds
17575  * support for auto-sizing.
17576  * @constructor
17577  * Creates a new TextArea
17578  * @param {Object} config Configuration options
17579  */
17580 Roo.form.TextArea = function(config){
17581     Roo.form.TextArea.superclass.constructor.call(this, config);
17582     // these are provided exchanges for backwards compat
17583     // minHeight/maxHeight were replaced by growMin/growMax to be
17584     // compatible with TextField growing config values
17585     if(this.minHeight !== undefined){
17586         this.growMin = this.minHeight;
17587     }
17588     if(this.maxHeight !== undefined){
17589         this.growMax = this.maxHeight;
17590     }
17591 };
17592
17593 Roo.extend(Roo.form.TextArea, Roo.form.TextField,  {
17594     /**
17595      * @cfg {Number} growMin The minimum height to allow when grow = true (defaults to 60)
17596      */
17597     growMin : 60,
17598     /**
17599      * @cfg {Number} growMax The maximum height to allow when grow = true (defaults to 1000)
17600      */
17601     growMax: 1000,
17602     /**
17603      * @cfg {Boolean} preventScrollbars True to prevent scrollbars from appearing regardless of how much text is
17604      * in the field (equivalent to setting overflow: hidden, defaults to false)
17605      */
17606     preventScrollbars: false,
17607     /**
17608      * @cfg {String/Object} autoCreate A DomHelper element spec, or true for a default element spec (defaults to
17609      * {tag: "textarea", style: "width:300px;height:60px;", autocomplete: "off"})
17610      */
17611
17612     // private
17613     onRender : function(ct, position){
17614         if(!this.el){
17615             this.defaultAutoCreate = {
17616                 tag: "textarea",
17617                 style:"width:300px;height:60px;",
17618                 autocomplete: "new-password"
17619             };
17620         }
17621         Roo.form.TextArea.superclass.onRender.call(this, ct, position);
17622         if(this.grow){
17623             this.textSizeEl = Roo.DomHelper.append(document.body, {
17624                 tag: "pre", cls: "x-form-grow-sizer"
17625             });
17626             if(this.preventScrollbars){
17627                 this.el.setStyle("overflow", "hidden");
17628             }
17629             this.el.setHeight(this.growMin);
17630         }
17631     },
17632
17633     onDestroy : function(){
17634         if(this.textSizeEl){
17635             this.textSizeEl.parentNode.removeChild(this.textSizeEl);
17636         }
17637         Roo.form.TextArea.superclass.onDestroy.call(this);
17638     },
17639
17640     // private
17641     onKeyUp : function(e){
17642         if(!e.isNavKeyPress() || e.getKey() == e.ENTER){
17643             this.autoSize();
17644         }
17645     },
17646
17647     /**
17648      * Automatically grows the field to accomodate the height of the text up to the maximum field height allowed.
17649      * This only takes effect if grow = true, and fires the autosize event if the height changes.
17650      */
17651     autoSize : function(){
17652         if(!this.grow || !this.textSizeEl){
17653             return;
17654         }
17655         var el = this.el;
17656         var v = el.dom.value;
17657         var ts = this.textSizeEl;
17658
17659         ts.innerHTML = '';
17660         ts.appendChild(document.createTextNode(v));
17661         v = ts.innerHTML;
17662
17663         Roo.fly(ts).setWidth(this.el.getWidth());
17664         if(v.length < 1){
17665             v = "&#160;&#160;";
17666         }else{
17667             if(Roo.isIE){
17668                 v = v.replace(/\n/g, '<p>&#160;</p>');
17669             }
17670             v += "&#160;\n&#160;";
17671         }
17672         ts.innerHTML = v;
17673         var h = Math.min(this.growMax, Math.max(ts.offsetHeight, this.growMin));
17674         if(h != this.lastHeight){
17675             this.lastHeight = h;
17676             this.el.setHeight(h);
17677             this.fireEvent("autosize", this, h);
17678         }
17679     }
17680 });/*
17681  * Based on:
17682  * Ext JS Library 1.1.1
17683  * Copyright(c) 2006-2007, Ext JS, LLC.
17684  *
17685  * Originally Released Under LGPL - original licence link has changed is not relivant.
17686  *
17687  * Fork - LGPL
17688  * <script type="text/javascript">
17689  */
17690  
17691
17692 /**
17693  * @class Roo.form.NumberField
17694  * @extends Roo.form.TextField
17695  * Numeric text field that provides automatic keystroke filtering and numeric validation.
17696  * @constructor
17697  * Creates a new NumberField
17698  * @param {Object} config Configuration options
17699  */
17700 Roo.form.NumberField = function(config){
17701     Roo.form.NumberField.superclass.constructor.call(this, config);
17702 };
17703
17704 Roo.extend(Roo.form.NumberField, Roo.form.TextField,  {
17705     /**
17706      * @cfg {String} fieldClass The default CSS class for the field (defaults to "x-form-field x-form-num-field")
17707      */
17708     fieldClass: "x-form-field x-form-num-field",
17709     /**
17710      * @cfg {Boolean} allowDecimals False to disallow decimal values (defaults to true)
17711      */
17712     allowDecimals : true,
17713     /**
17714      * @cfg {String} decimalSeparator Character(s) to allow as the decimal separator (defaults to '.')
17715      */
17716     decimalSeparator : ".",
17717     /**
17718      * @cfg {Number} decimalPrecision The maximum precision to display after the decimal separator (defaults to 2)
17719      */
17720     decimalPrecision : 2,
17721     /**
17722      * @cfg {Boolean} allowNegative False to prevent entering a negative sign (defaults to true)
17723      */
17724     allowNegative : true,
17725     /**
17726      * @cfg {Number} minValue The minimum allowed value (defaults to Number.NEGATIVE_INFINITY)
17727      */
17728     minValue : Number.NEGATIVE_INFINITY,
17729     /**
17730      * @cfg {Number} maxValue The maximum allowed value (defaults to Number.MAX_VALUE)
17731      */
17732     maxValue : Number.MAX_VALUE,
17733     /**
17734      * @cfg {String} minText Error text to display if the minimum value validation fails (defaults to "The minimum value for this field is {minValue}")
17735      */
17736     minText : "The minimum value for this field is {0}",
17737     /**
17738      * @cfg {String} maxText Error text to display if the maximum value validation fails (defaults to "The maximum value for this field is {maxValue}")
17739      */
17740     maxText : "The maximum value for this field is {0}",
17741     /**
17742      * @cfg {String} nanText Error text to display if the value is not a valid number.  For example, this can happen
17743      * if a valid character like '.' or '-' is left in the field with no number (defaults to "{value} is not a valid number")
17744      */
17745     nanText : "{0} is not a valid number",
17746
17747     // private
17748     initEvents : function(){
17749         Roo.form.NumberField.superclass.initEvents.call(this);
17750         var allowed = "0123456789";
17751         if(this.allowDecimals){
17752             allowed += this.decimalSeparator;
17753         }
17754         if(this.allowNegative){
17755             allowed += "-";
17756         }
17757         this.stripCharsRe = new RegExp('[^'+allowed+']', 'gi');
17758         var keyPress = function(e){
17759             var k = e.getKey();
17760             if(!Roo.isIE && (e.isSpecialKey() || k == e.BACKSPACE || k == e.DELETE)){
17761                 return;
17762             }
17763             var c = e.getCharCode();
17764             if(allowed.indexOf(String.fromCharCode(c)) === -1){
17765                 e.stopEvent();
17766             }
17767         };
17768         this.el.on("keypress", keyPress, this);
17769     },
17770
17771     // private
17772     validateValue : function(value){
17773         if(!Roo.form.NumberField.superclass.validateValue.call(this, value)){
17774             return false;
17775         }
17776         if(value.length < 1){ // if it's blank and textfield didn't flag it then it's valid
17777              return true;
17778         }
17779         var num = this.parseValue(value);
17780         if(isNaN(num)){
17781             this.markInvalid(String.format(this.nanText, value));
17782             return false;
17783         }
17784         if(num < this.minValue){
17785             this.markInvalid(String.format(this.minText, this.minValue));
17786             return false;
17787         }
17788         if(num > this.maxValue){
17789             this.markInvalid(String.format(this.maxText, this.maxValue));
17790             return false;
17791         }
17792         return true;
17793     },
17794
17795     getValue : function(){
17796         return this.fixPrecision(this.parseValue(Roo.form.NumberField.superclass.getValue.call(this)));
17797     },
17798
17799     // private
17800     parseValue : function(value){
17801         value = parseFloat(String(value).replace(this.decimalSeparator, "."));
17802         return isNaN(value) ? '' : value;
17803     },
17804
17805     // private
17806     fixPrecision : function(value){
17807         var nan = isNaN(value);
17808         if(!this.allowDecimals || this.decimalPrecision == -1 || nan || !value){
17809             return nan ? '' : value;
17810         }
17811         return parseFloat(value).toFixed(this.decimalPrecision);
17812     },
17813
17814     setValue : function(v){
17815         v = this.fixPrecision(v);
17816         Roo.form.NumberField.superclass.setValue.call(this, String(v).replace(".", this.decimalSeparator));
17817     },
17818
17819     // private
17820     decimalPrecisionFcn : function(v){
17821         return Math.floor(v);
17822     },
17823
17824     beforeBlur : function(){
17825         var v = this.parseValue(this.getRawValue());
17826         if(v){
17827             this.setValue(v);
17828         }
17829     }
17830 });/*
17831  * Based on:
17832  * Ext JS Library 1.1.1
17833  * Copyright(c) 2006-2007, Ext JS, LLC.
17834  *
17835  * Originally Released Under LGPL - original licence link has changed is not relivant.
17836  *
17837  * Fork - LGPL
17838  * <script type="text/javascript">
17839  */
17840  
17841 /**
17842  * @class Roo.form.DateField
17843  * @extends Roo.form.TriggerField
17844  * Provides a date input field with a {@link Roo.DatePicker} dropdown and automatic date validation.
17845 * @constructor
17846 * Create a new DateField
17847 * @param {Object} config
17848  */
17849 Roo.form.DateField = function(config)
17850 {
17851     Roo.form.DateField.superclass.constructor.call(this, config);
17852     
17853       this.addEvents({
17854          
17855         /**
17856          * @event select
17857          * Fires when a date is selected
17858              * @param {Roo.form.DateField} combo This combo box
17859              * @param {Date} date The date selected
17860              */
17861         'select' : true
17862          
17863     });
17864     
17865     
17866     if(typeof this.minValue == "string") {
17867         this.minValue = this.parseDate(this.minValue);
17868     }
17869     if(typeof this.maxValue == "string") {
17870         this.maxValue = this.parseDate(this.maxValue);
17871     }
17872     this.ddMatch = null;
17873     if(this.disabledDates){
17874         var dd = this.disabledDates;
17875         var re = "(?:";
17876         for(var i = 0; i < dd.length; i++){
17877             re += dd[i];
17878             if(i != dd.length-1) {
17879                 re += "|";
17880             }
17881         }
17882         this.ddMatch = new RegExp(re + ")");
17883     }
17884 };
17885
17886 Roo.extend(Roo.form.DateField, Roo.form.TriggerField,  {
17887     /**
17888      * @cfg {String} format
17889      * The default date format string which can be overriden for localization support.  The format must be
17890      * valid according to {@link Date#parseDate} (defaults to 'm/d/y').
17891      */
17892     format : "m/d/y",
17893     /**
17894      * @cfg {String} altFormats
17895      * Multiple date formats separated by "|" to try when parsing a user input value and it doesn't match the defined
17896      * format (defaults to 'm/d/Y|m-d-y|m-d-Y|m/d|m-d|d').
17897      */
17898     altFormats : "m/d/Y|m-d-y|m-d-Y|m/d|m-d|md|mdy|mdY|d",
17899     /**
17900      * @cfg {Array} disabledDays
17901      * An array of days to disable, 0 based. For example, [0, 6] disables Sunday and Saturday (defaults to null).
17902      */
17903     disabledDays : null,
17904     /**
17905      * @cfg {String} disabledDaysText
17906      * The tooltip to display when the date falls on a disabled day (defaults to 'Disabled')
17907      */
17908     disabledDaysText : "Disabled",
17909     /**
17910      * @cfg {Array} disabledDates
17911      * An array of "dates" to disable, as strings. These strings will be used to build a dynamic regular
17912      * expression so they are very powerful. Some examples:
17913      * <ul>
17914      * <li>["03/08/2003", "09/16/2003"] would disable those exact dates</li>
17915      * <li>["03/08", "09/16"] would disable those days for every year</li>
17916      * <li>["^03/08"] would only match the beginning (useful if you are using short years)</li>
17917      * <li>["03/../2006"] would disable every day in March 2006</li>
17918      * <li>["^03"] would disable every day in every March</li>
17919      * </ul>
17920      * In order to support regular expressions, if you are using a date format that has "." in it, you will have to
17921      * escape the dot when restricting dates. For example: ["03\\.08\\.03"].
17922      */
17923     disabledDates : null,
17924     /**
17925      * @cfg {String} disabledDatesText
17926      * The tooltip text to display when the date falls on a disabled date (defaults to 'Disabled')
17927      */
17928     disabledDatesText : "Disabled",
17929     /**
17930      * @cfg {Date/String} minValue
17931      * The minimum allowed date. Can be either a Javascript date object or a string date in a
17932      * valid format (defaults to null).
17933      */
17934     minValue : null,
17935     /**
17936      * @cfg {Date/String} maxValue
17937      * The maximum allowed date. Can be either a Javascript date object or a string date in a
17938      * valid format (defaults to null).
17939      */
17940     maxValue : null,
17941     /**
17942      * @cfg {String} minText
17943      * The error text to display when the date in the cell is before minValue (defaults to
17944      * 'The date in this field must be after {minValue}').
17945      */
17946     minText : "The date in this field must be equal to or after {0}",
17947     /**
17948      * @cfg {String} maxText
17949      * The error text to display when the date in the cell is after maxValue (defaults to
17950      * 'The date in this field must be before {maxValue}').
17951      */
17952     maxText : "The date in this field must be equal to or before {0}",
17953     /**
17954      * @cfg {String} invalidText
17955      * The error text to display when the date in the field is invalid (defaults to
17956      * '{value} is not a valid date - it must be in the format {format}').
17957      */
17958     invalidText : "{0} is not a valid date - it must be in the format {1}",
17959     /**
17960      * @cfg {String} triggerClass
17961      * An additional CSS class used to style the trigger button.  The trigger will always get the
17962      * class 'x-form-trigger' and triggerClass will be <b>appended</b> if specified (defaults to 'x-form-date-trigger'
17963      * which displays a calendar icon).
17964      */
17965     triggerClass : 'x-form-date-trigger',
17966     
17967
17968     /**
17969      * @cfg {Boolean} useIso
17970      * if enabled, then the date field will use a hidden field to store the 
17971      * real value as iso formated date. default (false)
17972      */ 
17973     useIso : false,
17974     /**
17975      * @cfg {String/Object} autoCreate
17976      * A DomHelper element spec, or true for a default element spec (defaults to
17977      * {tag: "input", type: "text", size: "10", autocomplete: "off"})
17978      */ 
17979     // private
17980     defaultAutoCreate : {tag: "input", type: "text", size: "10", autocomplete: "off"},
17981     
17982     // private
17983     hiddenField: false,
17984     
17985     onRender : function(ct, position)
17986     {
17987         Roo.form.DateField.superclass.onRender.call(this, ct, position);
17988         if (this.useIso) {
17989             //this.el.dom.removeAttribute('name'); 
17990             Roo.log("Changing name?");
17991             this.el.dom.setAttribute('name', this.name + '____hidden___' ); 
17992             this.hiddenField = this.el.insertSibling({ tag:'input', type:'hidden', name: this.name },
17993                     'before', true);
17994             this.hiddenField.value = this.value ? this.formatDate(this.value, 'Y-m-d') : '';
17995             // prevent input submission
17996             this.hiddenName = this.name;
17997         }
17998             
17999             
18000     },
18001     
18002     // private
18003     validateValue : function(value)
18004     {
18005         value = this.formatDate(value);
18006         if(!Roo.form.DateField.superclass.validateValue.call(this, value)){
18007             Roo.log('super failed');
18008             return false;
18009         }
18010         if(value.length < 1){ // if it's blank and textfield didn't flag it then it's valid
18011              return true;
18012         }
18013         var svalue = value;
18014         value = this.parseDate(value);
18015         if(!value){
18016             Roo.log('parse date failed' + svalue);
18017             this.markInvalid(String.format(this.invalidText, svalue, this.format));
18018             return false;
18019         }
18020         var time = value.getTime();
18021         if(this.minValue && time < this.minValue.getTime()){
18022             this.markInvalid(String.format(this.minText, this.formatDate(this.minValue)));
18023             return false;
18024         }
18025         if(this.maxValue && time > this.maxValue.getTime()){
18026             this.markInvalid(String.format(this.maxText, this.formatDate(this.maxValue)));
18027             return false;
18028         }
18029         if(this.disabledDays){
18030             var day = value.getDay();
18031             for(var i = 0; i < this.disabledDays.length; i++) {
18032                 if(day === this.disabledDays[i]){
18033                     this.markInvalid(this.disabledDaysText);
18034                     return false;
18035                 }
18036             }
18037         }
18038         var fvalue = this.formatDate(value);
18039         if(this.ddMatch && this.ddMatch.test(fvalue)){
18040             this.markInvalid(String.format(this.disabledDatesText, fvalue));
18041             return false;
18042         }
18043         return true;
18044     },
18045
18046     // private
18047     // Provides logic to override the default TriggerField.validateBlur which just returns true
18048     validateBlur : function(){
18049         return !this.menu || !this.menu.isVisible();
18050     },
18051     
18052     getName: function()
18053     {
18054         // returns hidden if it's set..
18055         if (!this.rendered) {return ''};
18056         return !this.hiddenName && this.el.dom.name  ? this.el.dom.name : (this.hiddenName || '');
18057         
18058     },
18059
18060     /**
18061      * Returns the current date value of the date field.
18062      * @return {Date} The date value
18063      */
18064     getValue : function(){
18065         
18066         return  this.hiddenField ?
18067                 this.hiddenField.value :
18068                 this.parseDate(Roo.form.DateField.superclass.getValue.call(this)) || "";
18069     },
18070
18071     /**
18072      * Sets the value of the date field.  You can pass a date object or any string that can be parsed into a valid
18073      * date, using DateField.format as the date format, according to the same rules as {@link Date#parseDate}
18074      * (the default format used is "m/d/y").
18075      * <br />Usage:
18076      * <pre><code>
18077 //All of these calls set the same date value (May 4, 2006)
18078
18079 //Pass a date object:
18080 var dt = new Date('5/4/06');
18081 dateField.setValue(dt);
18082
18083 //Pass a date string (default format):
18084 dateField.setValue('5/4/06');
18085
18086 //Pass a date string (custom format):
18087 dateField.format = 'Y-m-d';
18088 dateField.setValue('2006-5-4');
18089 </code></pre>
18090      * @param {String/Date} date The date or valid date string
18091      */
18092     setValue : function(date){
18093         if (this.hiddenField) {
18094             this.hiddenField.value = this.formatDate(this.parseDate(date), 'Y-m-d');
18095         }
18096         Roo.form.DateField.superclass.setValue.call(this, this.formatDate(this.parseDate(date)));
18097         // make sure the value field is always stored as a date..
18098         this.value = this.parseDate(date);
18099         
18100         
18101     },
18102
18103     // private
18104     parseDate : function(value){
18105         if(!value || value instanceof Date){
18106             return value;
18107         }
18108         var v = Date.parseDate(value, this.format);
18109          if (!v && this.useIso) {
18110             v = Date.parseDate(value, 'Y-m-d');
18111         }
18112         if(!v && this.altFormats){
18113             if(!this.altFormatsArray){
18114                 this.altFormatsArray = this.altFormats.split("|");
18115             }
18116             for(var i = 0, len = this.altFormatsArray.length; i < len && !v; i++){
18117                 v = Date.parseDate(value, this.altFormatsArray[i]);
18118             }
18119         }
18120         return v;
18121     },
18122
18123     // private
18124     formatDate : function(date, fmt){
18125         return (!date || !(date instanceof Date)) ?
18126                date : date.dateFormat(fmt || this.format);
18127     },
18128
18129     // private
18130     menuListeners : {
18131         select: function(m, d){
18132             
18133             this.setValue(d);
18134             this.fireEvent('select', this, d);
18135         },
18136         show : function(){ // retain focus styling
18137             this.onFocus();
18138         },
18139         hide : function(){
18140             this.focus.defer(10, this);
18141             var ml = this.menuListeners;
18142             this.menu.un("select", ml.select,  this);
18143             this.menu.un("show", ml.show,  this);
18144             this.menu.un("hide", ml.hide,  this);
18145         }
18146     },
18147
18148     // private
18149     // Implements the default empty TriggerField.onTriggerClick function to display the DatePicker
18150     onTriggerClick : function(){
18151         if(this.disabled){
18152             return;
18153         }
18154         if(this.menu == null){
18155             this.menu = new Roo.menu.DateMenu();
18156         }
18157         Roo.apply(this.menu.picker,  {
18158             showClear: this.allowBlank,
18159             minDate : this.minValue,
18160             maxDate : this.maxValue,
18161             disabledDatesRE : this.ddMatch,
18162             disabledDatesText : this.disabledDatesText,
18163             disabledDays : this.disabledDays,
18164             disabledDaysText : this.disabledDaysText,
18165             format : this.useIso ? 'Y-m-d' : this.format,
18166             minText : String.format(this.minText, this.formatDate(this.minValue)),
18167             maxText : String.format(this.maxText, this.formatDate(this.maxValue))
18168         });
18169         this.menu.on(Roo.apply({}, this.menuListeners, {
18170             scope:this
18171         }));
18172         this.menu.picker.setValue(this.getValue() || new Date());
18173         this.menu.show(this.el, "tl-bl?");
18174     },
18175
18176     beforeBlur : function(){
18177         var v = this.parseDate(this.getRawValue());
18178         if(v){
18179             this.setValue(v);
18180         }
18181     },
18182
18183     /*@
18184      * overide
18185      * 
18186      */
18187     isDirty : function() {
18188         if(this.disabled) {
18189             return false;
18190         }
18191         
18192         if(typeof(this.startValue) === 'undefined'){
18193             return false;
18194         }
18195         
18196         return String(this.getValue()) !== String(this.startValue);
18197         
18198     },
18199     // @overide
18200     cleanLeadingSpace : function(e)
18201     {
18202        return;
18203     }
18204     
18205 });/*
18206  * Based on:
18207  * Ext JS Library 1.1.1
18208  * Copyright(c) 2006-2007, Ext JS, LLC.
18209  *
18210  * Originally Released Under LGPL - original licence link has changed is not relivant.
18211  *
18212  * Fork - LGPL
18213  * <script type="text/javascript">
18214  */
18215  
18216 /**
18217  * @class Roo.form.MonthField
18218  * @extends Roo.form.TriggerField
18219  * Provides a date input field with a {@link Roo.DatePicker} dropdown and automatic date validation.
18220 * @constructor
18221 * Create a new MonthField
18222 * @param {Object} config
18223  */
18224 Roo.form.MonthField = function(config){
18225     
18226     Roo.form.MonthField.superclass.constructor.call(this, config);
18227     
18228       this.addEvents({
18229          
18230         /**
18231          * @event select
18232          * Fires when a date is selected
18233              * @param {Roo.form.MonthFieeld} combo This combo box
18234              * @param {Date} date The date selected
18235              */
18236         'select' : true
18237          
18238     });
18239     
18240     
18241     if(typeof this.minValue == "string") {
18242         this.minValue = this.parseDate(this.minValue);
18243     }
18244     if(typeof this.maxValue == "string") {
18245         this.maxValue = this.parseDate(this.maxValue);
18246     }
18247     this.ddMatch = null;
18248     if(this.disabledDates){
18249         var dd = this.disabledDates;
18250         var re = "(?:";
18251         for(var i = 0; i < dd.length; i++){
18252             re += dd[i];
18253             if(i != dd.length-1) {
18254                 re += "|";
18255             }
18256         }
18257         this.ddMatch = new RegExp(re + ")");
18258     }
18259 };
18260
18261 Roo.extend(Roo.form.MonthField, Roo.form.TriggerField,  {
18262     /**
18263      * @cfg {String} format
18264      * The default date format string which can be overriden for localization support.  The format must be
18265      * valid according to {@link Date#parseDate} (defaults to 'm/d/y').
18266      */
18267     format : "M Y",
18268     /**
18269      * @cfg {String} altFormats
18270      * Multiple date formats separated by "|" to try when parsing a user input value and it doesn't match the defined
18271      * format (defaults to 'm/d/Y|m-d-y|m-d-Y|m/d|m-d|d').
18272      */
18273     altFormats : "M Y|m/Y|m-y|m-Y|my|mY",
18274     /**
18275      * @cfg {Array} disabledDays
18276      * An array of days to disable, 0 based. For example, [0, 6] disables Sunday and Saturday (defaults to null).
18277      */
18278     disabledDays : [0,1,2,3,4,5,6],
18279     /**
18280      * @cfg {String} disabledDaysText
18281      * The tooltip to display when the date falls on a disabled day (defaults to 'Disabled')
18282      */
18283     disabledDaysText : "Disabled",
18284     /**
18285      * @cfg {Array} disabledDates
18286      * An array of "dates" to disable, as strings. These strings will be used to build a dynamic regular
18287      * expression so they are very powerful. Some examples:
18288      * <ul>
18289      * <li>["03/08/2003", "09/16/2003"] would disable those exact dates</li>
18290      * <li>["03/08", "09/16"] would disable those days for every year</li>
18291      * <li>["^03/08"] would only match the beginning (useful if you are using short years)</li>
18292      * <li>["03/../2006"] would disable every day in March 2006</li>
18293      * <li>["^03"] would disable every day in every March</li>
18294      * </ul>
18295      * In order to support regular expressions, if you are using a date format that has "." in it, you will have to
18296      * escape the dot when restricting dates. For example: ["03\\.08\\.03"].
18297      */
18298     disabledDates : null,
18299     /**
18300      * @cfg {String} disabledDatesText
18301      * The tooltip text to display when the date falls on a disabled date (defaults to 'Disabled')
18302      */
18303     disabledDatesText : "Disabled",
18304     /**
18305      * @cfg {Date/String} minValue
18306      * The minimum allowed date. Can be either a Javascript date object or a string date in a
18307      * valid format (defaults to null).
18308      */
18309     minValue : null,
18310     /**
18311      * @cfg {Date/String} maxValue
18312      * The maximum allowed date. Can be either a Javascript date object or a string date in a
18313      * valid format (defaults to null).
18314      */
18315     maxValue : null,
18316     /**
18317      * @cfg {String} minText
18318      * The error text to display when the date in the cell is before minValue (defaults to
18319      * 'The date in this field must be after {minValue}').
18320      */
18321     minText : "The date in this field must be equal to or after {0}",
18322     /**
18323      * @cfg {String} maxTextf
18324      * The error text to display when the date in the cell is after maxValue (defaults to
18325      * 'The date in this field must be before {maxValue}').
18326      */
18327     maxText : "The date in this field must be equal to or before {0}",
18328     /**
18329      * @cfg {String} invalidText
18330      * The error text to display when the date in the field is invalid (defaults to
18331      * '{value} is not a valid date - it must be in the format {format}').
18332      */
18333     invalidText : "{0} is not a valid date - it must be in the format {1}",
18334     /**
18335      * @cfg {String} triggerClass
18336      * An additional CSS class used to style the trigger button.  The trigger will always get the
18337      * class 'x-form-trigger' and triggerClass will be <b>appended</b> if specified (defaults to 'x-form-date-trigger'
18338      * which displays a calendar icon).
18339      */
18340     triggerClass : 'x-form-date-trigger',
18341     
18342
18343     /**
18344      * @cfg {Boolean} useIso
18345      * if enabled, then the date field will use a hidden field to store the 
18346      * real value as iso formated date. default (true)
18347      */ 
18348     useIso : true,
18349     /**
18350      * @cfg {String/Object} autoCreate
18351      * A DomHelper element spec, or true for a default element spec (defaults to
18352      * {tag: "input", type: "text", size: "10", autocomplete: "off"})
18353      */ 
18354     // private
18355     defaultAutoCreate : {tag: "input", type: "text", size: "10", autocomplete: "new-password"},
18356     
18357     // private
18358     hiddenField: false,
18359     
18360     hideMonthPicker : false,
18361     
18362     onRender : function(ct, position)
18363     {
18364         Roo.form.MonthField.superclass.onRender.call(this, ct, position);
18365         if (this.useIso) {
18366             this.el.dom.removeAttribute('name'); 
18367             this.hiddenField = this.el.insertSibling({ tag:'input', type:'hidden', name: this.name },
18368                     'before', true);
18369             this.hiddenField.value = this.value ? this.formatDate(this.value, 'Y-m-d') : '';
18370             // prevent input submission
18371             this.hiddenName = this.name;
18372         }
18373             
18374             
18375     },
18376     
18377     // private
18378     validateValue : function(value)
18379     {
18380         value = this.formatDate(value);
18381         if(!Roo.form.MonthField.superclass.validateValue.call(this, value)){
18382             return false;
18383         }
18384         if(value.length < 1){ // if it's blank and textfield didn't flag it then it's valid
18385              return true;
18386         }
18387         var svalue = value;
18388         value = this.parseDate(value);
18389         if(!value){
18390             this.markInvalid(String.format(this.invalidText, svalue, this.format));
18391             return false;
18392         }
18393         var time = value.getTime();
18394         if(this.minValue && time < this.minValue.getTime()){
18395             this.markInvalid(String.format(this.minText, this.formatDate(this.minValue)));
18396             return false;
18397         }
18398         if(this.maxValue && time > this.maxValue.getTime()){
18399             this.markInvalid(String.format(this.maxText, this.formatDate(this.maxValue)));
18400             return false;
18401         }
18402         /*if(this.disabledDays){
18403             var day = value.getDay();
18404             for(var i = 0; i < this.disabledDays.length; i++) {
18405                 if(day === this.disabledDays[i]){
18406                     this.markInvalid(this.disabledDaysText);
18407                     return false;
18408                 }
18409             }
18410         }
18411         */
18412         var fvalue = this.formatDate(value);
18413         /*if(this.ddMatch && this.ddMatch.test(fvalue)){
18414             this.markInvalid(String.format(this.disabledDatesText, fvalue));
18415             return false;
18416         }
18417         */
18418         return true;
18419     },
18420
18421     // private
18422     // Provides logic to override the default TriggerField.validateBlur which just returns true
18423     validateBlur : function(){
18424         return !this.menu || !this.menu.isVisible();
18425     },
18426
18427     /**
18428      * Returns the current date value of the date field.
18429      * @return {Date} The date value
18430      */
18431     getValue : function(){
18432         
18433         
18434         
18435         return  this.hiddenField ?
18436                 this.hiddenField.value :
18437                 this.parseDate(Roo.form.MonthField.superclass.getValue.call(this)) || "";
18438     },
18439
18440     /**
18441      * Sets the value of the date field.  You can pass a date object or any string that can be parsed into a valid
18442      * date, using MonthField.format as the date format, according to the same rules as {@link Date#parseDate}
18443      * (the default format used is "m/d/y").
18444      * <br />Usage:
18445      * <pre><code>
18446 //All of these calls set the same date value (May 4, 2006)
18447
18448 //Pass a date object:
18449 var dt = new Date('5/4/06');
18450 monthField.setValue(dt);
18451
18452 //Pass a date string (default format):
18453 monthField.setValue('5/4/06');
18454
18455 //Pass a date string (custom format):
18456 monthField.format = 'Y-m-d';
18457 monthField.setValue('2006-5-4');
18458 </code></pre>
18459      * @param {String/Date} date The date or valid date string
18460      */
18461     setValue : function(date){
18462         Roo.log('month setValue' + date);
18463         // can only be first of month..
18464         
18465         var val = this.parseDate(date);
18466         
18467         if (this.hiddenField) {
18468             this.hiddenField.value = this.formatDate(this.parseDate(date), 'Y-m-d');
18469         }
18470         Roo.form.MonthField.superclass.setValue.call(this, this.formatDate(this.parseDate(date)));
18471         this.value = this.parseDate(date);
18472     },
18473
18474     // private
18475     parseDate : function(value){
18476         if(!value || value instanceof Date){
18477             value = value ? Date.parseDate(value.format('Y-m') + '-01', 'Y-m-d') : null;
18478             return value;
18479         }
18480         var v = Date.parseDate(value, this.format);
18481         if (!v && this.useIso) {
18482             v = Date.parseDate(value, 'Y-m-d');
18483         }
18484         if (v) {
18485             // 
18486             v = Date.parseDate(v.format('Y-m') +'-01', 'Y-m-d');
18487         }
18488         
18489         
18490         if(!v && this.altFormats){
18491             if(!this.altFormatsArray){
18492                 this.altFormatsArray = this.altFormats.split("|");
18493             }
18494             for(var i = 0, len = this.altFormatsArray.length; i < len && !v; i++){
18495                 v = Date.parseDate(value, this.altFormatsArray[i]);
18496             }
18497         }
18498         return v;
18499     },
18500
18501     // private
18502     formatDate : function(date, fmt){
18503         return (!date || !(date instanceof Date)) ?
18504                date : date.dateFormat(fmt || this.format);
18505     },
18506
18507     // private
18508     menuListeners : {
18509         select: function(m, d){
18510             this.setValue(d);
18511             this.fireEvent('select', this, d);
18512         },
18513         show : function(){ // retain focus styling
18514             this.onFocus();
18515         },
18516         hide : function(){
18517             this.focus.defer(10, this);
18518             var ml = this.menuListeners;
18519             this.menu.un("select", ml.select,  this);
18520             this.menu.un("show", ml.show,  this);
18521             this.menu.un("hide", ml.hide,  this);
18522         }
18523     },
18524     // private
18525     // Implements the default empty TriggerField.onTriggerClick function to display the DatePicker
18526     onTriggerClick : function(){
18527         if(this.disabled){
18528             return;
18529         }
18530         if(this.menu == null){
18531             this.menu = new Roo.menu.DateMenu();
18532            
18533         }
18534         
18535         Roo.apply(this.menu.picker,  {
18536             
18537             showClear: this.allowBlank,
18538             minDate : this.minValue,
18539             maxDate : this.maxValue,
18540             disabledDatesRE : this.ddMatch,
18541             disabledDatesText : this.disabledDatesText,
18542             
18543             format : this.useIso ? 'Y-m-d' : this.format,
18544             minText : String.format(this.minText, this.formatDate(this.minValue)),
18545             maxText : String.format(this.maxText, this.formatDate(this.maxValue))
18546             
18547         });
18548          this.menu.on(Roo.apply({}, this.menuListeners, {
18549             scope:this
18550         }));
18551        
18552         
18553         var m = this.menu;
18554         var p = m.picker;
18555         
18556         // hide month picker get's called when we called by 'before hide';
18557         
18558         var ignorehide = true;
18559         p.hideMonthPicker  = function(disableAnim){
18560             if (ignorehide) {
18561                 return;
18562             }
18563              if(this.monthPicker){
18564                 Roo.log("hideMonthPicker called");
18565                 if(disableAnim === true){
18566                     this.monthPicker.hide();
18567                 }else{
18568                     this.monthPicker.slideOut('t', {duration:.2});
18569                     p.setValue(new Date(m.picker.mpSelYear, m.picker.mpSelMonth, 1));
18570                     p.fireEvent("select", this, this.value);
18571                     m.hide();
18572                 }
18573             }
18574         }
18575         
18576         Roo.log('picker set value');
18577         Roo.log(this.getValue());
18578         p.setValue(this.getValue() ? this.parseDate(this.getValue()) : new Date());
18579         m.show(this.el, 'tl-bl?');
18580         ignorehide  = false;
18581         // this will trigger hideMonthPicker..
18582         
18583         
18584         // hidden the day picker
18585         Roo.select('.x-date-picker table', true).first().dom.style.visibility = "hidden";
18586         
18587         
18588         
18589       
18590         
18591         p.showMonthPicker.defer(100, p);
18592     
18593         
18594        
18595     },
18596
18597     beforeBlur : function(){
18598         var v = this.parseDate(this.getRawValue());
18599         if(v){
18600             this.setValue(v);
18601         }
18602     }
18603
18604     /** @cfg {Boolean} grow @hide */
18605     /** @cfg {Number} growMin @hide */
18606     /** @cfg {Number} growMax @hide */
18607     /**
18608      * @hide
18609      * @method autoSize
18610      */
18611 });/*
18612  * Based on:
18613  * Ext JS Library 1.1.1
18614  * Copyright(c) 2006-2007, Ext JS, LLC.
18615  *
18616  * Originally Released Under LGPL - original licence link has changed is not relivant.
18617  *
18618  * Fork - LGPL
18619  * <script type="text/javascript">
18620  */
18621  
18622
18623 /**
18624  * @class Roo.form.ComboBox
18625  * @extends Roo.form.TriggerField
18626  * A combobox control with support for autocomplete, remote-loading, paging and many other features.
18627  * @constructor
18628  * Create a new ComboBox.
18629  * @param {Object} config Configuration options
18630  */
18631 Roo.form.ComboBox = function(config){
18632     Roo.form.ComboBox.superclass.constructor.call(this, config);
18633     this.addEvents({
18634         /**
18635          * @event expand
18636          * Fires when the dropdown list is expanded
18637              * @param {Roo.form.ComboBox} combo This combo box
18638              */
18639         'expand' : true,
18640         /**
18641          * @event collapse
18642          * Fires when the dropdown list is collapsed
18643              * @param {Roo.form.ComboBox} combo This combo box
18644              */
18645         'collapse' : true,
18646         /**
18647          * @event beforeselect
18648          * Fires before a list item is selected. Return false to cancel the selection.
18649              * @param {Roo.form.ComboBox} combo This combo box
18650              * @param {Roo.data.Record} record The data record returned from the underlying store
18651              * @param {Number} index The index of the selected item in the dropdown list
18652              */
18653         'beforeselect' : true,
18654         /**
18655          * @event select
18656          * Fires when a list item is selected
18657              * @param {Roo.form.ComboBox} combo This combo box
18658              * @param {Roo.data.Record} record The data record returned from the underlying store (or false on clear)
18659              * @param {Number} index The index of the selected item in the dropdown list
18660              */
18661         'select' : true,
18662         /**
18663          * @event beforequery
18664          * Fires before all queries are processed. Return false to cancel the query or set cancel to true.
18665          * The event object passed has these properties:
18666              * @param {Roo.form.ComboBox} combo This combo box
18667              * @param {String} query The query
18668              * @param {Boolean} forceAll true to force "all" query
18669              * @param {Boolean} cancel true to cancel the query
18670              * @param {Object} e The query event object
18671              */
18672         'beforequery': true,
18673          /**
18674          * @event add
18675          * Fires when the 'add' icon is pressed (add a listener to enable add button)
18676              * @param {Roo.form.ComboBox} combo This combo box
18677              */
18678         'add' : true,
18679         /**
18680          * @event edit
18681          * Fires when the 'edit' icon is pressed (add a listener to enable add button)
18682              * @param {Roo.form.ComboBox} combo This combo box
18683              * @param {Roo.data.Record|false} record The data record returned from the underlying store (or false on nothing selected)
18684              */
18685         'edit' : true
18686         
18687         
18688     });
18689     if(this.transform){
18690         this.allowDomMove = false;
18691         var s = Roo.getDom(this.transform);
18692         if(!this.hiddenName){
18693             this.hiddenName = s.name;
18694         }
18695         if(!this.store){
18696             this.mode = 'local';
18697             var d = [], opts = s.options;
18698             for(var i = 0, len = opts.length;i < len; i++){
18699                 var o = opts[i];
18700                 var value = (Roo.isIE ? o.getAttributeNode('value').specified : o.hasAttribute('value')) ? o.value : o.text;
18701                 if(o.selected) {
18702                     this.value = value;
18703                 }
18704                 d.push([value, o.text]);
18705             }
18706             this.store = new Roo.data.SimpleStore({
18707                 'id': 0,
18708                 fields: ['value', 'text'],
18709                 data : d
18710             });
18711             this.valueField = 'value';
18712             this.displayField = 'text';
18713         }
18714         s.name = Roo.id(); // wipe out the name in case somewhere else they have a reference
18715         if(!this.lazyRender){
18716             this.target = true;
18717             this.el = Roo.DomHelper.insertBefore(s, this.autoCreate || this.defaultAutoCreate);
18718             s.parentNode.removeChild(s); // remove it
18719             this.render(this.el.parentNode);
18720         }else{
18721             s.parentNode.removeChild(s); // remove it
18722         }
18723
18724     }
18725     if (this.store) {
18726         this.store = Roo.factory(this.store, Roo.data);
18727     }
18728     
18729     this.selectedIndex = -1;
18730     if(this.mode == 'local'){
18731         if(config.queryDelay === undefined){
18732             this.queryDelay = 10;
18733         }
18734         if(config.minChars === undefined){
18735             this.minChars = 0;
18736         }
18737     }
18738 };
18739
18740 Roo.extend(Roo.form.ComboBox, Roo.form.TriggerField, {
18741     /**
18742      * @cfg {String/HTMLElement/Element} transform The id, DOM node or element of an existing select to convert to a ComboBox
18743      */
18744     /**
18745      * @cfg {Boolean} lazyRender True to prevent the ComboBox from rendering until requested (should always be used when
18746      * rendering into an Roo.Editor, defaults to false)
18747      */
18748     /**
18749      * @cfg {Boolean/Object} autoCreate A DomHelper element spec, or true for a default element spec (defaults to:
18750      * {tag: "input", type: "text", size: "24", autocomplete: "off"})
18751      */
18752     /**
18753      * @cfg {Roo.data.Store} store The data store to which this combo is bound (defaults to undefined)
18754      */
18755     /**
18756      * @cfg {String} title If supplied, a header element is created containing this text and added into the top of
18757      * the dropdown list (defaults to undefined, with no header element)
18758      */
18759
18760      /**
18761      * @cfg {String/Roo.Template} tpl The template to use to render the output
18762      */
18763      
18764     // private
18765     defaultAutoCreate : {tag: "input", type: "text", size: "24", autocomplete: "off"},
18766     /**
18767      * @cfg {Number} listWidth The width in pixels of the dropdown list (defaults to the width of the ComboBox field)
18768      */
18769     listWidth: undefined,
18770     /**
18771      * @cfg {String} displayField The underlying data field name to bind to this CombBox (defaults to undefined if
18772      * mode = 'remote' or 'text' if mode = 'local')
18773      */
18774     displayField: undefined,
18775     /**
18776      * @cfg {String} valueField The underlying data value name to bind to this CombBox (defaults to undefined if
18777      * mode = 'remote' or 'value' if mode = 'local'). 
18778      * Note: use of a valueField requires the user make a selection
18779      * in order for a value to be mapped.
18780      */
18781     valueField: undefined,
18782     
18783     
18784     /**
18785      * @cfg {String} hiddenName If specified, a hidden form field with this name is dynamically generated to store the
18786      * field's data value (defaults to the underlying DOM element's name)
18787      */
18788     hiddenName: undefined,
18789     /**
18790      * @cfg {String} listClass CSS class to apply to the dropdown list element (defaults to '')
18791      */
18792     listClass: '',
18793     /**
18794      * @cfg {String} selectedClass CSS class to apply to the selected item in the dropdown list (defaults to 'x-combo-selected')
18795      */
18796     selectedClass: 'x-combo-selected',
18797     /**
18798      * @cfg {String} triggerClass An additional CSS class used to style the trigger button.  The trigger will always get the
18799      * class 'x-form-trigger' and triggerClass will be <b>appended</b> if specified (defaults to 'x-form-arrow-trigger'
18800      * which displays a downward arrow icon).
18801      */
18802     triggerClass : 'x-form-arrow-trigger',
18803     /**
18804      * @cfg {Boolean/String} shadow True or "sides" for the default effect, "frame" for 4-way shadow, and "drop" for bottom-right
18805      */
18806     shadow:'sides',
18807     /**
18808      * @cfg {String} listAlign A valid anchor position value. See {@link Roo.Element#alignTo} for details on supported
18809      * anchor positions (defaults to 'tl-bl')
18810      */
18811     listAlign: 'tl-bl?',
18812     /**
18813      * @cfg {Number} maxHeight The maximum height in pixels of the dropdown list before scrollbars are shown (defaults to 300)
18814      */
18815     maxHeight: 300,
18816     /**
18817      * @cfg {String} triggerAction The action to execute when the trigger field is activated.  Use 'all' to run the
18818      * query specified by the allQuery config option (defaults to 'query')
18819      */
18820     triggerAction: 'query',
18821     /**
18822      * @cfg {Number} minChars The minimum number of characters the user must type before autocomplete and typeahead activate
18823      * (defaults to 4, does not apply if editable = false)
18824      */
18825     minChars : 4,
18826     /**
18827      * @cfg {Boolean} typeAhead True to populate and autoselect the remainder of the text being typed after a configurable
18828      * delay (typeAheadDelay) if it matches a known value (defaults to false)
18829      */
18830     typeAhead: false,
18831     /**
18832      * @cfg {Number} queryDelay The length of time in milliseconds to delay between the start of typing and sending the
18833      * query to filter the dropdown list (defaults to 500 if mode = 'remote' or 10 if mode = 'local')
18834      */
18835     queryDelay: 500,
18836     /**
18837      * @cfg {Number} pageSize If greater than 0, a paging toolbar is displayed in the footer of the dropdown list and the
18838      * filter queries will execute with page start and limit parameters.  Only applies when mode = 'remote' (defaults to 0)
18839      */
18840     pageSize: 0,
18841     /**
18842      * @cfg {Boolean} selectOnFocus True to select any existing text in the field immediately on focus.  Only applies
18843      * when editable = true (defaults to false)
18844      */
18845     selectOnFocus:false,
18846     /**
18847      * @cfg {String} queryParam Name of the query as it will be passed on the querystring (defaults to 'query')
18848      */
18849     queryParam: 'query',
18850     /**
18851      * @cfg {String} loadingText The text to display in the dropdown list while data is loading.  Only applies
18852      * when mode = 'remote' (defaults to 'Loading...')
18853      */
18854     loadingText: 'Loading...',
18855     /**
18856      * @cfg {Boolean} resizable True to add a resize handle to the bottom of the dropdown list (defaults to false)
18857      */
18858     resizable: false,
18859     /**
18860      * @cfg {Number} handleHeight The height in pixels of the dropdown list resize handle if resizable = true (defaults to 8)
18861      */
18862     handleHeight : 8,
18863     /**
18864      * @cfg {Boolean} editable False to prevent the user from typing text directly into the field, just like a
18865      * traditional select (defaults to true)
18866      */
18867     editable: true,
18868     /**
18869      * @cfg {String} allQuery The text query to send to the server to return all records for the list with no filtering (defaults to '')
18870      */
18871     allQuery: '',
18872     /**
18873      * @cfg {String} mode Set to 'local' if the ComboBox loads local data (defaults to 'remote' which loads from the server)
18874      */
18875     mode: 'remote',
18876     /**
18877      * @cfg {Number} minListWidth The minimum width of the dropdown list in pixels (defaults to 70, will be ignored if
18878      * listWidth has a higher value)
18879      */
18880     minListWidth : 70,
18881     /**
18882      * @cfg {Boolean} forceSelection True to restrict the selected value to one of the values in the list, false to
18883      * allow the user to set arbitrary text into the field (defaults to false)
18884      */
18885     forceSelection:false,
18886     /**
18887      * @cfg {Number} typeAheadDelay The length of time in milliseconds to wait until the typeahead text is displayed
18888      * if typeAhead = true (defaults to 250)
18889      */
18890     typeAheadDelay : 250,
18891     /**
18892      * @cfg {String} valueNotFoundText When using a name/value combo, if the value passed to setValue is not found in
18893      * the store, valueNotFoundText will be displayed as the field text if defined (defaults to undefined)
18894      */
18895     valueNotFoundText : undefined,
18896     /**
18897      * @cfg {Boolean} blockFocus Prevents all focus calls, so it can work with things like HTML edtor bar
18898      */
18899     blockFocus : false,
18900     
18901     /**
18902      * @cfg {Boolean} disableClear Disable showing of clear button.
18903      */
18904     disableClear : false,
18905     /**
18906      * @cfg {Boolean} alwaysQuery  Disable caching of results, and always send query
18907      */
18908     alwaysQuery : false,
18909     
18910     //private
18911     addicon : false,
18912     editicon: false,
18913     
18914     // element that contains real text value.. (when hidden is used..)
18915      
18916     // private
18917     onRender : function(ct, position){
18918         Roo.form.ComboBox.superclass.onRender.call(this, ct, position);
18919         if(this.hiddenName){
18920             this.hiddenField = this.el.insertSibling({tag:'input', type:'hidden', name: this.hiddenName, id:  (this.hiddenId||this.hiddenName)},
18921                     'before', true);
18922             this.hiddenField.value =
18923                 this.hiddenValue !== undefined ? this.hiddenValue :
18924                 this.value !== undefined ? this.value : '';
18925
18926             // prevent input submission
18927             this.el.dom.removeAttribute('name');
18928              
18929              
18930         }
18931         if(Roo.isGecko){
18932             this.el.dom.setAttribute('autocomplete', 'off');
18933         }
18934
18935         var cls = 'x-combo-list';
18936
18937         this.list = new Roo.Layer({
18938             shadow: this.shadow, cls: [cls, this.listClass].join(' '), constrain:false
18939         });
18940
18941         var lw = this.listWidth || Math.max(this.wrap.getWidth(), this.minListWidth);
18942         this.list.setWidth(lw);
18943         this.list.swallowEvent('mousewheel');
18944         this.assetHeight = 0;
18945
18946         if(this.title){
18947             this.header = this.list.createChild({cls:cls+'-hd', html: this.title});
18948             this.assetHeight += this.header.getHeight();
18949         }
18950
18951         this.innerList = this.list.createChild({cls:cls+'-inner'});
18952         this.innerList.on('mouseover', this.onViewOver, this);
18953         this.innerList.on('mousemove', this.onViewMove, this);
18954         this.innerList.setWidth(lw - this.list.getFrameWidth('lr'));
18955         
18956         if(this.allowBlank && !this.pageSize && !this.disableClear){
18957             this.footer = this.list.createChild({cls:cls+'-ft'});
18958             this.pageTb = new Roo.Toolbar(this.footer);
18959            
18960         }
18961         if(this.pageSize){
18962             this.footer = this.list.createChild({cls:cls+'-ft'});
18963             this.pageTb = new Roo.PagingToolbar(this.footer, this.store,
18964                     {pageSize: this.pageSize});
18965             
18966         }
18967         
18968         if (this.pageTb && this.allowBlank && !this.disableClear) {
18969             var _this = this;
18970             this.pageTb.add(new Roo.Toolbar.Fill(), {
18971                 cls: 'x-btn-icon x-btn-clear',
18972                 text: '&#160;',
18973                 handler: function()
18974                 {
18975                     _this.collapse();
18976                     _this.clearValue();
18977                     _this.onSelect(false, -1);
18978                 }
18979             });
18980         }
18981         if (this.footer) {
18982             this.assetHeight += this.footer.getHeight();
18983         }
18984         
18985
18986         if(!this.tpl){
18987             this.tpl = '<div class="'+cls+'-item">{' + this.displayField + '}</div>';
18988         }
18989
18990         this.view = new Roo.View(this.innerList, this.tpl, {
18991             singleSelect:true, store: this.store, selectedClass: this.selectedClass
18992         });
18993
18994         this.view.on('click', this.onViewClick, this);
18995
18996         this.store.on('beforeload', this.onBeforeLoad, this);
18997         this.store.on('load', this.onLoad, this);
18998         this.store.on('loadexception', this.onLoadException, this);
18999
19000         if(this.resizable){
19001             this.resizer = new Roo.Resizable(this.list,  {
19002                pinned:true, handles:'se'
19003             });
19004             this.resizer.on('resize', function(r, w, h){
19005                 this.maxHeight = h-this.handleHeight-this.list.getFrameWidth('tb')-this.assetHeight;
19006                 this.listWidth = w;
19007                 this.innerList.setWidth(w - this.list.getFrameWidth('lr'));
19008                 this.restrictHeight();
19009             }, this);
19010             this[this.pageSize?'footer':'innerList'].setStyle('margin-bottom', this.handleHeight+'px');
19011         }
19012         if(!this.editable){
19013             this.editable = true;
19014             this.setEditable(false);
19015         }  
19016         
19017         
19018         if (typeof(this.events.add.listeners) != 'undefined') {
19019             
19020             this.addicon = this.wrap.createChild(
19021                 {tag: 'img', src: Roo.BLANK_IMAGE_URL, cls: 'x-form-combo-add' });  
19022        
19023             this.addicon.on('click', function(e) {
19024                 this.fireEvent('add', this);
19025             }, this);
19026         }
19027         if (typeof(this.events.edit.listeners) != 'undefined') {
19028             
19029             this.editicon = this.wrap.createChild(
19030                 {tag: 'img', src: Roo.BLANK_IMAGE_URL, cls: 'x-form-combo-edit' });  
19031             if (this.addicon) {
19032                 this.editicon.setStyle('margin-left', '40px');
19033             }
19034             this.editicon.on('click', function(e) {
19035                 
19036                 // we fire even  if inothing is selected..
19037                 this.fireEvent('edit', this, this.lastData );
19038                 
19039             }, this);
19040         }
19041         
19042         
19043         
19044     },
19045
19046     // private
19047     initEvents : function(){
19048         Roo.form.ComboBox.superclass.initEvents.call(this);
19049
19050         this.keyNav = new Roo.KeyNav(this.el, {
19051             "up" : function(e){
19052                 this.inKeyMode = true;
19053                 this.selectPrev();
19054             },
19055
19056             "down" : function(e){
19057                 if(!this.isExpanded()){
19058                     this.onTriggerClick();
19059                 }else{
19060                     this.inKeyMode = true;
19061                     this.selectNext();
19062                 }
19063             },
19064
19065             "enter" : function(e){
19066                 this.onViewClick();
19067                 //return true;
19068             },
19069
19070             "esc" : function(e){
19071                 this.collapse();
19072             },
19073
19074             "tab" : function(e){
19075                 this.onViewClick(false);
19076                 this.fireEvent("specialkey", this, e);
19077                 return true;
19078             },
19079
19080             scope : this,
19081
19082             doRelay : function(foo, bar, hname){
19083                 if(hname == 'down' || this.scope.isExpanded()){
19084                    return Roo.KeyNav.prototype.doRelay.apply(this, arguments);
19085                 }
19086                 return true;
19087             },
19088
19089             forceKeyDown: true
19090         });
19091         this.queryDelay = Math.max(this.queryDelay || 10,
19092                 this.mode == 'local' ? 10 : 250);
19093         this.dqTask = new Roo.util.DelayedTask(this.initQuery, this);
19094         if(this.typeAhead){
19095             this.taTask = new Roo.util.DelayedTask(this.onTypeAhead, this);
19096         }
19097         if(this.editable !== false){
19098             this.el.on("keyup", this.onKeyUp, this);
19099         }
19100         if(this.forceSelection){
19101             this.on('blur', this.doForce, this);
19102         }
19103     },
19104
19105     onDestroy : function(){
19106         if(this.view){
19107             this.view.setStore(null);
19108             this.view.el.removeAllListeners();
19109             this.view.el.remove();
19110             this.view.purgeListeners();
19111         }
19112         if(this.list){
19113             this.list.destroy();
19114         }
19115         if(this.store){
19116             this.store.un('beforeload', this.onBeforeLoad, this);
19117             this.store.un('load', this.onLoad, this);
19118             this.store.un('loadexception', this.onLoadException, this);
19119         }
19120         Roo.form.ComboBox.superclass.onDestroy.call(this);
19121     },
19122
19123     // private
19124     fireKey : function(e){
19125         if(e.isNavKeyPress() && !this.list.isVisible()){
19126             this.fireEvent("specialkey", this, e);
19127         }
19128     },
19129
19130     // private
19131     onResize: function(w, h){
19132         Roo.form.ComboBox.superclass.onResize.apply(this, arguments);
19133         
19134         if(typeof w != 'number'){
19135             // we do not handle it!?!?
19136             return;
19137         }
19138         var tw = this.trigger.getWidth();
19139         tw += this.addicon ? this.addicon.getWidth() : 0;
19140         tw += this.editicon ? this.editicon.getWidth() : 0;
19141         var x = w - tw;
19142         this.el.setWidth( this.adjustWidth('input', x));
19143             
19144         this.trigger.setStyle('left', x+'px');
19145         
19146         if(this.list && this.listWidth === undefined){
19147             var lw = Math.max(x + this.trigger.getWidth(), this.minListWidth);
19148             this.list.setWidth(lw);
19149             this.innerList.setWidth(lw - this.list.getFrameWidth('lr'));
19150         }
19151         
19152     
19153         
19154     },
19155
19156     /**
19157      * Allow or prevent the user from directly editing the field text.  If false is passed,
19158      * the user will only be able to select from the items defined in the dropdown list.  This method
19159      * is the runtime equivalent of setting the 'editable' config option at config time.
19160      * @param {Boolean} value True to allow the user to directly edit the field text
19161      */
19162     setEditable : function(value){
19163         if(value == this.editable){
19164             return;
19165         }
19166         this.editable = value;
19167         if(!value){
19168             this.el.dom.setAttribute('readOnly', true);
19169             this.el.on('mousedown', this.onTriggerClick,  this);
19170             this.el.addClass('x-combo-noedit');
19171         }else{
19172             this.el.dom.setAttribute('readOnly', false);
19173             this.el.un('mousedown', this.onTriggerClick,  this);
19174             this.el.removeClass('x-combo-noedit');
19175         }
19176     },
19177
19178     // private
19179     onBeforeLoad : function(){
19180         if(!this.hasFocus){
19181             return;
19182         }
19183         this.innerList.update(this.loadingText ?
19184                '<div class="loading-indicator">'+this.loadingText+'</div>' : '');
19185         this.restrictHeight();
19186         this.selectedIndex = -1;
19187     },
19188
19189     // private
19190     onLoad : function(){
19191         if(!this.hasFocus){
19192             return;
19193         }
19194         if(this.store.getCount() > 0){
19195             this.expand();
19196             this.restrictHeight();
19197             if(this.lastQuery == this.allQuery){
19198                 if(this.editable){
19199                     this.el.dom.select();
19200                 }
19201                 if(!this.selectByValue(this.value, true)){
19202                     this.select(0, true);
19203                 }
19204             }else{
19205                 this.selectNext();
19206                 if(this.typeAhead && this.lastKey != Roo.EventObject.BACKSPACE && this.lastKey != Roo.EventObject.DELETE){
19207                     this.taTask.delay(this.typeAheadDelay);
19208                 }
19209             }
19210         }else{
19211             this.onEmptyResults();
19212         }
19213         //this.el.focus();
19214     },
19215     // private
19216     onLoadException : function()
19217     {
19218         this.collapse();
19219         Roo.log(this.store.reader.jsonData);
19220         if (this.store && typeof(this.store.reader.jsonData.errorMsg) != 'undefined') {
19221             Roo.MessageBox.alert("Error loading",this.store.reader.jsonData.errorMsg);
19222         }
19223         
19224         
19225     },
19226     // private
19227     onTypeAhead : function(){
19228         if(this.store.getCount() > 0){
19229             var r = this.store.getAt(0);
19230             var newValue = r.data[this.displayField];
19231             var len = newValue.length;
19232             var selStart = this.getRawValue().length;
19233             if(selStart != len){
19234                 this.setRawValue(newValue);
19235                 this.selectText(selStart, newValue.length);
19236             }
19237         }
19238     },
19239
19240     // private
19241     onSelect : function(record, index){
19242         if(this.fireEvent('beforeselect', this, record, index) !== false){
19243             this.setFromData(index > -1 ? record.data : false);
19244             this.collapse();
19245             this.fireEvent('select', this, record, index);
19246         }
19247     },
19248
19249     /**
19250      * Returns the currently selected field value or empty string if no value is set.
19251      * @return {String} value The selected value
19252      */
19253     getValue : function(){
19254         if(this.valueField){
19255             return typeof this.value != 'undefined' ? this.value : '';
19256         }
19257         return Roo.form.ComboBox.superclass.getValue.call(this);
19258     },
19259
19260     /**
19261      * Clears any text/value currently set in the field
19262      */
19263     clearValue : function(){
19264         if(this.hiddenField){
19265             this.hiddenField.value = '';
19266         }
19267         this.value = '';
19268         this.setRawValue('');
19269         this.lastSelectionText = '';
19270         
19271     },
19272
19273     /**
19274      * Sets the specified value into the field.  If the value finds a match, the corresponding record text
19275      * will be displayed in the field.  If the value does not match the data value of an existing item,
19276      * and the valueNotFoundText config option is defined, it will be displayed as the default field text.
19277      * Otherwise the field will be blank (although the value will still be set).
19278      * @param {String} value The value to match
19279      */
19280     setValue : function(v){
19281         var text = v;
19282         if(this.valueField){
19283             var r = this.findRecord(this.valueField, v);
19284             if(r){
19285                 text = r.data[this.displayField];
19286             }else if(this.valueNotFoundText !== undefined){
19287                 text = this.valueNotFoundText;
19288             }
19289         }
19290         this.lastSelectionText = text;
19291         if(this.hiddenField){
19292             this.hiddenField.value = v;
19293         }
19294         Roo.form.ComboBox.superclass.setValue.call(this, text);
19295         this.value = v;
19296     },
19297     /**
19298      * @property {Object} the last set data for the element
19299      */
19300     
19301     lastData : false,
19302     /**
19303      * Sets the value of the field based on a object which is related to the record format for the store.
19304      * @param {Object} value the value to set as. or false on reset?
19305      */
19306     setFromData : function(o){
19307         var dv = ''; // display value
19308         var vv = ''; // value value..
19309         this.lastData = o;
19310         if (this.displayField) {
19311             dv = !o || typeof(o[this.displayField]) == 'undefined' ? '' : o[this.displayField];
19312         } else {
19313             // this is an error condition!!!
19314             Roo.log('no  displayField value set for '+ (this.name ? this.name : this.id));
19315         }
19316         
19317         if(this.valueField){
19318             vv = !o || typeof(o[this.valueField]) == 'undefined' ? dv : o[this.valueField];
19319         }
19320         if(this.hiddenField){
19321             this.hiddenField.value = vv;
19322             
19323             this.lastSelectionText = dv;
19324             Roo.form.ComboBox.superclass.setValue.call(this, dv);
19325             this.value = vv;
19326             return;
19327         }
19328         // no hidden field.. - we store the value in 'value', but still display
19329         // display field!!!!
19330         this.lastSelectionText = dv;
19331         Roo.form.ComboBox.superclass.setValue.call(this, dv);
19332         this.value = vv;
19333         
19334         
19335     },
19336     // private
19337     reset : function(){
19338         // overridden so that last data is reset..
19339         this.setValue(this.resetValue);
19340         this.originalValue = this.getValue();
19341         this.clearInvalid();
19342         this.lastData = false;
19343         if (this.view) {
19344             this.view.clearSelections();
19345         }
19346     },
19347     // private
19348     findRecord : function(prop, value){
19349         var record;
19350         if(this.store.getCount() > 0){
19351             this.store.each(function(r){
19352                 if(r.data[prop] == value){
19353                     record = r;
19354                     return false;
19355                 }
19356                 return true;
19357             });
19358         }
19359         return record;
19360     },
19361     
19362     getName: function()
19363     {
19364         // returns hidden if it's set..
19365         if (!this.rendered) {return ''};
19366         return !this.hiddenName && this.el.dom.name  ? this.el.dom.name : (this.hiddenName || '');
19367         
19368     },
19369     // private
19370     onViewMove : function(e, t){
19371         this.inKeyMode = false;
19372     },
19373
19374     // private
19375     onViewOver : function(e, t){
19376         if(this.inKeyMode){ // prevent key nav and mouse over conflicts
19377             return;
19378         }
19379         var item = this.view.findItemFromChild(t);
19380         if(item){
19381             var index = this.view.indexOf(item);
19382             this.select(index, false);
19383         }
19384     },
19385
19386     // private
19387     onViewClick : function(doFocus)
19388     {
19389         var index = this.view.getSelectedIndexes()[0];
19390         var r = this.store.getAt(index);
19391         if(r){
19392             this.onSelect(r, index);
19393         }
19394         if(doFocus !== false && !this.blockFocus){
19395             this.el.focus();
19396         }
19397     },
19398
19399     // private
19400     restrictHeight : function(){
19401         this.innerList.dom.style.height = '';
19402         var inner = this.innerList.dom;
19403         var h = Math.max(inner.clientHeight, inner.offsetHeight, inner.scrollHeight);
19404         this.innerList.setHeight(h < this.maxHeight ? 'auto' : this.maxHeight);
19405         this.list.beginUpdate();
19406         this.list.setHeight(this.innerList.getHeight()+this.list.getFrameWidth('tb')+(this.resizable?this.handleHeight:0)+this.assetHeight);
19407         this.list.alignTo(this.el, this.listAlign);
19408         this.list.endUpdate();
19409     },
19410
19411     // private
19412     onEmptyResults : function(){
19413         this.collapse();
19414     },
19415
19416     /**
19417      * Returns true if the dropdown list is expanded, else false.
19418      */
19419     isExpanded : function(){
19420         return this.list.isVisible();
19421     },
19422
19423     /**
19424      * Select an item in the dropdown list by its data value. This function does NOT cause the select event to fire.
19425      * The store must be loaded and the list expanded for this function to work, otherwise use setValue.
19426      * @param {String} value The data value of the item to select
19427      * @param {Boolean} scrollIntoView False to prevent the dropdown list from autoscrolling to display the
19428      * selected item if it is not currently in view (defaults to true)
19429      * @return {Boolean} True if the value matched an item in the list, else false
19430      */
19431     selectByValue : function(v, scrollIntoView){
19432         if(v !== undefined && v !== null){
19433             var r = this.findRecord(this.valueField || this.displayField, v);
19434             if(r){
19435                 this.select(this.store.indexOf(r), scrollIntoView);
19436                 return true;
19437             }
19438         }
19439         return false;
19440     },
19441
19442     /**
19443      * Select an item in the dropdown list by its numeric index in the list. This function does NOT cause the select event to fire.
19444      * The store must be loaded and the list expanded for this function to work, otherwise use setValue.
19445      * @param {Number} index The zero-based index of the list item to select
19446      * @param {Boolean} scrollIntoView False to prevent the dropdown list from autoscrolling to display the
19447      * selected item if it is not currently in view (defaults to true)
19448      */
19449     select : function(index, scrollIntoView){
19450         this.selectedIndex = index;
19451         this.view.select(index);
19452         if(scrollIntoView !== false){
19453             var el = this.view.getNode(index);
19454             if(el){
19455                 this.innerList.scrollChildIntoView(el, false);
19456             }
19457         }
19458     },
19459
19460     // private
19461     selectNext : function(){
19462         var ct = this.store.getCount();
19463         if(ct > 0){
19464             if(this.selectedIndex == -1){
19465                 this.select(0);
19466             }else if(this.selectedIndex < ct-1){
19467                 this.select(this.selectedIndex+1);
19468             }
19469         }
19470     },
19471
19472     // private
19473     selectPrev : function(){
19474         var ct = this.store.getCount();
19475         if(ct > 0){
19476             if(this.selectedIndex == -1){
19477                 this.select(0);
19478             }else if(this.selectedIndex != 0){
19479                 this.select(this.selectedIndex-1);
19480             }
19481         }
19482     },
19483
19484     // private
19485     onKeyUp : function(e){
19486         if(this.editable !== false && !e.isSpecialKey()){
19487             this.lastKey = e.getKey();
19488             this.dqTask.delay(this.queryDelay);
19489         }
19490     },
19491
19492     // private
19493     validateBlur : function(){
19494         return !this.list || !this.list.isVisible();   
19495     },
19496
19497     // private
19498     initQuery : function(){
19499         this.doQuery(this.getRawValue());
19500     },
19501
19502     // private
19503     doForce : function(){
19504         if(this.el.dom.value.length > 0){
19505             this.el.dom.value =
19506                 this.lastSelectionText === undefined ? '' : this.lastSelectionText;
19507              
19508         }
19509     },
19510
19511     /**
19512      * Execute a query to filter the dropdown list.  Fires the beforequery event prior to performing the
19513      * query allowing the query action to be canceled if needed.
19514      * @param {String} query The SQL query to execute
19515      * @param {Boolean} forceAll True to force the query to execute even if there are currently fewer characters
19516      * in the field than the minimum specified by the minChars config option.  It also clears any filter previously
19517      * saved in the current store (defaults to false)
19518      */
19519     doQuery : function(q, forceAll){
19520         if(q === undefined || q === null){
19521             q = '';
19522         }
19523         var qe = {
19524             query: q,
19525             forceAll: forceAll,
19526             combo: this,
19527             cancel:false
19528         };
19529         if(this.fireEvent('beforequery', qe)===false || qe.cancel){
19530             return false;
19531         }
19532         q = qe.query;
19533         forceAll = qe.forceAll;
19534         if(forceAll === true || (q.length >= this.minChars)){
19535             if(this.lastQuery != q || this.alwaysQuery){
19536                 this.lastQuery = q;
19537                 if(this.mode == 'local'){
19538                     this.selectedIndex = -1;
19539                     if(forceAll){
19540                         this.store.clearFilter();
19541                     }else{
19542                         this.store.filter(this.displayField, q);
19543                     }
19544                     this.onLoad();
19545                 }else{
19546                     this.store.baseParams[this.queryParam] = q;
19547                     this.store.load({
19548                         params: this.getParams(q)
19549                     });
19550                     this.expand();
19551                 }
19552             }else{
19553                 this.selectedIndex = -1;
19554                 this.onLoad();   
19555             }
19556         }
19557     },
19558
19559     // private
19560     getParams : function(q){
19561         var p = {};
19562         //p[this.queryParam] = q;
19563         if(this.pageSize){
19564             p.start = 0;
19565             p.limit = this.pageSize;
19566         }
19567         return p;
19568     },
19569
19570     /**
19571      * Hides the dropdown list if it is currently expanded. Fires the 'collapse' event on completion.
19572      */
19573     collapse : function(){
19574         if(!this.isExpanded()){
19575             return;
19576         }
19577         this.list.hide();
19578         Roo.get(document).un('mousedown', this.collapseIf, this);
19579         Roo.get(document).un('mousewheel', this.collapseIf, this);
19580         if (!this.editable) {
19581             Roo.get(document).un('keydown', this.listKeyPress, this);
19582         }
19583         this.fireEvent('collapse', this);
19584     },
19585
19586     // private
19587     collapseIf : function(e){
19588         if(!e.within(this.wrap) && !e.within(this.list)){
19589             this.collapse();
19590         }
19591     },
19592
19593     /**
19594      * Expands the dropdown list if it is currently hidden. Fires the 'expand' event on completion.
19595      */
19596     expand : function(){
19597         if(this.isExpanded() || !this.hasFocus){
19598             return;
19599         }
19600         this.list.alignTo(this.el, this.listAlign);
19601         this.list.show();
19602         Roo.get(document).on('mousedown', this.collapseIf, this);
19603         Roo.get(document).on('mousewheel', this.collapseIf, this);
19604         if (!this.editable) {
19605             Roo.get(document).on('keydown', this.listKeyPress, this);
19606         }
19607         
19608         this.fireEvent('expand', this);
19609     },
19610
19611     // private
19612     // Implements the default empty TriggerField.onTriggerClick function
19613     onTriggerClick : function(){
19614         if(this.disabled){
19615             return;
19616         }
19617         if(this.isExpanded()){
19618             this.collapse();
19619             if (!this.blockFocus) {
19620                 this.el.focus();
19621             }
19622             
19623         }else {
19624             this.hasFocus = true;
19625             if(this.triggerAction == 'all') {
19626                 this.doQuery(this.allQuery, true);
19627             } else {
19628                 this.doQuery(this.getRawValue());
19629             }
19630             if (!this.blockFocus) {
19631                 this.el.focus();
19632             }
19633         }
19634     },
19635     listKeyPress : function(e)
19636     {
19637         //Roo.log('listkeypress');
19638         // scroll to first matching element based on key pres..
19639         if (e.isSpecialKey()) {
19640             return false;
19641         }
19642         var k = String.fromCharCode(e.getKey()).toUpperCase();
19643         //Roo.log(k);
19644         var match  = false;
19645         var csel = this.view.getSelectedNodes();
19646         var cselitem = false;
19647         if (csel.length) {
19648             var ix = this.view.indexOf(csel[0]);
19649             cselitem  = this.store.getAt(ix);
19650             if (!cselitem.get(this.displayField) || cselitem.get(this.displayField).substring(0,1).toUpperCase() != k) {
19651                 cselitem = false;
19652             }
19653             
19654         }
19655         
19656         this.store.each(function(v) { 
19657             if (cselitem) {
19658                 // start at existing selection.
19659                 if (cselitem.id == v.id) {
19660                     cselitem = false;
19661                 }
19662                 return;
19663             }
19664                 
19665             if (v.get(this.displayField) && v.get(this.displayField).substring(0,1).toUpperCase() == k) {
19666                 match = this.store.indexOf(v);
19667                 return false;
19668             }
19669         }, this);
19670         
19671         if (match === false) {
19672             return true; // no more action?
19673         }
19674         // scroll to?
19675         this.view.select(match);
19676         var sn = Roo.get(this.view.getSelectedNodes()[0]);
19677         sn.scrollIntoView(sn.dom.parentNode, false);
19678     } 
19679
19680     /** 
19681     * @cfg {Boolean} grow 
19682     * @hide 
19683     */
19684     /** 
19685     * @cfg {Number} growMin 
19686     * @hide 
19687     */
19688     /** 
19689     * @cfg {Number} growMax 
19690     * @hide 
19691     */
19692     /**
19693      * @hide
19694      * @method autoSize
19695      */
19696 });/*
19697  * Copyright(c) 2010-2012, Roo J Solutions Limited
19698  *
19699  * Licence LGPL
19700  *
19701  */
19702
19703 /**
19704  * @class Roo.form.ComboBoxArray
19705  * @extends Roo.form.TextField
19706  * A facebook style adder... for lists of email / people / countries  etc...
19707  * pick multiple items from a combo box, and shows each one.
19708  *
19709  *  Fred [x]  Brian [x]  [Pick another |v]
19710  *
19711  *
19712  *  For this to work: it needs various extra information
19713  *    - normal combo problay has
19714  *      name, hiddenName
19715  *    + displayField, valueField
19716  *
19717  *    For our purpose...
19718  *
19719  *
19720  *   If we change from 'extends' to wrapping...
19721  *   
19722  *  
19723  *
19724  
19725  
19726  * @constructor
19727  * Create a new ComboBoxArray.
19728  * @param {Object} config Configuration options
19729  */
19730  
19731
19732 Roo.form.ComboBoxArray = function(config)
19733 {
19734     this.addEvents({
19735         /**
19736          * @event beforeremove
19737          * Fires before remove the value from the list
19738              * @param {Roo.form.ComboBoxArray} _self This combo box array
19739              * @param {Roo.form.ComboBoxArray.Item} item removed item
19740              */
19741         'beforeremove' : true,
19742         /**
19743          * @event remove
19744          * Fires when remove the value from the list
19745              * @param {Roo.form.ComboBoxArray} _self This combo box array
19746              * @param {Roo.form.ComboBoxArray.Item} item removed item
19747              */
19748         'remove' : true
19749         
19750         
19751     });
19752     
19753     Roo.form.ComboBoxArray.superclass.constructor.call(this, config);
19754     
19755     this.items = new Roo.util.MixedCollection(false);
19756     
19757     // construct the child combo...
19758     
19759     
19760     
19761     
19762    
19763     
19764 }
19765
19766  
19767 Roo.extend(Roo.form.ComboBoxArray, Roo.form.TextField,
19768
19769     /**
19770      * @cfg {Roo.form.Combo} combo The combo box that is wrapped
19771      */
19772     
19773     lastData : false,
19774     
19775     // behavies liek a hiddne field
19776     inputType:      'hidden',
19777     /**
19778      * @cfg {Number} width The width of the box that displays the selected element
19779      */ 
19780     width:          300,
19781
19782     
19783     
19784     /**
19785      * @cfg {String} name    The name of the visable items on this form (eg. titles not ids)
19786      */
19787     name : false,
19788     /**
19789      * @cfg {String} hiddenName    The hidden name of the field, often contains an comma seperated list of names
19790      */
19791     hiddenName : false,
19792     
19793     
19794     // private the array of items that are displayed..
19795     items  : false,
19796     // private - the hidden field el.
19797     hiddenEl : false,
19798     // private - the filed el..
19799     el : false,
19800     
19801     //validateValue : function() { return true; }, // all values are ok!
19802     //onAddClick: function() { },
19803     
19804     onRender : function(ct, position) 
19805     {
19806         
19807         // create the standard hidden element
19808         //Roo.form.ComboBoxArray.superclass.onRender.call(this, ct, position);
19809         
19810         
19811         // give fake names to child combo;
19812         this.combo.hiddenName = this.hiddenName ? (this.hiddenName+'-subcombo') : this.hiddenName;
19813         this.combo.name = this.name ? (this.name+'-subcombo') : this.name;
19814         
19815         this.combo = Roo.factory(this.combo, Roo.form);
19816         this.combo.onRender(ct, position);
19817         if (typeof(this.combo.width) != 'undefined') {
19818             this.combo.onResize(this.combo.width,0);
19819         }
19820         
19821         this.combo.initEvents();
19822         
19823         // assigned so form know we need to do this..
19824         this.store          = this.combo.store;
19825         this.valueField     = this.combo.valueField;
19826         this.displayField   = this.combo.displayField ;
19827         
19828         
19829         this.combo.wrap.addClass('x-cbarray-grp');
19830         
19831         var cbwrap = this.combo.wrap.createChild(
19832             {tag: 'div', cls: 'x-cbarray-cb'},
19833             this.combo.el.dom
19834         );
19835         
19836              
19837         this.hiddenEl = this.combo.wrap.createChild({
19838             tag: 'input',  type:'hidden' , name: this.hiddenName, value : ''
19839         });
19840         this.el = this.combo.wrap.createChild({
19841             tag: 'input',  type:'hidden' , name: this.name, value : ''
19842         });
19843          //   this.el.dom.removeAttribute("name");
19844         
19845         
19846         this.outerWrap = this.combo.wrap;
19847         this.wrap = cbwrap;
19848         
19849         this.outerWrap.setWidth(this.width);
19850         this.outerWrap.dom.removeChild(this.el.dom);
19851         
19852         this.wrap.dom.appendChild(this.el.dom);
19853         this.outerWrap.dom.removeChild(this.combo.trigger.dom);
19854         this.combo.wrap.dom.appendChild(this.combo.trigger.dom);
19855         
19856         this.combo.trigger.setStyle('position','relative');
19857         this.combo.trigger.setStyle('left', '0px');
19858         this.combo.trigger.setStyle('top', '2px');
19859         
19860         this.combo.el.setStyle('vertical-align', 'text-bottom');
19861         
19862         //this.trigger.setStyle('vertical-align', 'top');
19863         
19864         // this should use the code from combo really... on('add' ....)
19865         if (this.adder) {
19866             
19867         
19868             this.adder = this.outerWrap.createChild(
19869                 {tag: 'img', src: Roo.BLANK_IMAGE_URL, cls: 'x-form-adder', style: 'margin-left:2px'});  
19870             var _t = this;
19871             this.adder.on('click', function(e) {
19872                 _t.fireEvent('adderclick', this, e);
19873             }, _t);
19874         }
19875         //var _t = this;
19876         //this.adder.on('click', this.onAddClick, _t);
19877         
19878         
19879         this.combo.on('select', function(cb, rec, ix) {
19880             this.addItem(rec.data);
19881             
19882             cb.setValue('');
19883             cb.el.dom.value = '';
19884             //cb.lastData = rec.data;
19885             // add to list
19886             
19887         }, this);
19888         
19889         
19890     },
19891     
19892     
19893     getName: function()
19894     {
19895         // returns hidden if it's set..
19896         if (!this.rendered) {return ''};
19897         return  this.hiddenName ? this.hiddenName : this.name;
19898         
19899     },
19900     
19901     
19902     onResize: function(w, h){
19903         
19904         return;
19905         // not sure if this is needed..
19906         //this.combo.onResize(w,h);
19907         
19908         if(typeof w != 'number'){
19909             // we do not handle it!?!?
19910             return;
19911         }
19912         var tw = this.combo.trigger.getWidth();
19913         tw += this.addicon ? this.addicon.getWidth() : 0;
19914         tw += this.editicon ? this.editicon.getWidth() : 0;
19915         var x = w - tw;
19916         this.combo.el.setWidth( this.combo.adjustWidth('input', x));
19917             
19918         this.combo.trigger.setStyle('left', '0px');
19919         
19920         if(this.list && this.listWidth === undefined){
19921             var lw = Math.max(x + this.combo.trigger.getWidth(), this.combo.minListWidth);
19922             this.list.setWidth(lw);
19923             this.innerList.setWidth(lw - this.list.getFrameWidth('lr'));
19924         }
19925         
19926     
19927         
19928     },
19929     
19930     addItem: function(rec)
19931     {
19932         var valueField = this.combo.valueField;
19933         var displayField = this.combo.displayField;
19934         
19935         if (this.items.indexOfKey(rec[valueField]) > -1) {
19936             //console.log("GOT " + rec.data.id);
19937             return;
19938         }
19939         
19940         var x = new Roo.form.ComboBoxArray.Item({
19941             //id : rec[this.idField],
19942             data : rec,
19943             displayField : displayField ,
19944             tipField : displayField ,
19945             cb : this
19946         });
19947         // use the 
19948         this.items.add(rec[valueField],x);
19949         // add it before the element..
19950         this.updateHiddenEl();
19951         x.render(this.outerWrap, this.wrap.dom);
19952         // add the image handler..
19953     },
19954     
19955     updateHiddenEl : function()
19956     {
19957         this.validate();
19958         if (!this.hiddenEl) {
19959             return;
19960         }
19961         var ar = [];
19962         var idField = this.combo.valueField;
19963         
19964         this.items.each(function(f) {
19965             ar.push(f.data[idField]);
19966         });
19967         this.hiddenEl.dom.value = ar.join(',');
19968         this.validate();
19969     },
19970     
19971     reset : function()
19972     {
19973         this.items.clear();
19974         
19975         Roo.each(this.outerWrap.select('.x-cbarray-item', true).elements, function(el){
19976            el.remove();
19977         });
19978         
19979         this.el.dom.value = '';
19980         if (this.hiddenEl) {
19981             this.hiddenEl.dom.value = '';
19982         }
19983         
19984     },
19985     getValue: function()
19986     {
19987         return this.hiddenEl ? this.hiddenEl.dom.value : '';
19988     },
19989     setValue: function(v) // not a valid action - must use addItems..
19990     {
19991         
19992         this.reset();
19993          
19994         if (this.store.isLocal && (typeof(v) == 'string')) {
19995             // then we can use the store to find the values..
19996             // comma seperated at present.. this needs to allow JSON based encoding..
19997             this.hiddenEl.value  = v;
19998             var v_ar = [];
19999             Roo.each(v.split(','), function(k) {
20000                 Roo.log("CHECK " + this.valueField + ',' + k);
20001                 var li = this.store.query(this.valueField, k);
20002                 if (!li.length) {
20003                     return;
20004                 }
20005                 var add = {};
20006                 add[this.valueField] = k;
20007                 add[this.displayField] = li.item(0).data[this.displayField];
20008                 
20009                 this.addItem(add);
20010             }, this) 
20011              
20012         }
20013         if (typeof(v) == 'object' ) {
20014             // then let's assume it's an array of objects..
20015             Roo.each(v, function(l) {
20016                 this.addItem(l);
20017             }, this);
20018              
20019         }
20020         
20021         
20022     },
20023     setFromData: function(v)
20024     {
20025         // this recieves an object, if setValues is called.
20026         this.reset();
20027         this.el.dom.value = v[this.displayField];
20028         this.hiddenEl.dom.value = v[this.valueField];
20029         if (typeof(v[this.valueField]) != 'string' || !v[this.valueField].length) {
20030             return;
20031         }
20032         var kv = v[this.valueField];
20033         var dv = v[this.displayField];
20034         kv = typeof(kv) != 'string' ? '' : kv;
20035         dv = typeof(dv) != 'string' ? '' : dv;
20036         
20037         
20038         var keys = kv.split(',');
20039         var display = dv.split(',');
20040         for (var i = 0 ; i < keys.length; i++) {
20041             
20042             add = {};
20043             add[this.valueField] = keys[i];
20044             add[this.displayField] = display[i];
20045             this.addItem(add);
20046         }
20047       
20048         
20049     },
20050     
20051     /**
20052      * Validates the combox array value
20053      * @return {Boolean} True if the value is valid, else false
20054      */
20055     validate : function(){
20056         if(this.disabled || this.validateValue(this.processValue(this.getValue()))){
20057             this.clearInvalid();
20058             return true;
20059         }
20060         return false;
20061     },
20062     
20063     validateValue : function(value){
20064         return Roo.form.ComboBoxArray.superclass.validateValue.call(this, this.getValue());
20065         
20066     },
20067     
20068     /*@
20069      * overide
20070      * 
20071      */
20072     isDirty : function() {
20073         if(this.disabled) {
20074             return false;
20075         }
20076         
20077         try {
20078             var d = Roo.decode(String(this.originalValue));
20079         } catch (e) {
20080             return String(this.getValue()) !== String(this.originalValue);
20081         }
20082         
20083         var originalValue = [];
20084         
20085         for (var i = 0; i < d.length; i++){
20086             originalValue.push(d[i][this.valueField]);
20087         }
20088         
20089         return String(this.getValue()) !== String(originalValue.join(','));
20090         
20091     }
20092     
20093 });
20094
20095
20096
20097 /**
20098  * @class Roo.form.ComboBoxArray.Item
20099  * @extends Roo.BoxComponent
20100  * A selected item in the list
20101  *  Fred [x]  Brian [x]  [Pick another |v]
20102  * 
20103  * @constructor
20104  * Create a new item.
20105  * @param {Object} config Configuration options
20106  */
20107  
20108 Roo.form.ComboBoxArray.Item = function(config) {
20109     config.id = Roo.id();
20110     Roo.form.ComboBoxArray.Item.superclass.constructor.call(this, config);
20111 }
20112
20113 Roo.extend(Roo.form.ComboBoxArray.Item, Roo.BoxComponent, {
20114     data : {},
20115     cb: false,
20116     displayField : false,
20117     tipField : false,
20118     
20119     
20120     defaultAutoCreate : {
20121         tag: 'div',
20122         cls: 'x-cbarray-item',
20123         cn : [ 
20124             { tag: 'div' },
20125             {
20126                 tag: 'img',
20127                 width:16,
20128                 height : 16,
20129                 src : Roo.BLANK_IMAGE_URL ,
20130                 align: 'center'
20131             }
20132         ]
20133         
20134     },
20135     
20136  
20137     onRender : function(ct, position)
20138     {
20139         Roo.form.Field.superclass.onRender.call(this, ct, position);
20140         
20141         if(!this.el){
20142             var cfg = this.getAutoCreate();
20143             this.el = ct.createChild(cfg, position);
20144         }
20145         
20146         this.el.child('img').dom.setAttribute('src', Roo.BLANK_IMAGE_URL);
20147         
20148         this.el.child('div').dom.innerHTML = this.cb.renderer ? 
20149             this.cb.renderer(this.data) :
20150             String.format('{0}',this.data[this.displayField]);
20151         
20152             
20153         this.el.child('div').dom.setAttribute('qtip',
20154                         String.format('{0}',this.data[this.tipField])
20155         );
20156         
20157         this.el.child('img').on('click', this.remove, this);
20158         
20159     },
20160    
20161     remove : function()
20162     {
20163         if(this.cb.disabled){
20164             return;
20165         }
20166         
20167         if(false !== this.cb.fireEvent('beforeremove', this.cb, this)){
20168             this.cb.items.remove(this);
20169             this.el.child('img').un('click', this.remove, this);
20170             this.el.remove();
20171             this.cb.updateHiddenEl();
20172
20173             this.cb.fireEvent('remove', this.cb, this);
20174         }
20175         
20176     }
20177 });/*
20178  * Based on:
20179  * Ext JS Library 1.1.1
20180  * Copyright(c) 2006-2007, Ext JS, LLC.
20181  *
20182  * Originally Released Under LGPL - original licence link has changed is not relivant.
20183  *
20184  * Fork - LGPL
20185  * <script type="text/javascript">
20186  */
20187 /**
20188  * @class Roo.form.Checkbox
20189  * @extends Roo.form.Field
20190  * Single checkbox field.  Can be used as a direct replacement for traditional checkbox fields.
20191  * @constructor
20192  * Creates a new Checkbox
20193  * @param {Object} config Configuration options
20194  */
20195 Roo.form.Checkbox = function(config){
20196     Roo.form.Checkbox.superclass.constructor.call(this, config);
20197     this.addEvents({
20198         /**
20199          * @event check
20200          * Fires when the checkbox is checked or unchecked.
20201              * @param {Roo.form.Checkbox} this This checkbox
20202              * @param {Boolean} checked The new checked value
20203              */
20204         check : true
20205     });
20206 };
20207
20208 Roo.extend(Roo.form.Checkbox, Roo.form.Field,  {
20209     /**
20210      * @cfg {String} focusClass The CSS class to use when the checkbox receives focus (defaults to undefined)
20211      */
20212     focusClass : undefined,
20213     /**
20214      * @cfg {String} fieldClass The default CSS class for the checkbox (defaults to "x-form-field")
20215      */
20216     fieldClass: "x-form-field",
20217     /**
20218      * @cfg {Boolean} checked True if the the checkbox should render already checked (defaults to false)
20219      */
20220     checked: false,
20221     /**
20222      * @cfg {String/Object} autoCreate A DomHelper element spec, or true for a default element spec (defaults to
20223      * {tag: "input", type: "checkbox", autocomplete: "off"})
20224      */
20225     defaultAutoCreate : { tag: "input", type: 'hidden', autocomplete: "off"},
20226     /**
20227      * @cfg {String} boxLabel The text that appears beside the checkbox
20228      */
20229     boxLabel : "",
20230     /**
20231      * @cfg {String} inputValue The value that should go into the generated input element's value attribute
20232      */  
20233     inputValue : '1',
20234     /**
20235      * @cfg {String} valueOff The value that should go into the generated input element's value when unchecked.
20236      */
20237      valueOff: '0', // value when not checked..
20238
20239     actionMode : 'viewEl', 
20240     //
20241     // private
20242     itemCls : 'x-menu-check-item x-form-item',
20243     groupClass : 'x-menu-group-item',
20244     inputType : 'hidden',
20245     
20246     
20247     inSetChecked: false, // check that we are not calling self...
20248     
20249     inputElement: false, // real input element?
20250     basedOn: false, // ????
20251     
20252     isFormField: true, // not sure where this is needed!!!!
20253
20254     onResize : function(){
20255         Roo.form.Checkbox.superclass.onResize.apply(this, arguments);
20256         if(!this.boxLabel){
20257             this.el.alignTo(this.wrap, 'c-c');
20258         }
20259     },
20260
20261     initEvents : function(){
20262         Roo.form.Checkbox.superclass.initEvents.call(this);
20263         this.el.on("click", this.onClick,  this);
20264         this.el.on("change", this.onClick,  this);
20265     },
20266
20267
20268     getResizeEl : function(){
20269         return this.wrap;
20270     },
20271
20272     getPositionEl : function(){
20273         return this.wrap;
20274     },
20275
20276     // private
20277     onRender : function(ct, position){
20278         Roo.form.Checkbox.superclass.onRender.call(this, ct, position);
20279         /*
20280         if(this.inputValue !== undefined){
20281             this.el.dom.value = this.inputValue;
20282         }
20283         */
20284         //this.wrap = this.el.wrap({cls: "x-form-check-wrap"});
20285         this.wrap = this.el.wrap({cls: 'x-menu-check-item '});
20286         var viewEl = this.wrap.createChild({ 
20287             tag: 'img', cls: 'x-menu-item-icon', style: 'margin: 0px;' ,src : Roo.BLANK_IMAGE_URL });
20288         this.viewEl = viewEl;   
20289         this.wrap.on('click', this.onClick,  this); 
20290         
20291         this.el.on('DOMAttrModified', this.setFromHidden,  this); //ff
20292         this.el.on('propertychange', this.setFromHidden,  this);  //ie
20293         
20294         
20295         
20296         if(this.boxLabel){
20297             this.wrap.createChild({tag: 'label', htmlFor: this.el.id, cls: 'x-form-cb-label', html: this.boxLabel});
20298         //    viewEl.on('click', this.onClick,  this); 
20299         }
20300         //if(this.checked){
20301             this.setChecked(this.checked);
20302         //}else{
20303             //this.checked = this.el.dom;
20304         //}
20305
20306     },
20307
20308     // private
20309     initValue : Roo.emptyFn,
20310
20311     /**
20312      * Returns the checked state of the checkbox.
20313      * @return {Boolean} True if checked, else false
20314      */
20315     getValue : function(){
20316         if(this.el){
20317             return String(this.el.dom.value) == String(this.inputValue ) ? this.inputValue : this.valueOff;
20318         }
20319         return this.valueOff;
20320         
20321     },
20322
20323         // private
20324     onClick : function(){ 
20325         if (this.disabled) {
20326             return;
20327         }
20328         this.setChecked(!this.checked);
20329
20330         //if(this.el.dom.checked != this.checked){
20331         //    this.setValue(this.el.dom.checked);
20332        // }
20333     },
20334
20335     /**
20336      * Sets the checked state of the checkbox.
20337      * On is always based on a string comparison between inputValue and the param.
20338      * @param {Boolean/String} value - the value to set 
20339      * @param {Boolean/String} suppressEvent - whether to suppress the checkchange event.
20340      */
20341     setValue : function(v,suppressEvent){
20342         
20343         
20344         //this.checked = (v === true || v === 'true' || v == '1' || String(v).toLowerCase() == 'on');
20345         //if(this.el && this.el.dom){
20346         //    this.el.dom.checked = this.checked;
20347         //    this.el.dom.defaultChecked = this.checked;
20348         //}
20349         this.setChecked(String(v) === String(this.inputValue), suppressEvent);
20350         //this.fireEvent("check", this, this.checked);
20351     },
20352     // private..
20353     setChecked : function(state,suppressEvent)
20354     {
20355         if (this.inSetChecked) {
20356             this.checked = state;
20357             return;
20358         }
20359         
20360     
20361         if(this.wrap){
20362             this.wrap[state ? 'addClass' : 'removeClass']('x-menu-item-checked');
20363         }
20364         this.checked = state;
20365         if(suppressEvent !== true){
20366             this.fireEvent('check', this, state);
20367         }
20368         this.inSetChecked = true;
20369         this.el.dom.value = state ? this.inputValue : this.valueOff;
20370         this.inSetChecked = false;
20371         
20372     },
20373     // handle setting of hidden value by some other method!!?!?
20374     setFromHidden: function()
20375     {
20376         if(!this.el){
20377             return;
20378         }
20379         //console.log("SET FROM HIDDEN");
20380         //alert('setFrom hidden');
20381         this.setValue(this.el.dom.value);
20382     },
20383     
20384     onDestroy : function()
20385     {
20386         if(this.viewEl){
20387             Roo.get(this.viewEl).remove();
20388         }
20389          
20390         Roo.form.Checkbox.superclass.onDestroy.call(this);
20391     },
20392     
20393     setBoxLabel : function(str)
20394     {
20395         this.wrap.select('.x-form-cb-label', true).first().dom.innerHTML = str;
20396     }
20397
20398 });/*
20399  * Based on:
20400  * Ext JS Library 1.1.1
20401  * Copyright(c) 2006-2007, Ext JS, LLC.
20402  *
20403  * Originally Released Under LGPL - original licence link has changed is not relivant.
20404  *
20405  * Fork - LGPL
20406  * <script type="text/javascript">
20407  */
20408  
20409 /**
20410  * @class Roo.form.Radio
20411  * @extends Roo.form.Checkbox
20412  * Single radio field.  Same as Checkbox, but provided as a convenience for automatically setting the input type.
20413  * Radio grouping is handled automatically by the browser if you give each radio in a group the same name.
20414  * @constructor
20415  * Creates a new Radio
20416  * @param {Object} config Configuration options
20417  */
20418 Roo.form.Radio = function(){
20419     Roo.form.Radio.superclass.constructor.apply(this, arguments);
20420 };
20421 Roo.extend(Roo.form.Radio, Roo.form.Checkbox, {
20422     inputType: 'radio',
20423
20424     /**
20425      * If this radio is part of a group, it will return the selected value
20426      * @return {String}
20427      */
20428     getGroupValue : function(){
20429         return this.el.up('form').child('input[name='+this.el.dom.name+']:checked', true).value;
20430     },
20431     
20432     
20433     onRender : function(ct, position){
20434         Roo.form.Checkbox.superclass.onRender.call(this, ct, position);
20435         
20436         if(this.inputValue !== undefined){
20437             this.el.dom.value = this.inputValue;
20438         }
20439          
20440         this.wrap = this.el.wrap({cls: "x-form-check-wrap"});
20441         //this.wrap = this.el.wrap({cls: 'x-menu-check-item '});
20442         //var viewEl = this.wrap.createChild({ 
20443         //    tag: 'img', cls: 'x-menu-item-icon', style: 'margin: 0px;' ,src : Roo.BLANK_IMAGE_URL });
20444         //this.viewEl = viewEl;   
20445         //this.wrap.on('click', this.onClick,  this); 
20446         
20447         //this.el.on('DOMAttrModified', this.setFromHidden,  this); //ff
20448         //this.el.on('propertychange', this.setFromHidden,  this);  //ie
20449         
20450         
20451         
20452         if(this.boxLabel){
20453             this.wrap.createChild({tag: 'label', htmlFor: this.el.id, cls: 'x-form-cb-label', html: this.boxLabel});
20454         //    viewEl.on('click', this.onClick,  this); 
20455         }
20456          if(this.checked){
20457             this.el.dom.checked =   'checked' ;
20458         }
20459          
20460     } 
20461     
20462     
20463 });//<script type="text/javascript">
20464
20465 /*
20466  * Based  Ext JS Library 1.1.1
20467  * Copyright(c) 2006-2007, Ext JS, LLC.
20468  * LGPL
20469  *
20470  */
20471  
20472 /**
20473  * @class Roo.HtmlEditorCore
20474  * @extends Roo.Component
20475  * Provides a the editing component for the HTML editors in Roo. (bootstrap and Roo.form)
20476  *
20477  * any element that has display set to 'none' can cause problems in Safari and Firefox.<br/><br/>
20478  */
20479
20480 Roo.HtmlEditorCore = function(config){
20481     
20482     
20483     Roo.HtmlEditorCore.superclass.constructor.call(this, config);
20484     
20485     
20486     this.addEvents({
20487         /**
20488          * @event initialize
20489          * Fires when the editor is fully initialized (including the iframe)
20490          * @param {Roo.HtmlEditorCore} this
20491          */
20492         initialize: true,
20493         /**
20494          * @event activate
20495          * Fires when the editor is first receives the focus. Any insertion must wait
20496          * until after this event.
20497          * @param {Roo.HtmlEditorCore} this
20498          */
20499         activate: true,
20500          /**
20501          * @event beforesync
20502          * Fires before the textarea is updated with content from the editor iframe. Return false
20503          * to cancel the sync.
20504          * @param {Roo.HtmlEditorCore} this
20505          * @param {String} html
20506          */
20507         beforesync: true,
20508          /**
20509          * @event beforepush
20510          * Fires before the iframe editor is updated with content from the textarea. Return false
20511          * to cancel the push.
20512          * @param {Roo.HtmlEditorCore} this
20513          * @param {String} html
20514          */
20515         beforepush: true,
20516          /**
20517          * @event sync
20518          * Fires when the textarea is updated with content from the editor iframe.
20519          * @param {Roo.HtmlEditorCore} this
20520          * @param {String} html
20521          */
20522         sync: true,
20523          /**
20524          * @event push
20525          * Fires when the iframe editor is updated with content from the textarea.
20526          * @param {Roo.HtmlEditorCore} this
20527          * @param {String} html
20528          */
20529         push: true,
20530         
20531         /**
20532          * @event editorevent
20533          * Fires when on any editor (mouse up/down cursor movement etc.) - used for toolbar hooks.
20534          * @param {Roo.HtmlEditorCore} this
20535          */
20536         editorevent: true
20537         
20538     });
20539     
20540     // at this point this.owner is set, so we can start working out the whitelisted / blacklisted elements
20541     
20542     // defaults : white / black...
20543     this.applyBlacklists();
20544     
20545     
20546     
20547 };
20548
20549
20550 Roo.extend(Roo.HtmlEditorCore, Roo.Component,  {
20551
20552
20553      /**
20554      * @cfg {Roo.form.HtmlEditor|Roo.bootstrap.HtmlEditor} the owner field 
20555      */
20556     
20557     owner : false,
20558     
20559      /**
20560      * @cfg {String} resizable  's' or 'se' or 'e' - wrapps the element in a
20561      *                        Roo.resizable.
20562      */
20563     resizable : false,
20564      /**
20565      * @cfg {Number} height (in pixels)
20566      */   
20567     height: 300,
20568    /**
20569      * @cfg {Number} width (in pixels)
20570      */   
20571     width: 500,
20572     
20573     /**
20574      * @cfg {Array} stylesheets url of stylesheets. set to [] to disable stylesheets.
20575      * 
20576      */
20577     stylesheets: false,
20578     
20579     // id of frame..
20580     frameId: false,
20581     
20582     // private properties
20583     validationEvent : false,
20584     deferHeight: true,
20585     initialized : false,
20586     activated : false,
20587     sourceEditMode : false,
20588     onFocus : Roo.emptyFn,
20589     iframePad:3,
20590     hideMode:'offsets',
20591     
20592     clearUp: true,
20593     
20594     // blacklist + whitelisted elements..
20595     black: false,
20596     white: false,
20597      
20598     bodyCls : '',
20599
20600     /**
20601      * Protected method that will not generally be called directly. It
20602      * is called when the editor initializes the iframe with HTML contents. Override this method if you
20603      * want to change the initialization markup of the iframe (e.g. to add stylesheets).
20604      */
20605     getDocMarkup : function(){
20606         // body styles..
20607         var st = '';
20608         
20609         // inherit styels from page...?? 
20610         if (this.stylesheets === false) {
20611             
20612             Roo.get(document.head).select('style').each(function(node) {
20613                 st += node.dom.outerHTML || new XMLSerializer().serializeToString(node.dom);
20614             });
20615             
20616             Roo.get(document.head).select('link').each(function(node) { 
20617                 st += node.dom.outerHTML || new XMLSerializer().serializeToString(node.dom);
20618             });
20619             
20620         } else if (!this.stylesheets.length) {
20621                 // simple..
20622                 st = '<style type="text/css">' +
20623                     'body{border:0;margin:0;padding:3px;height:98%;cursor:text;}' +
20624                    '</style>';
20625         } else { 
20626             st = '<style type="text/css">' +
20627                     this.stylesheets +
20628                 '</style>';
20629         }
20630         
20631         st +=  '<style type="text/css">' +
20632             'IMG { cursor: pointer } ' +
20633         '</style>';
20634
20635         var cls = 'roo-htmleditor-body';
20636         
20637         if(this.bodyCls.length){
20638             cls += ' ' + this.bodyCls;
20639         }
20640         
20641         return '<html><head>' + st  +
20642             //<style type="text/css">' +
20643             //'body{border:0;margin:0;padding:3px;height:98%;cursor:text;}' +
20644             //'</style>' +
20645             ' </head><body class="' +  cls + '"></body></html>';
20646     },
20647
20648     // private
20649     onRender : function(ct, position)
20650     {
20651         var _t = this;
20652         //Roo.HtmlEditorCore.superclass.onRender.call(this, ct, position);
20653         this.el = this.owner.inputEl ? this.owner.inputEl() : this.owner.el;
20654         
20655         
20656         this.el.dom.style.border = '0 none';
20657         this.el.dom.setAttribute('tabIndex', -1);
20658         this.el.addClass('x-hidden hide');
20659         
20660         
20661         
20662         if(Roo.isIE){ // fix IE 1px bogus margin
20663             this.el.applyStyles('margin-top:-1px;margin-bottom:-1px;')
20664         }
20665        
20666         
20667         this.frameId = Roo.id();
20668         
20669          
20670         
20671         var iframe = this.owner.wrap.createChild({
20672             tag: 'iframe',
20673             cls: 'form-control', // bootstrap..
20674             id: this.frameId,
20675             name: this.frameId,
20676             frameBorder : 'no',
20677             'src' : Roo.SSL_SECURE_URL ? Roo.SSL_SECURE_URL  :  "javascript:false"
20678         }, this.el
20679         );
20680         
20681         
20682         this.iframe = iframe.dom;
20683
20684          this.assignDocWin();
20685         
20686         this.doc.designMode = 'on';
20687        
20688         this.doc.open();
20689         this.doc.write(this.getDocMarkup());
20690         this.doc.close();
20691
20692         
20693         var task = { // must defer to wait for browser to be ready
20694             run : function(){
20695                 //console.log("run task?" + this.doc.readyState);
20696                 this.assignDocWin();
20697                 if(this.doc.body || this.doc.readyState == 'complete'){
20698                     try {
20699                         this.doc.designMode="on";
20700                     } catch (e) {
20701                         return;
20702                     }
20703                     Roo.TaskMgr.stop(task);
20704                     this.initEditor.defer(10, this);
20705                 }
20706             },
20707             interval : 10,
20708             duration: 10000,
20709             scope: this
20710         };
20711         Roo.TaskMgr.start(task);
20712
20713     },
20714
20715     // private
20716     onResize : function(w, h)
20717     {
20718          Roo.log('resize: ' +w + ',' + h );
20719         //Roo.HtmlEditorCore.superclass.onResize.apply(this, arguments);
20720         if(!this.iframe){
20721             return;
20722         }
20723         if(typeof w == 'number'){
20724             
20725             this.iframe.style.width = w + 'px';
20726         }
20727         if(typeof h == 'number'){
20728             
20729             this.iframe.style.height = h + 'px';
20730             if(this.doc){
20731                 (this.doc.body || this.doc.documentElement).style.height = (h - (this.iframePad*2)) + 'px';
20732             }
20733         }
20734         
20735     },
20736
20737     /**
20738      * Toggles the editor between standard and source edit mode.
20739      * @param {Boolean} sourceEdit (optional) True for source edit, false for standard
20740      */
20741     toggleSourceEdit : function(sourceEditMode){
20742         
20743         this.sourceEditMode = sourceEditMode === true;
20744         
20745         if(this.sourceEditMode){
20746  
20747             Roo.get(this.iframe).addClass(['x-hidden','hide']);     //FIXME - what's the BS styles for these
20748             
20749         }else{
20750             Roo.get(this.iframe).removeClass(['x-hidden','hide']);
20751             //this.iframe.className = '';
20752             this.deferFocus();
20753         }
20754         //this.setSize(this.owner.wrap.getSize());
20755         //this.fireEvent('editmodechange', this, this.sourceEditMode);
20756     },
20757
20758     
20759   
20760
20761     /**
20762      * Protected method that will not generally be called directly. If you need/want
20763      * custom HTML cleanup, this is the method you should override.
20764      * @param {String} html The HTML to be cleaned
20765      * return {String} The cleaned HTML
20766      */
20767     cleanHtml : function(html){
20768         html = String(html);
20769         if(html.length > 5){
20770             if(Roo.isSafari){ // strip safari nonsense
20771                 html = html.replace(/\sclass="(?:Apple-style-span|khtml-block-placeholder)"/gi, '');
20772             }
20773         }
20774         if(html == '&nbsp;'){
20775             html = '';
20776         }
20777         return html;
20778     },
20779
20780     /**
20781      * HTML Editor -> Textarea
20782      * Protected method that will not generally be called directly. Syncs the contents
20783      * of the editor iframe with the textarea.
20784      */
20785     syncValue : function(){
20786         if(this.initialized){
20787             var bd = (this.doc.body || this.doc.documentElement);
20788             //this.cleanUpPaste(); -- this is done else where and causes havoc..
20789             var html = bd.innerHTML;
20790             if(Roo.isSafari){
20791                 var bs = bd.getAttribute('style'); // Safari puts text-align styles on the body element!
20792                 var m = bs ? bs.match(/text-align:(.*?);/i) : false;
20793                 if(m && m[1]){
20794                     html = '<div style="'+m[0]+'">' + html + '</div>';
20795                 }
20796             }
20797             html = this.cleanHtml(html);
20798             // fix up the special chars.. normaly like back quotes in word...
20799             // however we do not want to do this with chinese..
20800             html = html.replace(/[\uD800-\uDBFF][\uDC00-\uDFFF]|[\u0080-\uFFFF]/g, function(match) {
20801                 
20802                 var cc = match.charCodeAt();
20803
20804                 // Get the character value, handling surrogate pairs
20805                 if (match.length == 2) {
20806                     // It's a surrogate pair, calculate the Unicode code point
20807                     var high = match.charCodeAt(0) - 0xD800;
20808                     var low  = match.charCodeAt(1) - 0xDC00;
20809                     cc = (high * 0x400) + low + 0x10000;
20810                 }  else if (
20811                     (cc >= 0x4E00 && cc < 0xA000 ) ||
20812                     (cc >= 0x3400 && cc < 0x4E00 ) ||
20813                     (cc >= 0xf900 && cc < 0xfb00 )
20814                 ) {
20815                         return match;
20816                 }  
20817          
20818                 // No, use a numeric entity. Here we brazenly (and possibly mistakenly)
20819                 return "&#" + cc + ";";
20820                 
20821                 
20822             });
20823             
20824             
20825              
20826             if(this.owner.fireEvent('beforesync', this, html) !== false){
20827                 this.el.dom.value = html;
20828                 this.owner.fireEvent('sync', this, html);
20829             }
20830         }
20831     },
20832
20833     /**
20834      * Protected method that will not generally be called directly. Pushes the value of the textarea
20835      * into the iframe editor.
20836      */
20837     pushValue : function(){
20838         if(this.initialized){
20839             var v = this.el.dom.value.trim();
20840             
20841 //            if(v.length < 1){
20842 //                v = '&#160;';
20843 //            }
20844             
20845             if(this.owner.fireEvent('beforepush', this, v) !== false){
20846                 var d = (this.doc.body || this.doc.documentElement);
20847                 d.innerHTML = v;
20848                 this.cleanUpPaste();
20849                 this.el.dom.value = d.innerHTML;
20850                 this.owner.fireEvent('push', this, v);
20851             }
20852         }
20853     },
20854
20855     // private
20856     deferFocus : function(){
20857         this.focus.defer(10, this);
20858     },
20859
20860     // doc'ed in Field
20861     focus : function(){
20862         if(this.win && !this.sourceEditMode){
20863             this.win.focus();
20864         }else{
20865             this.el.focus();
20866         }
20867     },
20868     
20869     assignDocWin: function()
20870     {
20871         var iframe = this.iframe;
20872         
20873          if(Roo.isIE){
20874             this.doc = iframe.contentWindow.document;
20875             this.win = iframe.contentWindow;
20876         } else {
20877 //            if (!Roo.get(this.frameId)) {
20878 //                return;
20879 //            }
20880 //            this.doc = (iframe.contentDocument || Roo.get(this.frameId).dom.document);
20881 //            this.win = Roo.get(this.frameId).dom.contentWindow;
20882             
20883             if (!Roo.get(this.frameId) && !iframe.contentDocument) {
20884                 return;
20885             }
20886             
20887             this.doc = (iframe.contentDocument || Roo.get(this.frameId).dom.document);
20888             this.win = (iframe.contentWindow || Roo.get(this.frameId).dom.contentWindow);
20889         }
20890     },
20891     
20892     // private
20893     initEditor : function(){
20894         //console.log("INIT EDITOR");
20895         this.assignDocWin();
20896         
20897         
20898         
20899         this.doc.designMode="on";
20900         this.doc.open();
20901         this.doc.write(this.getDocMarkup());
20902         this.doc.close();
20903         
20904         var dbody = (this.doc.body || this.doc.documentElement);
20905         //var ss = this.el.getStyles('font-size', 'font-family', 'background-image', 'background-repeat');
20906         // this copies styles from the containing element into thsi one..
20907         // not sure why we need all of this..
20908         //var ss = this.el.getStyles('font-size', 'background-image', 'background-repeat');
20909         
20910         //var ss = this.el.getStyles( 'background-image', 'background-repeat');
20911         //ss['background-attachment'] = 'fixed'; // w3c
20912         dbody.bgProperties = 'fixed'; // ie
20913         //Roo.DomHelper.applyStyles(dbody, ss);
20914         Roo.EventManager.on(this.doc, {
20915             //'mousedown': this.onEditorEvent,
20916             'mouseup': this.onEditorEvent,
20917             'dblclick': this.onEditorEvent,
20918             'click': this.onEditorEvent,
20919             'keyup': this.onEditorEvent,
20920             buffer:100,
20921             scope: this
20922         });
20923         if(Roo.isGecko){
20924             Roo.EventManager.on(this.doc, 'keypress', this.mozKeyPress, this);
20925         }
20926         if(Roo.isIE || Roo.isSafari || Roo.isOpera){
20927             Roo.EventManager.on(this.doc, 'keydown', this.fixKeys, this);
20928         }
20929         this.initialized = true;
20930
20931         this.owner.fireEvent('initialize', this);
20932         this.pushValue();
20933     },
20934
20935     // private
20936     onDestroy : function(){
20937         
20938         
20939         
20940         if(this.rendered){
20941             
20942             //for (var i =0; i < this.toolbars.length;i++) {
20943             //    // fixme - ask toolbars for heights?
20944             //    this.toolbars[i].onDestroy();
20945            // }
20946             
20947             //this.wrap.dom.innerHTML = '';
20948             //this.wrap.remove();
20949         }
20950     },
20951
20952     // private
20953     onFirstFocus : function(){
20954         
20955         this.assignDocWin();
20956         
20957         
20958         this.activated = true;
20959          
20960     
20961         if(Roo.isGecko){ // prevent silly gecko errors
20962             this.win.focus();
20963             var s = this.win.getSelection();
20964             if(!s.focusNode || s.focusNode.nodeType != 3){
20965                 var r = s.getRangeAt(0);
20966                 r.selectNodeContents((this.doc.body || this.doc.documentElement));
20967                 r.collapse(true);
20968                 this.deferFocus();
20969             }
20970             try{
20971                 this.execCmd('useCSS', true);
20972                 this.execCmd('styleWithCSS', false);
20973             }catch(e){}
20974         }
20975         this.owner.fireEvent('activate', this);
20976     },
20977
20978     // private
20979     adjustFont: function(btn){
20980         var adjust = btn.cmd == 'increasefontsize' ? 1 : -1;
20981         //if(Roo.isSafari){ // safari
20982         //    adjust *= 2;
20983        // }
20984         var v = parseInt(this.doc.queryCommandValue('FontSize')|| 3, 10);
20985         if(Roo.isSafari){ // safari
20986             var sm = { 10 : 1, 13: 2, 16:3, 18:4, 24: 5, 32:6, 48: 7 };
20987             v =  (v < 10) ? 10 : v;
20988             v =  (v > 48) ? 48 : v;
20989             v = typeof(sm[v]) == 'undefined' ? 1 : sm[v];
20990             
20991         }
20992         
20993         
20994         v = Math.max(1, v+adjust);
20995         
20996         this.execCmd('FontSize', v  );
20997     },
20998
20999     onEditorEvent : function(e)
21000     {
21001         this.owner.fireEvent('editorevent', this, e);
21002       //  this.updateToolbar();
21003         this.syncValue(); //we can not sync so often.. sync cleans, so this breaks stuff
21004     },
21005
21006     insertTag : function(tg)
21007     {
21008         // could be a bit smarter... -> wrap the current selected tRoo..
21009         if (tg.toLowerCase() == 'span' || tg.toLowerCase() == 'code') {
21010             
21011             range = this.createRange(this.getSelection());
21012             var wrappingNode = this.doc.createElement(tg.toLowerCase());
21013             wrappingNode.appendChild(range.extractContents());
21014             range.insertNode(wrappingNode);
21015
21016             return;
21017             
21018             
21019             
21020         }
21021         this.execCmd("formatblock",   tg);
21022         
21023     },
21024     
21025     insertText : function(txt)
21026     {
21027         
21028         
21029         var range = this.createRange();
21030         range.deleteContents();
21031                //alert(Sender.getAttribute('label'));
21032                
21033         range.insertNode(this.doc.createTextNode(txt));
21034     } ,
21035     
21036      
21037
21038     /**
21039      * Executes a Midas editor command on the editor document and performs necessary focus and
21040      * toolbar updates. <b>This should only be called after the editor is initialized.</b>
21041      * @param {String} cmd The Midas command
21042      * @param {String/Boolean} value (optional) The value to pass to the command (defaults to null)
21043      */
21044     relayCmd : function(cmd, value){
21045         this.win.focus();
21046         this.execCmd(cmd, value);
21047         this.owner.fireEvent('editorevent', this);
21048         //this.updateToolbar();
21049         this.owner.deferFocus();
21050     },
21051
21052     /**
21053      * Executes a Midas editor command directly on the editor document.
21054      * For visual commands, you should use {@link #relayCmd} instead.
21055      * <b>This should only be called after the editor is initialized.</b>
21056      * @param {String} cmd The Midas command
21057      * @param {String/Boolean} value (optional) The value to pass to the command (defaults to null)
21058      */
21059     execCmd : function(cmd, value){
21060         this.doc.execCommand(cmd, false, value === undefined ? null : value);
21061         this.syncValue();
21062     },
21063  
21064  
21065    
21066     /**
21067      * Inserts the passed text at the current cursor position. Note: the editor must be initialized and activated
21068      * to insert tRoo.
21069      * @param {String} text | dom node.. 
21070      */
21071     insertAtCursor : function(text)
21072     {
21073         
21074         if(!this.activated){
21075             return;
21076         }
21077         /*
21078         if(Roo.isIE){
21079             this.win.focus();
21080             var r = this.doc.selection.createRange();
21081             if(r){
21082                 r.collapse(true);
21083                 r.pasteHTML(text);
21084                 this.syncValue();
21085                 this.deferFocus();
21086             
21087             }
21088             return;
21089         }
21090         */
21091         if(Roo.isGecko || Roo.isOpera || Roo.isSafari){
21092             this.win.focus();
21093             
21094             
21095             // from jquery ui (MIT licenced)
21096             var range, node;
21097             var win = this.win;
21098             
21099             if (win.getSelection && win.getSelection().getRangeAt) {
21100                 range = win.getSelection().getRangeAt(0);
21101                 node = typeof(text) == 'string' ? range.createContextualFragment(text) : text;
21102                 range.insertNode(node);
21103             } else if (win.document.selection && win.document.selection.createRange) {
21104                 // no firefox support
21105                 var txt = typeof(text) == 'string' ? text : text.outerHTML;
21106                 win.document.selection.createRange().pasteHTML(txt);
21107             } else {
21108                 // no firefox support
21109                 var txt = typeof(text) == 'string' ? text : text.outerHTML;
21110                 this.execCmd('InsertHTML', txt);
21111             } 
21112             
21113             this.syncValue();
21114             
21115             this.deferFocus();
21116         }
21117     },
21118  // private
21119     mozKeyPress : function(e){
21120         if(e.ctrlKey){
21121             var c = e.getCharCode(), cmd;
21122           
21123             if(c > 0){
21124                 c = String.fromCharCode(c).toLowerCase();
21125                 switch(c){
21126                     case 'b':
21127                         cmd = 'bold';
21128                         break;
21129                     case 'i':
21130                         cmd = 'italic';
21131                         break;
21132                     
21133                     case 'u':
21134                         cmd = 'underline';
21135                         break;
21136                     
21137                     case 'v':
21138                         this.cleanUpPaste.defer(100, this);
21139                         return;
21140                         
21141                 }
21142                 if(cmd){
21143                     this.win.focus();
21144                     this.execCmd(cmd);
21145                     this.deferFocus();
21146                     e.preventDefault();
21147                 }
21148                 
21149             }
21150         }
21151     },
21152
21153     // private
21154     fixKeys : function(){ // load time branching for fastest keydown performance
21155         if(Roo.isIE){
21156             return function(e){
21157                 var k = e.getKey(), r;
21158                 if(k == e.TAB){
21159                     e.stopEvent();
21160                     r = this.doc.selection.createRange();
21161                     if(r){
21162                         r.collapse(true);
21163                         r.pasteHTML('&#160;&#160;&#160;&#160;');
21164                         this.deferFocus();
21165                     }
21166                     return;
21167                 }
21168                 
21169                 if(k == e.ENTER){
21170                     r = this.doc.selection.createRange();
21171                     if(r){
21172                         var target = r.parentElement();
21173                         if(!target || target.tagName.toLowerCase() != 'li'){
21174                             e.stopEvent();
21175                             r.pasteHTML('<br />');
21176                             r.collapse(false);
21177                             r.select();
21178                         }
21179                     }
21180                 }
21181                 if (String.fromCharCode(k).toLowerCase() == 'v') { // paste
21182                     this.cleanUpPaste.defer(100, this);
21183                     return;
21184                 }
21185                 
21186                 
21187             };
21188         }else if(Roo.isOpera){
21189             return function(e){
21190                 var k = e.getKey();
21191                 if(k == e.TAB){
21192                     e.stopEvent();
21193                     this.win.focus();
21194                     this.execCmd('InsertHTML','&#160;&#160;&#160;&#160;');
21195                     this.deferFocus();
21196                 }
21197                 if (String.fromCharCode(k).toLowerCase() == 'v') { // paste
21198                     this.cleanUpPaste.defer(100, this);
21199                     return;
21200                 }
21201                 
21202             };
21203         }else if(Roo.isSafari){
21204             return function(e){
21205                 var k = e.getKey();
21206                 
21207                 if(k == e.TAB){
21208                     e.stopEvent();
21209                     this.execCmd('InsertText','\t');
21210                     this.deferFocus();
21211                     return;
21212                 }
21213                if (String.fromCharCode(k).toLowerCase() == 'v') { // paste
21214                     this.cleanUpPaste.defer(100, this);
21215                     return;
21216                 }
21217                 
21218              };
21219         }
21220     }(),
21221     
21222     getAllAncestors: function()
21223     {
21224         var p = this.getSelectedNode();
21225         var a = [];
21226         if (!p) {
21227             a.push(p); // push blank onto stack..
21228             p = this.getParentElement();
21229         }
21230         
21231         
21232         while (p && (p.nodeType == 1) && (p.tagName.toLowerCase() != 'body')) {
21233             a.push(p);
21234             p = p.parentNode;
21235         }
21236         a.push(this.doc.body);
21237         return a;
21238     },
21239     lastSel : false,
21240     lastSelNode : false,
21241     
21242     
21243     getSelection : function() 
21244     {
21245         this.assignDocWin();
21246         return Roo.isIE ? this.doc.selection : this.win.getSelection();
21247     },
21248     
21249     getSelectedNode: function() 
21250     {
21251         // this may only work on Gecko!!!
21252         
21253         // should we cache this!!!!
21254         
21255         
21256         
21257          
21258         var range = this.createRange(this.getSelection()).cloneRange();
21259         
21260         if (Roo.isIE) {
21261             var parent = range.parentElement();
21262             while (true) {
21263                 var testRange = range.duplicate();
21264                 testRange.moveToElementText(parent);
21265                 if (testRange.inRange(range)) {
21266                     break;
21267                 }
21268                 if ((parent.nodeType != 1) || (parent.tagName.toLowerCase() == 'body')) {
21269                     break;
21270                 }
21271                 parent = parent.parentElement;
21272             }
21273             return parent;
21274         }
21275         
21276         // is ancestor a text element.
21277         var ac =  range.commonAncestorContainer;
21278         if (ac.nodeType == 3) {
21279             ac = ac.parentNode;
21280         }
21281         
21282         var ar = ac.childNodes;
21283          
21284         var nodes = [];
21285         var other_nodes = [];
21286         var has_other_nodes = false;
21287         for (var i=0;i<ar.length;i++) {
21288             if ((ar[i].nodeType == 3) && (!ar[i].data.length)) { // empty text ? 
21289                 continue;
21290             }
21291             // fullly contained node.
21292             
21293             if (this.rangeIntersectsNode(range,ar[i]) && this.rangeCompareNode(range,ar[i]) == 3) {
21294                 nodes.push(ar[i]);
21295                 continue;
21296             }
21297             
21298             // probably selected..
21299             if ((ar[i].nodeType == 1) && this.rangeIntersectsNode(range,ar[i]) && (this.rangeCompareNode(range,ar[i]) > 0)) {
21300                 other_nodes.push(ar[i]);
21301                 continue;
21302             }
21303             // outer..
21304             if (!this.rangeIntersectsNode(range,ar[i])|| (this.rangeCompareNode(range,ar[i]) == 0))  {
21305                 continue;
21306             }
21307             
21308             
21309             has_other_nodes = true;
21310         }
21311         if (!nodes.length && other_nodes.length) {
21312             nodes= other_nodes;
21313         }
21314         if (has_other_nodes || !nodes.length || (nodes.length > 1)) {
21315             return false;
21316         }
21317         
21318         return nodes[0];
21319     },
21320     createRange: function(sel)
21321     {
21322         // this has strange effects when using with 
21323         // top toolbar - not sure if it's a great idea.
21324         //this.editor.contentWindow.focus();
21325         if (typeof sel != "undefined") {
21326             try {
21327                 return sel.getRangeAt ? sel.getRangeAt(0) : sel.createRange();
21328             } catch(e) {
21329                 return this.doc.createRange();
21330             }
21331         } else {
21332             return this.doc.createRange();
21333         }
21334     },
21335     getParentElement: function()
21336     {
21337         
21338         this.assignDocWin();
21339         var sel = Roo.isIE ? this.doc.selection : this.win.getSelection();
21340         
21341         var range = this.createRange(sel);
21342          
21343         try {
21344             var p = range.commonAncestorContainer;
21345             while (p.nodeType == 3) { // text node
21346                 p = p.parentNode;
21347             }
21348             return p;
21349         } catch (e) {
21350             return null;
21351         }
21352     
21353     },
21354     /***
21355      *
21356      * Range intersection.. the hard stuff...
21357      *  '-1' = before
21358      *  '0' = hits..
21359      *  '1' = after.
21360      *         [ -- selected range --- ]
21361      *   [fail]                        [fail]
21362      *
21363      *    basically..
21364      *      if end is before start or  hits it. fail.
21365      *      if start is after end or hits it fail.
21366      *
21367      *   if either hits (but other is outside. - then it's not 
21368      *   
21369      *    
21370      **/
21371     
21372     
21373     // @see http://www.thismuchiknow.co.uk/?p=64.
21374     rangeIntersectsNode : function(range, node)
21375     {
21376         var nodeRange = node.ownerDocument.createRange();
21377         try {
21378             nodeRange.selectNode(node);
21379         } catch (e) {
21380             nodeRange.selectNodeContents(node);
21381         }
21382     
21383         var rangeStartRange = range.cloneRange();
21384         rangeStartRange.collapse(true);
21385     
21386         var rangeEndRange = range.cloneRange();
21387         rangeEndRange.collapse(false);
21388     
21389         var nodeStartRange = nodeRange.cloneRange();
21390         nodeStartRange.collapse(true);
21391     
21392         var nodeEndRange = nodeRange.cloneRange();
21393         nodeEndRange.collapse(false);
21394     
21395         return rangeStartRange.compareBoundaryPoints(
21396                  Range.START_TO_START, nodeEndRange) == -1 &&
21397                rangeEndRange.compareBoundaryPoints(
21398                  Range.START_TO_START, nodeStartRange) == 1;
21399         
21400          
21401     },
21402     rangeCompareNode : function(range, node)
21403     {
21404         var nodeRange = node.ownerDocument.createRange();
21405         try {
21406             nodeRange.selectNode(node);
21407         } catch (e) {
21408             nodeRange.selectNodeContents(node);
21409         }
21410         
21411         
21412         range.collapse(true);
21413     
21414         nodeRange.collapse(true);
21415      
21416         var ss = range.compareBoundaryPoints( Range.START_TO_START, nodeRange);
21417         var ee = range.compareBoundaryPoints(  Range.END_TO_END, nodeRange);
21418          
21419         //Roo.log(node.tagName + ': ss='+ss +', ee='+ee)
21420         
21421         var nodeIsBefore   =  ss == 1;
21422         var nodeIsAfter    = ee == -1;
21423         
21424         if (nodeIsBefore && nodeIsAfter) {
21425             return 0; // outer
21426         }
21427         if (!nodeIsBefore && nodeIsAfter) {
21428             return 1; //right trailed.
21429         }
21430         
21431         if (nodeIsBefore && !nodeIsAfter) {
21432             return 2;  // left trailed.
21433         }
21434         // fully contined.
21435         return 3;
21436     },
21437
21438     // private? - in a new class?
21439     cleanUpPaste :  function()
21440     {
21441         // cleans up the whole document..
21442         Roo.log('cleanuppaste');
21443         
21444         this.cleanUpChildren(this.doc.body);
21445         var clean = this.cleanWordChars(this.doc.body.innerHTML);
21446         if (clean != this.doc.body.innerHTML) {
21447             this.doc.body.innerHTML = clean;
21448         }
21449         
21450     },
21451     
21452     cleanWordChars : function(input) {// change the chars to hex code
21453         var he = Roo.HtmlEditorCore;
21454         
21455         var output = input;
21456         Roo.each(he.swapCodes, function(sw) { 
21457             var swapper = new RegExp("\\u" + sw[0].toString(16), "g"); // hex codes
21458             
21459             output = output.replace(swapper, sw[1]);
21460         });
21461         
21462         return output;
21463     },
21464     
21465     
21466     cleanUpChildren : function (n)
21467     {
21468         if (!n.childNodes.length) {
21469             return;
21470         }
21471         for (var i = n.childNodes.length-1; i > -1 ; i--) {
21472            this.cleanUpChild(n.childNodes[i]);
21473         }
21474     },
21475     
21476     
21477         
21478     
21479     cleanUpChild : function (node)
21480     {
21481         var ed = this;
21482         //console.log(node);
21483         if (node.nodeName == "#text") {
21484             // clean up silly Windows -- stuff?
21485             return; 
21486         }
21487         if (node.nodeName == "#comment") {
21488             node.parentNode.removeChild(node);
21489             // clean up silly Windows -- stuff?
21490             return; 
21491         }
21492         var lcname = node.tagName.toLowerCase();
21493         // we ignore whitelists... ?? = not really the way to go, but we probably have not got a full
21494         // whitelist of tags..
21495         
21496         if (this.black.indexOf(lcname) > -1 && this.clearUp ) {
21497             // remove node.
21498             node.parentNode.removeChild(node);
21499             return;
21500             
21501         }
21502         
21503         var remove_keep_children= Roo.HtmlEditorCore.remove.indexOf(node.tagName.toLowerCase()) > -1;
21504         
21505         // spans with no attributes - just remove them..
21506         if ((!node.attributes || !node.attributes.length) && lcname == 'span') { 
21507             remove_keep_children = true;
21508         }
21509         
21510         // remove <a name=....> as rendering on yahoo mailer is borked with this.
21511         // this will have to be flaged elsewhere - perhaps ablack=name... on the mailer..
21512         
21513         //if (node.tagName.toLowerCase() == 'a' && !node.hasAttribute('href')) {
21514         //    remove_keep_children = true;
21515         //}
21516         
21517         if (remove_keep_children) {
21518             this.cleanUpChildren(node);
21519             // inserts everything just before this node...
21520             while (node.childNodes.length) {
21521                 var cn = node.childNodes[0];
21522                 node.removeChild(cn);
21523                 node.parentNode.insertBefore(cn, node);
21524             }
21525             node.parentNode.removeChild(node);
21526             return;
21527         }
21528         
21529         if (!node.attributes || !node.attributes.length) {
21530             
21531           
21532             
21533             
21534             this.cleanUpChildren(node);
21535             return;
21536         }
21537         
21538         function cleanAttr(n,v)
21539         {
21540             
21541             if (v.match(/^\./) || v.match(/^\//)) {
21542                 return;
21543             }
21544             if (v.match(/^(http|https):\/\//) || v.match(/^mailto:/) || v.match(/^ftp:/)) {
21545                 return;
21546             }
21547             if (v.match(/^#/)) {
21548                 return;
21549             }
21550 //            Roo.log("(REMOVE TAG)"+ node.tagName +'.' + n + '=' + v);
21551             node.removeAttribute(n);
21552             
21553         }
21554         
21555         var cwhite = this.cwhite;
21556         var cblack = this.cblack;
21557             
21558         function cleanStyle(n,v)
21559         {
21560             if (v.match(/expression/)) { //XSS?? should we even bother..
21561                 node.removeAttribute(n);
21562                 return;
21563             }
21564             
21565             var parts = v.split(/;/);
21566             var clean = [];
21567             
21568             Roo.each(parts, function(p) {
21569                 p = p.replace(/^\s+/g,'').replace(/\s+$/g,'');
21570                 if (!p.length) {
21571                     return true;
21572                 }
21573                 var l = p.split(':').shift().replace(/\s+/g,'');
21574                 l = l.replace(/^\s+/g,'').replace(/\s+$/g,'');
21575                 
21576                 if ( cwhite.length && cblack.indexOf(l) > -1) {
21577 //                    Roo.log('(REMOVE CSS)' + node.tagName +'.' + n + ':'+l + '=' + v);
21578                     //node.removeAttribute(n);
21579                     return true;
21580                 }
21581                 //Roo.log()
21582                 // only allow 'c whitelisted system attributes'
21583                 if ( cwhite.length &&  cwhite.indexOf(l) < 0) {
21584 //                    Roo.log('(REMOVE CSS)' + node.tagName +'.' + n + ':'+l + '=' + v);
21585                     //node.removeAttribute(n);
21586                     return true;
21587                 }
21588                 
21589                 
21590                  
21591                 
21592                 clean.push(p);
21593                 return true;
21594             });
21595             if (clean.length) { 
21596                 node.setAttribute(n, clean.join(';'));
21597             } else {
21598                 node.removeAttribute(n);
21599             }
21600             
21601         }
21602         
21603         
21604         for (var i = node.attributes.length-1; i > -1 ; i--) {
21605             var a = node.attributes[i];
21606             //console.log(a);
21607             
21608             if (a.name.toLowerCase().substr(0,2)=='on')  {
21609                 node.removeAttribute(a.name);
21610                 continue;
21611             }
21612             if (Roo.HtmlEditorCore.ablack.indexOf(a.name.toLowerCase()) > -1) {
21613                 node.removeAttribute(a.name);
21614                 continue;
21615             }
21616             if (Roo.HtmlEditorCore.aclean.indexOf(a.name.toLowerCase()) > -1) {
21617                 cleanAttr(a.name,a.value); // fixme..
21618                 continue;
21619             }
21620             if (a.name == 'style') {
21621                 cleanStyle(a.name,a.value);
21622                 continue;
21623             }
21624             /// clean up MS crap..
21625             // tecnically this should be a list of valid class'es..
21626             
21627             
21628             if (a.name == 'class') {
21629                 if (a.value.match(/^Mso/)) {
21630                     node.removeAttribute('class');
21631                 }
21632                 
21633                 if (a.value.match(/^body$/)) {
21634                     node.removeAttribute('class');
21635                 }
21636                 continue;
21637             }
21638             
21639             // style cleanup!?
21640             // class cleanup?
21641             
21642         }
21643         
21644         
21645         this.cleanUpChildren(node);
21646         
21647         
21648     },
21649     
21650     /**
21651      * Clean up MS wordisms...
21652      */
21653     cleanWord : function(node)
21654     {
21655         if (!node) {
21656             this.cleanWord(this.doc.body);
21657             return;
21658         }
21659         
21660         if(
21661                 node.nodeName == 'SPAN' &&
21662                 !node.hasAttributes() &&
21663                 node.childNodes.length == 1 &&
21664                 node.firstChild.nodeName == "#text"  
21665         ) {
21666             var textNode = node.firstChild;
21667             node.removeChild(textNode);
21668             if (node.getAttribute('lang') != 'zh-CN') {   // do not space pad on chinese characters..
21669                 node.parentNode.insertBefore(node.ownerDocument.createTextNode(" "), node);
21670             }
21671             node.parentNode.insertBefore(textNode, node);
21672             if (node.getAttribute('lang') != 'zh-CN') {   // do not space pad on chinese characters..
21673                 node.parentNode.insertBefore(node.ownerDocument.createTextNode(" ") , node);
21674             }
21675             node.parentNode.removeChild(node);
21676         }
21677         
21678         if (node.nodeName == "#text") {
21679             // clean up silly Windows -- stuff?
21680             return; 
21681         }
21682         if (node.nodeName == "#comment") {
21683             node.parentNode.removeChild(node);
21684             // clean up silly Windows -- stuff?
21685             return; 
21686         }
21687         
21688         if (node.tagName.toLowerCase().match(/^(style|script|applet|embed|noframes|noscript)$/)) {
21689             node.parentNode.removeChild(node);
21690             return;
21691         }
21692         Roo.log(node.tagName);
21693         // remove - but keep children..
21694         if (node.tagName.toLowerCase().match(/^(meta|link|\\?xml:|st1:|o:|v:|font)/)) {
21695             while (node.childNodes.length) {
21696                 var cn = node.childNodes[0];
21697                 node.removeChild(cn);
21698                 node.parentNode.insertBefore(cn, node);
21699             }
21700             node.parentNode.removeChild(node);
21701             /// no need to iterate chidlren = it's got none..
21702             //this.iterateChildren(node, this.cleanWord);
21703             return;
21704         }
21705         // clean styles
21706         if (node.className.length) {
21707             
21708             var cn = node.className.split(/\W+/);
21709             var cna = [];
21710             Roo.each(cn, function(cls) {
21711                 if (cls.match(/Mso[a-zA-Z]+/)) {
21712                     return;
21713                 }
21714                 cna.push(cls);
21715             });
21716             node.className = cna.length ? cna.join(' ') : '';
21717             if (!cna.length) {
21718                 node.removeAttribute("class");
21719             }
21720         }
21721         
21722         if (node.hasAttribute("lang")) {
21723             node.removeAttribute("lang");
21724         }
21725         
21726         if (node.hasAttribute("style")) {
21727             
21728             var styles = node.getAttribute("style").split(";");
21729             var nstyle = [];
21730             Roo.each(styles, function(s) {
21731                 if (!s.match(/:/)) {
21732                     return;
21733                 }
21734                 var kv = s.split(":");
21735                 if (kv[0].match(/^(mso-|line|font|background|margin|padding|color)/)) {
21736                     return;
21737                 }
21738                 // what ever is left... we allow.
21739                 nstyle.push(s);
21740             });
21741             node.setAttribute("style", nstyle.length ? nstyle.join(';') : '');
21742             if (!nstyle.length) {
21743                 node.removeAttribute('style');
21744             }
21745         }
21746         this.iterateChildren(node, this.cleanWord);
21747         
21748         
21749         
21750     },
21751     /**
21752      * iterateChildren of a Node, calling fn each time, using this as the scole..
21753      * @param {DomNode} node node to iterate children of.
21754      * @param {Function} fn method of this class to call on each item.
21755      */
21756     iterateChildren : function(node, fn)
21757     {
21758         if (!node.childNodes.length) {
21759                 return;
21760         }
21761         for (var i = node.childNodes.length-1; i > -1 ; i--) {
21762            fn.call(this, node.childNodes[i])
21763         }
21764     },
21765     
21766     
21767     /**
21768      * cleanTableWidths.
21769      *
21770      * Quite often pasting from word etc.. results in tables with column and widths.
21771      * This does not work well on fluid HTML layouts - like emails. - so this code should hunt an destroy them..
21772      *
21773      */
21774     cleanTableWidths : function(node)
21775     {
21776          
21777          
21778         if (!node) {
21779             this.cleanTableWidths(this.doc.body);
21780             return;
21781         }
21782         
21783         // ignore list...
21784         if (node.nodeName == "#text" || node.nodeName == "#comment") {
21785             return; 
21786         }
21787         Roo.log(node.tagName);
21788         if (!node.tagName.toLowerCase().match(/^(table|td|tr)$/)) {
21789             this.iterateChildren(node, this.cleanTableWidths);
21790             return;
21791         }
21792         if (node.hasAttribute('width')) {
21793             node.removeAttribute('width');
21794         }
21795         
21796          
21797         if (node.hasAttribute("style")) {
21798             // pretty basic...
21799             
21800             var styles = node.getAttribute("style").split(";");
21801             var nstyle = [];
21802             Roo.each(styles, function(s) {
21803                 if (!s.match(/:/)) {
21804                     return;
21805                 }
21806                 var kv = s.split(":");
21807                 if (kv[0].match(/^\s*(width|min-width)\s*$/)) {
21808                     return;
21809                 }
21810                 // what ever is left... we allow.
21811                 nstyle.push(s);
21812             });
21813             node.setAttribute("style", nstyle.length ? nstyle.join(';') : '');
21814             if (!nstyle.length) {
21815                 node.removeAttribute('style');
21816             }
21817         }
21818         
21819         this.iterateChildren(node, this.cleanTableWidths);
21820         
21821         
21822     },
21823     
21824     
21825     
21826     
21827     domToHTML : function(currentElement, depth, nopadtext) {
21828         
21829         depth = depth || 0;
21830         nopadtext = nopadtext || false;
21831     
21832         if (!currentElement) {
21833             return this.domToHTML(this.doc.body);
21834         }
21835         
21836         //Roo.log(currentElement);
21837         var j;
21838         var allText = false;
21839         var nodeName = currentElement.nodeName;
21840         var tagName = Roo.util.Format.htmlEncode(currentElement.tagName);
21841         
21842         if  (nodeName == '#text') {
21843             
21844             return nopadtext ? currentElement.nodeValue : currentElement.nodeValue.trim();
21845         }
21846         
21847         
21848         var ret = '';
21849         if (nodeName != 'BODY') {
21850              
21851             var i = 0;
21852             // Prints the node tagName, such as <A>, <IMG>, etc
21853             if (tagName) {
21854                 var attr = [];
21855                 for(i = 0; i < currentElement.attributes.length;i++) {
21856                     // quoting?
21857                     var aname = currentElement.attributes.item(i).name;
21858                     if (!currentElement.attributes.item(i).value.length) {
21859                         continue;
21860                     }
21861                     attr.push(aname + '="' + Roo.util.Format.htmlEncode(currentElement.attributes.item(i).value) + '"' );
21862                 }
21863                 
21864                 ret = "<"+currentElement.tagName+ ( attr.length ? (' ' + attr.join(' ') ) : '') + ">";
21865             } 
21866             else {
21867                 
21868                 // eack
21869             }
21870         } else {
21871             tagName = false;
21872         }
21873         if (['IMG', 'BR', 'HR', 'INPUT'].indexOf(tagName) > -1) {
21874             return ret;
21875         }
21876         if (['PRE', 'TEXTAREA', 'TD', 'A', 'SPAN'].indexOf(tagName) > -1) { // or code?
21877             nopadtext = true;
21878         }
21879         
21880         
21881         // Traverse the tree
21882         i = 0;
21883         var currentElementChild = currentElement.childNodes.item(i);
21884         var allText = true;
21885         var innerHTML  = '';
21886         lastnode = '';
21887         while (currentElementChild) {
21888             // Formatting code (indent the tree so it looks nice on the screen)
21889             var nopad = nopadtext;
21890             if (lastnode == 'SPAN') {
21891                 nopad  = true;
21892             }
21893             // text
21894             if  (currentElementChild.nodeName == '#text') {
21895                 var toadd = Roo.util.Format.htmlEncode(currentElementChild.nodeValue);
21896                 toadd = nopadtext ? toadd : toadd.trim();
21897                 if (!nopad && toadd.length > 80) {
21898                     innerHTML  += "\n" + (new Array( depth + 1 )).join( "  "  );
21899                 }
21900                 innerHTML  += toadd;
21901                 
21902                 i++;
21903                 currentElementChild = currentElement.childNodes.item(i);
21904                 lastNode = '';
21905                 continue;
21906             }
21907             allText = false;
21908             
21909             innerHTML  += nopad ? '' : "\n" + (new Array( depth + 1 )).join( "  "  );
21910                 
21911             // Recursively traverse the tree structure of the child node
21912             innerHTML   += this.domToHTML(currentElementChild, depth+1, nopadtext);
21913             lastnode = currentElementChild.nodeName;
21914             i++;
21915             currentElementChild=currentElement.childNodes.item(i);
21916         }
21917         
21918         ret += innerHTML;
21919         
21920         if (!allText) {
21921                 // The remaining code is mostly for formatting the tree
21922             ret+= nopadtext ? '' : "\n" + (new Array( depth  )).join( "  "  );
21923         }
21924         
21925         
21926         if (tagName) {
21927             ret+= "</"+tagName+">";
21928         }
21929         return ret;
21930         
21931     },
21932         
21933     applyBlacklists : function()
21934     {
21935         var w = typeof(this.owner.white) != 'undefined' && this.owner.white ? this.owner.white  : [];
21936         var b = typeof(this.owner.black) != 'undefined' && this.owner.black ? this.owner.black :  [];
21937         
21938         this.white = [];
21939         this.black = [];
21940         Roo.each(Roo.HtmlEditorCore.white, function(tag) {
21941             if (b.indexOf(tag) > -1) {
21942                 return;
21943             }
21944             this.white.push(tag);
21945             
21946         }, this);
21947         
21948         Roo.each(w, function(tag) {
21949             if (b.indexOf(tag) > -1) {
21950                 return;
21951             }
21952             if (this.white.indexOf(tag) > -1) {
21953                 return;
21954             }
21955             this.white.push(tag);
21956             
21957         }, this);
21958         
21959         
21960         Roo.each(Roo.HtmlEditorCore.black, function(tag) {
21961             if (w.indexOf(tag) > -1) {
21962                 return;
21963             }
21964             this.black.push(tag);
21965             
21966         }, this);
21967         
21968         Roo.each(b, function(tag) {
21969             if (w.indexOf(tag) > -1) {
21970                 return;
21971             }
21972             if (this.black.indexOf(tag) > -1) {
21973                 return;
21974             }
21975             this.black.push(tag);
21976             
21977         }, this);
21978         
21979         
21980         w = typeof(this.owner.cwhite) != 'undefined' && this.owner.cwhite ? this.owner.cwhite  : [];
21981         b = typeof(this.owner.cblack) != 'undefined' && this.owner.cblack ? this.owner.cblack :  [];
21982         
21983         this.cwhite = [];
21984         this.cblack = [];
21985         Roo.each(Roo.HtmlEditorCore.cwhite, function(tag) {
21986             if (b.indexOf(tag) > -1) {
21987                 return;
21988             }
21989             this.cwhite.push(tag);
21990             
21991         }, this);
21992         
21993         Roo.each(w, function(tag) {
21994             if (b.indexOf(tag) > -1) {
21995                 return;
21996             }
21997             if (this.cwhite.indexOf(tag) > -1) {
21998                 return;
21999             }
22000             this.cwhite.push(tag);
22001             
22002         }, this);
22003         
22004         
22005         Roo.each(Roo.HtmlEditorCore.cblack, function(tag) {
22006             if (w.indexOf(tag) > -1) {
22007                 return;
22008             }
22009             this.cblack.push(tag);
22010             
22011         }, this);
22012         
22013         Roo.each(b, function(tag) {
22014             if (w.indexOf(tag) > -1) {
22015                 return;
22016             }
22017             if (this.cblack.indexOf(tag) > -1) {
22018                 return;
22019             }
22020             this.cblack.push(tag);
22021             
22022         }, this);
22023     },
22024     
22025     setStylesheets : function(stylesheets)
22026     {
22027         if(typeof(stylesheets) == 'string'){
22028             Roo.get(this.iframe.contentDocument.head).createChild({
22029                 tag : 'link',
22030                 rel : 'stylesheet',
22031                 type : 'text/css',
22032                 href : stylesheets
22033             });
22034             
22035             return;
22036         }
22037         var _this = this;
22038      
22039         Roo.each(stylesheets, function(s) {
22040             if(!s.length){
22041                 return;
22042             }
22043             
22044             Roo.get(_this.iframe.contentDocument.head).createChild({
22045                 tag : 'link',
22046                 rel : 'stylesheet',
22047                 type : 'text/css',
22048                 href : s
22049             });
22050         });
22051
22052         
22053     },
22054     
22055     removeStylesheets : function()
22056     {
22057         var _this = this;
22058         
22059         Roo.each(Roo.get(_this.iframe.contentDocument.head).select('link[rel=stylesheet]', true).elements, function(s){
22060             s.remove();
22061         });
22062     },
22063     
22064     setStyle : function(style)
22065     {
22066         Roo.get(this.iframe.contentDocument.head).createChild({
22067             tag : 'style',
22068             type : 'text/css',
22069             html : style
22070         });
22071
22072         return;
22073     }
22074     
22075     // hide stuff that is not compatible
22076     /**
22077      * @event blur
22078      * @hide
22079      */
22080     /**
22081      * @event change
22082      * @hide
22083      */
22084     /**
22085      * @event focus
22086      * @hide
22087      */
22088     /**
22089      * @event specialkey
22090      * @hide
22091      */
22092     /**
22093      * @cfg {String} fieldClass @hide
22094      */
22095     /**
22096      * @cfg {String} focusClass @hide
22097      */
22098     /**
22099      * @cfg {String} autoCreate @hide
22100      */
22101     /**
22102      * @cfg {String} inputType @hide
22103      */
22104     /**
22105      * @cfg {String} invalidClass @hide
22106      */
22107     /**
22108      * @cfg {String} invalidText @hide
22109      */
22110     /**
22111      * @cfg {String} msgFx @hide
22112      */
22113     /**
22114      * @cfg {String} validateOnBlur @hide
22115      */
22116 });
22117
22118 Roo.HtmlEditorCore.white = [
22119         'area', 'br', 'img', 'input', 'hr', 'wbr',
22120         
22121        'address', 'blockquote', 'center', 'dd',      'dir',       'div', 
22122        'dl',      'dt',         'h1',     'h2',      'h3',        'h4', 
22123        'h5',      'h6',         'hr',     'isindex', 'listing',   'marquee', 
22124        'menu',    'multicol',   'ol',     'p',       'plaintext', 'pre', 
22125        'table',   'ul',         'xmp', 
22126        
22127        'caption', 'col', 'colgroup', 'tbody', 'td', 'tfoot', 'th', 
22128       'thead',   'tr', 
22129      
22130       'dir', 'menu', 'ol', 'ul', 'dl',
22131        
22132       'embed',  'object'
22133 ];
22134
22135
22136 Roo.HtmlEditorCore.black = [
22137     //    'embed',  'object', // enable - backend responsiblity to clean thiese
22138         'applet', // 
22139         'base',   'basefont', 'bgsound', 'blink',  'body', 
22140         'frame',  'frameset', 'head',    'html',   'ilayer', 
22141         'iframe', 'layer',  'link',     'meta',    'object',   
22142         'script', 'style' ,'title',  'xml' // clean later..
22143 ];
22144 Roo.HtmlEditorCore.clean = [
22145     'script', 'style', 'title', 'xml'
22146 ];
22147 Roo.HtmlEditorCore.remove = [
22148     'font'
22149 ];
22150 // attributes..
22151
22152 Roo.HtmlEditorCore.ablack = [
22153     'on'
22154 ];
22155     
22156 Roo.HtmlEditorCore.aclean = [ 
22157     'action', 'background', 'codebase', 'dynsrc', 'href', 'lowsrc' 
22158 ];
22159
22160 // protocols..
22161 Roo.HtmlEditorCore.pwhite= [
22162         'http',  'https',  'mailto'
22163 ];
22164
22165 // white listed style attributes.
22166 Roo.HtmlEditorCore.cwhite= [
22167       //  'text-align', /// default is to allow most things..
22168       
22169          
22170 //        'font-size'//??
22171 ];
22172
22173 // black listed style attributes.
22174 Roo.HtmlEditorCore.cblack= [
22175       //  'font-size' -- this can be set by the project 
22176 ];
22177
22178
22179 Roo.HtmlEditorCore.swapCodes   =[ 
22180     [    8211, "--" ], 
22181     [    8212, "--" ], 
22182     [    8216,  "'" ],  
22183     [    8217, "'" ],  
22184     [    8220, '"' ],  
22185     [    8221, '"' ],  
22186     [    8226, "*" ],  
22187     [    8230, "..." ]
22188 ]; 
22189
22190     //<script type="text/javascript">
22191
22192 /*
22193  * Ext JS Library 1.1.1
22194  * Copyright(c) 2006-2007, Ext JS, LLC.
22195  * Licence LGPL
22196  * 
22197  */
22198  
22199  
22200 Roo.form.HtmlEditor = function(config){
22201     
22202     
22203     
22204     Roo.form.HtmlEditor.superclass.constructor.call(this, config);
22205     
22206     if (!this.toolbars) {
22207         this.toolbars = [];
22208     }
22209     this.editorcore = new Roo.HtmlEditorCore(Roo.apply({ owner : this} , config));
22210     
22211     
22212 };
22213
22214 /**
22215  * @class Roo.form.HtmlEditor
22216  * @extends Roo.form.Field
22217  * Provides a lightweight HTML Editor component.
22218  *
22219  * This has been tested on Fireforx / Chrome.. IE may not be so great..
22220  * 
22221  * <br><br><b>Note: The focus/blur and validation marking functionality inherited from Ext.form.Field is NOT
22222  * supported by this editor.</b><br/><br/>
22223  * An Editor is a sensitive component that can't be used in all spots standard fields can be used. Putting an Editor within
22224  * any element that has display set to 'none' can cause problems in Safari and Firefox.<br/><br/>
22225  */
22226 Roo.extend(Roo.form.HtmlEditor, Roo.form.Field, {
22227     /**
22228      * @cfg {Boolean} clearUp
22229      */
22230     clearUp : true,
22231       /**
22232      * @cfg {Array} toolbars Array of toolbars. - defaults to just the Standard one
22233      */
22234     toolbars : false,
22235    
22236      /**
22237      * @cfg {String} resizable  's' or 'se' or 'e' - wrapps the element in a
22238      *                        Roo.resizable.
22239      */
22240     resizable : false,
22241      /**
22242      * @cfg {Number} height (in pixels)
22243      */   
22244     height: 300,
22245    /**
22246      * @cfg {Number} width (in pixels)
22247      */   
22248     width: 500,
22249     
22250     /**
22251      * @cfg {Array} stylesheets url of stylesheets. set to [] to disable stylesheets.
22252      * 
22253      */
22254     stylesheets: false,
22255     
22256     
22257      /**
22258      * @cfg {Array} blacklist of css styles style attributes (blacklist overrides whitelist)
22259      * 
22260      */
22261     cblack: false,
22262     /**
22263      * @cfg {Array} whitelist of css styles style attributes (blacklist overrides whitelist)
22264      * 
22265      */
22266     cwhite: false,
22267     
22268      /**
22269      * @cfg {Array} blacklist of html tags - in addition to standard blacklist.
22270      * 
22271      */
22272     black: false,
22273     /**
22274      * @cfg {Array} whitelist of html tags - in addition to statndard whitelist
22275      * 
22276      */
22277     white: false,
22278     
22279     // id of frame..
22280     frameId: false,
22281     
22282     // private properties
22283     validationEvent : false,
22284     deferHeight: true,
22285     initialized : false,
22286     activated : false,
22287     
22288     onFocus : Roo.emptyFn,
22289     iframePad:3,
22290     hideMode:'offsets',
22291     
22292     actionMode : 'container', // defaults to hiding it...
22293     
22294     defaultAutoCreate : { // modified by initCompnoent..
22295         tag: "textarea",
22296         style:"width:500px;height:300px;",
22297         autocomplete: "new-password"
22298     },
22299
22300     // private
22301     initComponent : function(){
22302         this.addEvents({
22303             /**
22304              * @event initialize
22305              * Fires when the editor is fully initialized (including the iframe)
22306              * @param {HtmlEditor} this
22307              */
22308             initialize: true,
22309             /**
22310              * @event activate
22311              * Fires when the editor is first receives the focus. Any insertion must wait
22312              * until after this event.
22313              * @param {HtmlEditor} this
22314              */
22315             activate: true,
22316              /**
22317              * @event beforesync
22318              * Fires before the textarea is updated with content from the editor iframe. Return false
22319              * to cancel the sync.
22320              * @param {HtmlEditor} this
22321              * @param {String} html
22322              */
22323             beforesync: true,
22324              /**
22325              * @event beforepush
22326              * Fires before the iframe editor is updated with content from the textarea. Return false
22327              * to cancel the push.
22328              * @param {HtmlEditor} this
22329              * @param {String} html
22330              */
22331             beforepush: true,
22332              /**
22333              * @event sync
22334              * Fires when the textarea is updated with content from the editor iframe.
22335              * @param {HtmlEditor} this
22336              * @param {String} html
22337              */
22338             sync: true,
22339              /**
22340              * @event push
22341              * Fires when the iframe editor is updated with content from the textarea.
22342              * @param {HtmlEditor} this
22343              * @param {String} html
22344              */
22345             push: true,
22346              /**
22347              * @event editmodechange
22348              * Fires when the editor switches edit modes
22349              * @param {HtmlEditor} this
22350              * @param {Boolean} sourceEdit True if source edit, false if standard editing.
22351              */
22352             editmodechange: true,
22353             /**
22354              * @event editorevent
22355              * Fires when on any editor (mouse up/down cursor movement etc.) - used for toolbar hooks.
22356              * @param {HtmlEditor} this
22357              */
22358             editorevent: true,
22359             /**
22360              * @event firstfocus
22361              * Fires when on first focus - needed by toolbars..
22362              * @param {HtmlEditor} this
22363              */
22364             firstfocus: true,
22365             /**
22366              * @event autosave
22367              * Auto save the htmlEditor value as a file into Events
22368              * @param {HtmlEditor} this
22369              */
22370             autosave: true,
22371             /**
22372              * @event savedpreview
22373              * preview the saved version of htmlEditor
22374              * @param {HtmlEditor} this
22375              */
22376             savedpreview: true,
22377             
22378             /**
22379             * @event stylesheetsclick
22380             * Fires when press the Sytlesheets button
22381             * @param {Roo.HtmlEditorCore} this
22382             */
22383             stylesheetsclick: true
22384         });
22385         this.defaultAutoCreate =  {
22386             tag: "textarea",
22387             style:'width: ' + this.width + 'px;height: ' + this.height + 'px;',
22388             autocomplete: "new-password"
22389         };
22390     },
22391
22392     /**
22393      * Protected method that will not generally be called directly. It
22394      * is called when the editor creates its toolbar. Override this method if you need to
22395      * add custom toolbar buttons.
22396      * @param {HtmlEditor} editor
22397      */
22398     createToolbar : function(editor){
22399         Roo.log("create toolbars");
22400         if (!editor.toolbars || !editor.toolbars.length) {
22401             editor.toolbars = [ new Roo.form.HtmlEditor.ToolbarStandard() ]; // can be empty?
22402         }
22403         
22404         for (var i =0 ; i < editor.toolbars.length;i++) {
22405             editor.toolbars[i] = Roo.factory(
22406                     typeof(editor.toolbars[i]) == 'string' ?
22407                         { xtype: editor.toolbars[i]} : editor.toolbars[i],
22408                 Roo.form.HtmlEditor);
22409             editor.toolbars[i].init(editor);
22410         }
22411          
22412         
22413     },
22414
22415      
22416     // private
22417     onRender : function(ct, position)
22418     {
22419         var _t = this;
22420         Roo.form.HtmlEditor.superclass.onRender.call(this, ct, position);
22421         
22422         this.wrap = this.el.wrap({
22423             cls:'x-html-editor-wrap', cn:{cls:'x-html-editor-tb'}
22424         });
22425         
22426         this.editorcore.onRender(ct, position);
22427          
22428         if (this.resizable) {
22429             this.resizeEl = new Roo.Resizable(this.wrap, {
22430                 pinned : true,
22431                 wrap: true,
22432                 dynamic : true,
22433                 minHeight : this.height,
22434                 height: this.height,
22435                 handles : this.resizable,
22436                 width: this.width,
22437                 listeners : {
22438                     resize : function(r, w, h) {
22439                         _t.onResize(w,h); // -something
22440                     }
22441                 }
22442             });
22443             
22444         }
22445         this.createToolbar(this);
22446        
22447         
22448         if(!this.width){
22449             this.setSize(this.wrap.getSize());
22450         }
22451         if (this.resizeEl) {
22452             this.resizeEl.resizeTo.defer(100, this.resizeEl,[ this.width,this.height ] );
22453             // should trigger onReize..
22454         }
22455         
22456         this.keyNav = new Roo.KeyNav(this.el, {
22457             
22458             "tab" : function(e){
22459                 e.preventDefault();
22460                 
22461                 var value = this.getValue();
22462                 
22463                 var start = this.el.dom.selectionStart;
22464                 var end = this.el.dom.selectionEnd;
22465                 
22466                 if(!e.shiftKey){
22467                     
22468                     this.setValue(value.substring(0, start) + "\t" + value.substring(end));
22469                     this.el.dom.setSelectionRange(end + 1, end + 1);
22470                     return;
22471                 }
22472                 
22473                 var f = value.substring(0, start).split("\t");
22474                 
22475                 if(f.pop().length != 0){
22476                     return;
22477                 }
22478                 
22479                 this.setValue(f.join("\t") + value.substring(end));
22480                 this.el.dom.setSelectionRange(start - 1, start - 1);
22481                 
22482             },
22483             
22484             "home" : function(e){
22485                 e.preventDefault();
22486                 
22487                 var curr = this.el.dom.selectionStart;
22488                 var lines = this.getValue().split("\n");
22489                 
22490                 if(!lines.length){
22491                     return;
22492                 }
22493                 
22494                 if(e.ctrlKey){
22495                     this.el.dom.setSelectionRange(0, 0);
22496                     return;
22497                 }
22498                 
22499                 var pos = 0;
22500                 
22501                 for (var i = 0; i < lines.length;i++) {
22502                     pos += lines[i].length;
22503                     
22504                     if(i != 0){
22505                         pos += 1;
22506                     }
22507                     
22508                     if(pos < curr){
22509                         continue;
22510                     }
22511                     
22512                     pos -= lines[i].length;
22513                     
22514                     break;
22515                 }
22516                 
22517                 if(!e.shiftKey){
22518                     this.el.dom.setSelectionRange(pos, pos);
22519                     return;
22520                 }
22521                 
22522                 this.el.dom.selectionStart = pos;
22523                 this.el.dom.selectionEnd = curr;
22524             },
22525             
22526             "end" : function(e){
22527                 e.preventDefault();
22528                 
22529                 var curr = this.el.dom.selectionStart;
22530                 var lines = this.getValue().split("\n");
22531                 
22532                 if(!lines.length){
22533                     return;
22534                 }
22535                 
22536                 if(e.ctrlKey){
22537                     this.el.dom.setSelectionRange(this.getValue().length, this.getValue().length);
22538                     return;
22539                 }
22540                 
22541                 var pos = 0;
22542                 
22543                 for (var i = 0; i < lines.length;i++) {
22544                     
22545                     pos += lines[i].length;
22546                     
22547                     if(i != 0){
22548                         pos += 1;
22549                     }
22550                     
22551                     if(pos < curr){
22552                         continue;
22553                     }
22554                     
22555                     break;
22556                 }
22557                 
22558                 if(!e.shiftKey){
22559                     this.el.dom.setSelectionRange(pos, pos);
22560                     return;
22561                 }
22562                 
22563                 this.el.dom.selectionStart = curr;
22564                 this.el.dom.selectionEnd = pos;
22565             },
22566
22567             scope : this,
22568
22569             doRelay : function(foo, bar, hname){
22570                 return Roo.KeyNav.prototype.doRelay.apply(this, arguments);
22571             },
22572
22573             forceKeyDown: true
22574         });
22575         
22576 //        if(this.autosave && this.w){
22577 //            this.autoSaveFn = setInterval(this.autosave, 1000);
22578 //        }
22579     },
22580
22581     // private
22582     onResize : function(w, h)
22583     {
22584         Roo.form.HtmlEditor.superclass.onResize.apply(this, arguments);
22585         var ew = false;
22586         var eh = false;
22587         
22588         if(this.el ){
22589             if(typeof w == 'number'){
22590                 var aw = w - this.wrap.getFrameWidth('lr');
22591                 this.el.setWidth(this.adjustWidth('textarea', aw));
22592                 ew = aw;
22593             }
22594             if(typeof h == 'number'){
22595                 var tbh = 0;
22596                 for (var i =0; i < this.toolbars.length;i++) {
22597                     // fixme - ask toolbars for heights?
22598                     tbh += this.toolbars[i].tb.el.getHeight();
22599                     if (this.toolbars[i].footer) {
22600                         tbh += this.toolbars[i].footer.el.getHeight();
22601                     }
22602                 }
22603                 
22604                 
22605                 
22606                 
22607                 var ah = h - this.wrap.getFrameWidth('tb') - tbh;// this.tb.el.getHeight();
22608                 ah -= 5; // knock a few pixes off for look..
22609 //                Roo.log(ah);
22610                 this.el.setHeight(this.adjustWidth('textarea', ah));
22611                 var eh = ah;
22612             }
22613         }
22614         Roo.log('onResize:' + [w,h,ew,eh].join(',') );
22615         this.editorcore.onResize(ew,eh);
22616         
22617     },
22618
22619     /**
22620      * Toggles the editor between standard and source edit mode.
22621      * @param {Boolean} sourceEdit (optional) True for source edit, false for standard
22622      */
22623     toggleSourceEdit : function(sourceEditMode)
22624     {
22625         this.editorcore.toggleSourceEdit(sourceEditMode);
22626         
22627         if(this.editorcore.sourceEditMode){
22628             Roo.log('editor - showing textarea');
22629             
22630 //            Roo.log('in');
22631 //            Roo.log(this.syncValue());
22632             this.editorcore.syncValue();
22633             this.el.removeClass('x-hidden');
22634             this.el.dom.removeAttribute('tabIndex');
22635             this.el.focus();
22636             
22637             for (var i = 0; i < this.toolbars.length; i++) {
22638                 if(this.toolbars[i] instanceof Roo.form.HtmlEditor.ToolbarContext){
22639                     this.toolbars[i].tb.hide();
22640                     this.toolbars[i].footer.hide();
22641                 }
22642             }
22643             
22644         }else{
22645             Roo.log('editor - hiding textarea');
22646 //            Roo.log('out')
22647 //            Roo.log(this.pushValue()); 
22648             this.editorcore.pushValue();
22649             
22650             this.el.addClass('x-hidden');
22651             this.el.dom.setAttribute('tabIndex', -1);
22652             
22653             for (var i = 0; i < this.toolbars.length; i++) {
22654                 if(this.toolbars[i] instanceof Roo.form.HtmlEditor.ToolbarContext){
22655                     this.toolbars[i].tb.show();
22656                     this.toolbars[i].footer.show();
22657                 }
22658             }
22659             
22660             //this.deferFocus();
22661         }
22662         
22663         this.setSize(this.wrap.getSize());
22664         this.onResize(this.wrap.getSize().width, this.wrap.getSize().height);
22665         
22666         this.fireEvent('editmodechange', this, this.editorcore.sourceEditMode);
22667     },
22668  
22669     // private (for BoxComponent)
22670     adjustSize : Roo.BoxComponent.prototype.adjustSize,
22671
22672     // private (for BoxComponent)
22673     getResizeEl : function(){
22674         return this.wrap;
22675     },
22676
22677     // private (for BoxComponent)
22678     getPositionEl : function(){
22679         return this.wrap;
22680     },
22681
22682     // private
22683     initEvents : function(){
22684         this.originalValue = this.getValue();
22685     },
22686
22687     /**
22688      * Overridden and disabled. The editor element does not support standard valid/invalid marking. @hide
22689      * @method
22690      */
22691     markInvalid : Roo.emptyFn,
22692     /**
22693      * Overridden and disabled. The editor element does not support standard valid/invalid marking. @hide
22694      * @method
22695      */
22696     clearInvalid : Roo.emptyFn,
22697
22698     setValue : function(v){
22699         Roo.form.HtmlEditor.superclass.setValue.call(this, v);
22700         this.editorcore.pushValue();
22701     },
22702
22703      
22704     // private
22705     deferFocus : function(){
22706         this.focus.defer(10, this);
22707     },
22708
22709     // doc'ed in Field
22710     focus : function(){
22711         this.editorcore.focus();
22712         
22713     },
22714       
22715
22716     // private
22717     onDestroy : function(){
22718         
22719         
22720         
22721         if(this.rendered){
22722             
22723             for (var i =0; i < this.toolbars.length;i++) {
22724                 // fixme - ask toolbars for heights?
22725                 this.toolbars[i].onDestroy();
22726             }
22727             
22728             this.wrap.dom.innerHTML = '';
22729             this.wrap.remove();
22730         }
22731     },
22732
22733     // private
22734     onFirstFocus : function(){
22735         //Roo.log("onFirstFocus");
22736         this.editorcore.onFirstFocus();
22737          for (var i =0; i < this.toolbars.length;i++) {
22738             this.toolbars[i].onFirstFocus();
22739         }
22740         
22741     },
22742     
22743     // private
22744     syncValue : function()
22745     {
22746         this.editorcore.syncValue();
22747     },
22748     
22749     pushValue : function()
22750     {
22751         this.editorcore.pushValue();
22752     },
22753     
22754     setStylesheets : function(stylesheets)
22755     {
22756         this.editorcore.setStylesheets(stylesheets);
22757     },
22758     
22759     removeStylesheets : function()
22760     {
22761         this.editorcore.removeStylesheets();
22762     }
22763      
22764     
22765     // hide stuff that is not compatible
22766     /**
22767      * @event blur
22768      * @hide
22769      */
22770     /**
22771      * @event change
22772      * @hide
22773      */
22774     /**
22775      * @event focus
22776      * @hide
22777      */
22778     /**
22779      * @event specialkey
22780      * @hide
22781      */
22782     /**
22783      * @cfg {String} fieldClass @hide
22784      */
22785     /**
22786      * @cfg {String} focusClass @hide
22787      */
22788     /**
22789      * @cfg {String} autoCreate @hide
22790      */
22791     /**
22792      * @cfg {String} inputType @hide
22793      */
22794     /**
22795      * @cfg {String} invalidClass @hide
22796      */
22797     /**
22798      * @cfg {String} invalidText @hide
22799      */
22800     /**
22801      * @cfg {String} msgFx @hide
22802      */
22803     /**
22804      * @cfg {String} validateOnBlur @hide
22805      */
22806 });
22807  
22808     // <script type="text/javascript">
22809 /*
22810  * Based on
22811  * Ext JS Library 1.1.1
22812  * Copyright(c) 2006-2007, Ext JS, LLC.
22813  *  
22814  
22815  */
22816
22817 /**
22818  * @class Roo.form.HtmlEditorToolbar1
22819  * Basic Toolbar
22820  * 
22821  * Usage:
22822  *
22823  new Roo.form.HtmlEditor({
22824     ....
22825     toolbars : [
22826         new Roo.form.HtmlEditorToolbar1({
22827             disable : { fonts: 1 , format: 1, ..., ... , ...],
22828             btns : [ .... ]
22829         })
22830     }
22831      
22832  * 
22833  * @cfg {Object} disable List of elements to disable..
22834  * @cfg {Array} btns List of additional buttons.
22835  * 
22836  * 
22837  * NEEDS Extra CSS? 
22838  * .x-html-editor-tb .x-edit-none .x-btn-text { background: none; }
22839  */
22840  
22841 Roo.form.HtmlEditor.ToolbarStandard = function(config)
22842 {
22843     
22844     Roo.apply(this, config);
22845     
22846     // default disabled, based on 'good practice'..
22847     this.disable = this.disable || {};
22848     Roo.applyIf(this.disable, {
22849         fontSize : true,
22850         colors : true,
22851         specialElements : true
22852     });
22853     
22854     
22855     //Roo.form.HtmlEditorToolbar1.superclass.constructor.call(this, editor.wrap.dom.firstChild, [], config);
22856     // dont call parent... till later.
22857 }
22858
22859 Roo.apply(Roo.form.HtmlEditor.ToolbarStandard.prototype,  {
22860     
22861     tb: false,
22862     
22863     rendered: false,
22864     
22865     editor : false,
22866     editorcore : false,
22867     /**
22868      * @cfg {Object} disable  List of toolbar elements to disable
22869          
22870      */
22871     disable : false,
22872     
22873     
22874      /**
22875      * @cfg {String} createLinkText The default text for the create link prompt
22876      */
22877     createLinkText : 'Please enter the URL for the link:',
22878     /**
22879      * @cfg {String} defaultLinkValue The default value for the create link prompt (defaults to http:/ /)
22880      */
22881     defaultLinkValue : 'http:/'+'/',
22882    
22883     
22884       /**
22885      * @cfg {Array} fontFamilies An array of available font families
22886      */
22887     fontFamilies : [
22888         'Arial',
22889         'Courier New',
22890         'Tahoma',
22891         'Times New Roman',
22892         'Verdana'
22893     ],
22894     
22895     specialChars : [
22896            "&#169;",
22897           "&#174;",     
22898           "&#8482;",    
22899           "&#163;" ,    
22900          // "&#8212;",    
22901           "&#8230;",    
22902           "&#247;" ,    
22903         //  "&#225;" ,     ?? a acute?
22904            "&#8364;"    , //Euro
22905        //   "&#8220;"    ,
22906         //  "&#8221;"    ,
22907         //  "&#8226;"    ,
22908           "&#176;"  //   , // degrees
22909
22910          // "&#233;"     , // e ecute
22911          // "&#250;"     , // u ecute?
22912     ],
22913     
22914     specialElements : [
22915         {
22916             text: "Insert Table",
22917             xtype: 'MenuItem',
22918             xns : Roo.Menu,
22919             ihtml :  '<table><tr><td>Cell</td></tr></table>' 
22920                 
22921         },
22922         {    
22923             text: "Insert Image",
22924             xtype: 'MenuItem',
22925             xns : Roo.Menu,
22926             ihtml : '<img src="about:blank"/>'
22927             
22928         }
22929         
22930          
22931     ],
22932     
22933     
22934     inputElements : [ 
22935             "form", "input:text", "input:hidden", "input:checkbox", "input:radio", "input:password", 
22936             "input:submit", "input:button", "select", "textarea", "label" ],
22937     formats : [
22938         ["p"] ,  
22939         ["h1"],["h2"],["h3"],["h4"],["h5"],["h6"], 
22940         ["pre"],[ "code"], 
22941         ["abbr"],[ "acronym"],[ "address"],[ "cite"],[ "samp"],[ "var"],
22942         ['div'],['span']
22943     ],
22944     
22945     cleanStyles : [
22946         "font-size"
22947     ],
22948      /**
22949      * @cfg {String} defaultFont default font to use.
22950      */
22951     defaultFont: 'tahoma',
22952    
22953     fontSelect : false,
22954     
22955     
22956     formatCombo : false,
22957     
22958     init : function(editor)
22959     {
22960         this.editor = editor;
22961         this.editorcore = editor.editorcore ? editor.editorcore : editor;
22962         var editorcore = this.editorcore;
22963         
22964         var _t = this;
22965         
22966         var fid = editorcore.frameId;
22967         var etb = this;
22968         function btn(id, toggle, handler){
22969             var xid = fid + '-'+ id ;
22970             return {
22971                 id : xid,
22972                 cmd : id,
22973                 cls : 'x-btn-icon x-edit-'+id,
22974                 enableToggle:toggle !== false,
22975                 scope: _t, // was editor...
22976                 handler:handler||_t.relayBtnCmd,
22977                 clickEvent:'mousedown',
22978                 tooltip: etb.buttonTips[id] || undefined, ///tips ???
22979                 tabIndex:-1
22980             };
22981         }
22982         
22983         
22984         
22985         var tb = new Roo.Toolbar(editor.wrap.dom.firstChild);
22986         this.tb = tb;
22987          // stop form submits
22988         tb.el.on('click', function(e){
22989             e.preventDefault(); // what does this do?
22990         });
22991
22992         if(!this.disable.font) { // && !Roo.isSafari){
22993             /* why no safari for fonts 
22994             editor.fontSelect = tb.el.createChild({
22995                 tag:'select',
22996                 tabIndex: -1,
22997                 cls:'x-font-select',
22998                 html: this.createFontOptions()
22999             });
23000             
23001             editor.fontSelect.on('change', function(){
23002                 var font = editor.fontSelect.dom.value;
23003                 editor.relayCmd('fontname', font);
23004                 editor.deferFocus();
23005             }, editor);
23006             
23007             tb.add(
23008                 editor.fontSelect.dom,
23009                 '-'
23010             );
23011             */
23012             
23013         };
23014         if(!this.disable.formats){
23015             this.formatCombo = new Roo.form.ComboBox({
23016                 store: new Roo.data.SimpleStore({
23017                     id : 'tag',
23018                     fields: ['tag'],
23019                     data : this.formats // from states.js
23020                 }),
23021                 blockFocus : true,
23022                 name : '',
23023                 //autoCreate : {tag: "div",  size: "20"},
23024                 displayField:'tag',
23025                 typeAhead: false,
23026                 mode: 'local',
23027                 editable : false,
23028                 triggerAction: 'all',
23029                 emptyText:'Add tag',
23030                 selectOnFocus:true,
23031                 width:135,
23032                 listeners : {
23033                     'select': function(c, r, i) {
23034                         editorcore.insertTag(r.get('tag'));
23035                         editor.focus();
23036                     }
23037                 }
23038
23039             });
23040             tb.addField(this.formatCombo);
23041             
23042         }
23043         
23044         if(!this.disable.format){
23045             tb.add(
23046                 btn('bold'),
23047                 btn('italic'),
23048                 btn('underline'),
23049                 btn('strikethrough')
23050             );
23051         };
23052         if(!this.disable.fontSize){
23053             tb.add(
23054                 '-',
23055                 
23056                 
23057                 btn('increasefontsize', false, editorcore.adjustFont),
23058                 btn('decreasefontsize', false, editorcore.adjustFont)
23059             );
23060         };
23061         
23062         
23063         if(!this.disable.colors){
23064             tb.add(
23065                 '-', {
23066                     id:editorcore.frameId +'-forecolor',
23067                     cls:'x-btn-icon x-edit-forecolor',
23068                     clickEvent:'mousedown',
23069                     tooltip: this.buttonTips['forecolor'] || undefined,
23070                     tabIndex:-1,
23071                     menu : new Roo.menu.ColorMenu({
23072                         allowReselect: true,
23073                         focus: Roo.emptyFn,
23074                         value:'000000',
23075                         plain:true,
23076                         selectHandler: function(cp, color){
23077                             editorcore.execCmd('forecolor', Roo.isSafari || Roo.isIE ? '#'+color : color);
23078                             editor.deferFocus();
23079                         },
23080                         scope: editorcore,
23081                         clickEvent:'mousedown'
23082                     })
23083                 }, {
23084                     id:editorcore.frameId +'backcolor',
23085                     cls:'x-btn-icon x-edit-backcolor',
23086                     clickEvent:'mousedown',
23087                     tooltip: this.buttonTips['backcolor'] || undefined,
23088                     tabIndex:-1,
23089                     menu : new Roo.menu.ColorMenu({
23090                         focus: Roo.emptyFn,
23091                         value:'FFFFFF',
23092                         plain:true,
23093                         allowReselect: true,
23094                         selectHandler: function(cp, color){
23095                             if(Roo.isGecko){
23096                                 editorcore.execCmd('useCSS', false);
23097                                 editorcore.execCmd('hilitecolor', color);
23098                                 editorcore.execCmd('useCSS', true);
23099                                 editor.deferFocus();
23100                             }else{
23101                                 editorcore.execCmd(Roo.isOpera ? 'hilitecolor' : 'backcolor', 
23102                                     Roo.isSafari || Roo.isIE ? '#'+color : color);
23103                                 editor.deferFocus();
23104                             }
23105                         },
23106                         scope:editorcore,
23107                         clickEvent:'mousedown'
23108                     })
23109                 }
23110             );
23111         };
23112         // now add all the items...
23113         
23114
23115         if(!this.disable.alignments){
23116             tb.add(
23117                 '-',
23118                 btn('justifyleft'),
23119                 btn('justifycenter'),
23120                 btn('justifyright')
23121             );
23122         };
23123
23124         //if(!Roo.isSafari){
23125             if(!this.disable.links){
23126                 tb.add(
23127                     '-',
23128                     btn('createlink', false, this.createLink)    /// MOVE TO HERE?!!?!?!?!
23129                 );
23130             };
23131
23132             if(!this.disable.lists){
23133                 tb.add(
23134                     '-',
23135                     btn('insertorderedlist'),
23136                     btn('insertunorderedlist')
23137                 );
23138             }
23139             if(!this.disable.sourceEdit){
23140                 tb.add(
23141                     '-',
23142                     btn('sourceedit', true, function(btn){
23143                         this.toggleSourceEdit(btn.pressed);
23144                     })
23145                 );
23146             }
23147         //}
23148         
23149         var smenu = { };
23150         // special menu.. - needs to be tidied up..
23151         if (!this.disable.special) {
23152             smenu = {
23153                 text: "&#169;",
23154                 cls: 'x-edit-none',
23155                 
23156                 menu : {
23157                     items : []
23158                 }
23159             };
23160             for (var i =0; i < this.specialChars.length; i++) {
23161                 smenu.menu.items.push({
23162                     
23163                     html: this.specialChars[i],
23164                     handler: function(a,b) {
23165                         editorcore.insertAtCursor(String.fromCharCode(a.html.replace('&#','').replace(';', '')));
23166                         //editor.insertAtCursor(a.html);
23167                         
23168                     },
23169                     tabIndex:-1
23170                 });
23171             }
23172             
23173             
23174             tb.add(smenu);
23175             
23176             
23177         }
23178         
23179         var cmenu = { };
23180         if (!this.disable.cleanStyles) {
23181             cmenu = {
23182                 cls: 'x-btn-icon x-btn-clear',
23183                 
23184                 menu : {
23185                     items : []
23186                 }
23187             };
23188             for (var i =0; i < this.cleanStyles.length; i++) {
23189                 cmenu.menu.items.push({
23190                     actiontype : this.cleanStyles[i],
23191                     html: 'Remove ' + this.cleanStyles[i],
23192                     handler: function(a,b) {
23193 //                        Roo.log(a);
23194 //                        Roo.log(b);
23195                         var c = Roo.get(editorcore.doc.body);
23196                         c.select('[style]').each(function(s) {
23197                             s.dom.style.removeProperty(a.actiontype);
23198                         });
23199                         editorcore.syncValue();
23200                     },
23201                     tabIndex:-1
23202                 });
23203             }
23204              cmenu.menu.items.push({
23205                 actiontype : 'tablewidths',
23206                 html: 'Remove Table Widths',
23207                 handler: function(a,b) {
23208                     editorcore.cleanTableWidths();
23209                     editorcore.syncValue();
23210                 },
23211                 tabIndex:-1
23212             });
23213             cmenu.menu.items.push({
23214                 actiontype : 'word',
23215                 html: 'Remove MS Word Formating',
23216                 handler: function(a,b) {
23217                     editorcore.cleanWord();
23218                     editorcore.syncValue();
23219                 },
23220                 tabIndex:-1
23221             });
23222             
23223             cmenu.menu.items.push({
23224                 actiontype : 'all',
23225                 html: 'Remove All Styles',
23226                 handler: function(a,b) {
23227                     
23228                     var c = Roo.get(editorcore.doc.body);
23229                     c.select('[style]').each(function(s) {
23230                         s.dom.removeAttribute('style');
23231                     });
23232                     editorcore.syncValue();
23233                 },
23234                 tabIndex:-1
23235             });
23236             
23237             cmenu.menu.items.push({
23238                 actiontype : 'all',
23239                 html: 'Remove All CSS Classes',
23240                 handler: function(a,b) {
23241                     
23242                     var c = Roo.get(editorcore.doc.body);
23243                     c.select('[class]').each(function(s) {
23244                         s.dom.removeAttribute('class');
23245                     });
23246                     editorcore.cleanWord();
23247                     editorcore.syncValue();
23248                 },
23249                 tabIndex:-1
23250             });
23251             
23252              cmenu.menu.items.push({
23253                 actiontype : 'tidy',
23254                 html: 'Tidy HTML Source',
23255                 handler: function(a,b) {
23256                     editorcore.doc.body.innerHTML = editorcore.domToHTML();
23257                     editorcore.syncValue();
23258                 },
23259                 tabIndex:-1
23260             });
23261             
23262             
23263             tb.add(cmenu);
23264         }
23265          
23266         if (!this.disable.specialElements) {
23267             var semenu = {
23268                 text: "Other;",
23269                 cls: 'x-edit-none',
23270                 menu : {
23271                     items : []
23272                 }
23273             };
23274             for (var i =0; i < this.specialElements.length; i++) {
23275                 semenu.menu.items.push(
23276                     Roo.apply({ 
23277                         handler: function(a,b) {
23278                             editor.insertAtCursor(this.ihtml);
23279                         }
23280                     }, this.specialElements[i])
23281                 );
23282                     
23283             }
23284             
23285             tb.add(semenu);
23286             
23287             
23288         }
23289          
23290         
23291         if (this.btns) {
23292             for(var i =0; i< this.btns.length;i++) {
23293                 var b = Roo.factory(this.btns[i],Roo.form);
23294                 b.cls =  'x-edit-none';
23295                 
23296                 if(typeof(this.btns[i].cls) != 'undefined' && this.btns[i].cls.indexOf('x-init-enable') !== -1){
23297                     b.cls += ' x-init-enable';
23298                 }
23299                 
23300                 b.scope = editorcore;
23301                 tb.add(b);
23302             }
23303         
23304         }
23305         
23306         
23307         
23308         // disable everything...
23309         
23310         this.tb.items.each(function(item){
23311             
23312            if(
23313                 item.id != editorcore.frameId+ '-sourceedit' && 
23314                 (typeof(item.cls) != 'undefined' && item.cls.indexOf('x-init-enable') === -1)
23315             ){
23316                 
23317                 item.disable();
23318             }
23319         });
23320         this.rendered = true;
23321         
23322         // the all the btns;
23323         editor.on('editorevent', this.updateToolbar, this);
23324         // other toolbars need to implement this..
23325         //editor.on('editmodechange', this.updateToolbar, this);
23326     },
23327     
23328     
23329     relayBtnCmd : function(btn) {
23330         this.editorcore.relayCmd(btn.cmd);
23331     },
23332     // private used internally
23333     createLink : function(){
23334         Roo.log("create link?");
23335         var url = prompt(this.createLinkText, this.defaultLinkValue);
23336         if(url && url != 'http:/'+'/'){
23337             this.editorcore.relayCmd('createlink', url);
23338         }
23339     },
23340
23341     
23342     /**
23343      * Protected method that will not generally be called directly. It triggers
23344      * a toolbar update by reading the markup state of the current selection in the editor.
23345      */
23346     updateToolbar: function(){
23347
23348         if(!this.editorcore.activated){
23349             this.editor.onFirstFocus();
23350             return;
23351         }
23352
23353         var btns = this.tb.items.map, 
23354             doc = this.editorcore.doc,
23355             frameId = this.editorcore.frameId;
23356
23357         if(!this.disable.font && !Roo.isSafari){
23358             /*
23359             var name = (doc.queryCommandValue('FontName')||this.editor.defaultFont).toLowerCase();
23360             if(name != this.fontSelect.dom.value){
23361                 this.fontSelect.dom.value = name;
23362             }
23363             */
23364         }
23365         if(!this.disable.format){
23366             btns[frameId + '-bold'].toggle(doc.queryCommandState('bold'));
23367             btns[frameId + '-italic'].toggle(doc.queryCommandState('italic'));
23368             btns[frameId + '-underline'].toggle(doc.queryCommandState('underline'));
23369             btns[frameId + '-strikethrough'].toggle(doc.queryCommandState('strikethrough'));
23370         }
23371         if(!this.disable.alignments){
23372             btns[frameId + '-justifyleft'].toggle(doc.queryCommandState('justifyleft'));
23373             btns[frameId + '-justifycenter'].toggle(doc.queryCommandState('justifycenter'));
23374             btns[frameId + '-justifyright'].toggle(doc.queryCommandState('justifyright'));
23375         }
23376         if(!Roo.isSafari && !this.disable.lists){
23377             btns[frameId + '-insertorderedlist'].toggle(doc.queryCommandState('insertorderedlist'));
23378             btns[frameId + '-insertunorderedlist'].toggle(doc.queryCommandState('insertunorderedlist'));
23379         }
23380         
23381         var ans = this.editorcore.getAllAncestors();
23382         if (this.formatCombo) {
23383             
23384             
23385             var store = this.formatCombo.store;
23386             this.formatCombo.setValue("");
23387             for (var i =0; i < ans.length;i++) {
23388                 if (ans[i] && store.query('tag',ans[i].tagName.toLowerCase(), false).length) {
23389                     // select it..
23390                     this.formatCombo.setValue(ans[i].tagName.toLowerCase());
23391                     break;
23392                 }
23393             }
23394         }
23395         
23396         
23397         
23398         // hides menus... - so this cant be on a menu...
23399         Roo.menu.MenuMgr.hideAll();
23400
23401         //this.editorsyncValue();
23402     },
23403    
23404     
23405     createFontOptions : function(){
23406         var buf = [], fs = this.fontFamilies, ff, lc;
23407         
23408         
23409         
23410         for(var i = 0, len = fs.length; i< len; i++){
23411             ff = fs[i];
23412             lc = ff.toLowerCase();
23413             buf.push(
23414                 '<option value="',lc,'" style="font-family:',ff,';"',
23415                     (this.defaultFont == lc ? ' selected="true">' : '>'),
23416                     ff,
23417                 '</option>'
23418             );
23419         }
23420         return buf.join('');
23421     },
23422     
23423     toggleSourceEdit : function(sourceEditMode){
23424         
23425         Roo.log("toolbar toogle");
23426         if(sourceEditMode === undefined){
23427             sourceEditMode = !this.sourceEditMode;
23428         }
23429         this.sourceEditMode = sourceEditMode === true;
23430         var btn = this.tb.items.get(this.editorcore.frameId +'-sourceedit');
23431         // just toggle the button?
23432         if(btn.pressed !== this.sourceEditMode){
23433             btn.toggle(this.sourceEditMode);
23434             return;
23435         }
23436         
23437         if(sourceEditMode){
23438             Roo.log("disabling buttons");
23439             this.tb.items.each(function(item){
23440                 if(item.cmd != 'sourceedit' && (typeof(item.cls) != 'undefined' && item.cls.indexOf('x-init-enable') === -1)){
23441                     item.disable();
23442                 }
23443             });
23444           
23445         }else{
23446             Roo.log("enabling buttons");
23447             if(this.editorcore.initialized){
23448                 this.tb.items.each(function(item){
23449                     item.enable();
23450                 });
23451             }
23452             
23453         }
23454         Roo.log("calling toggole on editor");
23455         // tell the editor that it's been pressed..
23456         this.editor.toggleSourceEdit(sourceEditMode);
23457        
23458     },
23459      /**
23460      * Object collection of toolbar tooltips for the buttons in the editor. The key
23461      * is the command id associated with that button and the value is a valid QuickTips object.
23462      * For example:
23463 <pre><code>
23464 {
23465     bold : {
23466         title: 'Bold (Ctrl+B)',
23467         text: 'Make the selected text bold.',
23468         cls: 'x-html-editor-tip'
23469     },
23470     italic : {
23471         title: 'Italic (Ctrl+I)',
23472         text: 'Make the selected text italic.',
23473         cls: 'x-html-editor-tip'
23474     },
23475     ...
23476 </code></pre>
23477     * @type Object
23478      */
23479     buttonTips : {
23480         bold : {
23481             title: 'Bold (Ctrl+B)',
23482             text: 'Make the selected text bold.',
23483             cls: 'x-html-editor-tip'
23484         },
23485         italic : {
23486             title: 'Italic (Ctrl+I)',
23487             text: 'Make the selected text italic.',
23488             cls: 'x-html-editor-tip'
23489         },
23490         underline : {
23491             title: 'Underline (Ctrl+U)',
23492             text: 'Underline the selected text.',
23493             cls: 'x-html-editor-tip'
23494         },
23495         strikethrough : {
23496             title: 'Strikethrough',
23497             text: 'Strikethrough the selected text.',
23498             cls: 'x-html-editor-tip'
23499         },
23500         increasefontsize : {
23501             title: 'Grow Text',
23502             text: 'Increase the font size.',
23503             cls: 'x-html-editor-tip'
23504         },
23505         decreasefontsize : {
23506             title: 'Shrink Text',
23507             text: 'Decrease the font size.',
23508             cls: 'x-html-editor-tip'
23509         },
23510         backcolor : {
23511             title: 'Text Highlight Color',
23512             text: 'Change the background color of the selected text.',
23513             cls: 'x-html-editor-tip'
23514         },
23515         forecolor : {
23516             title: 'Font Color',
23517             text: 'Change the color of the selected text.',
23518             cls: 'x-html-editor-tip'
23519         },
23520         justifyleft : {
23521             title: 'Align Text Left',
23522             text: 'Align text to the left.',
23523             cls: 'x-html-editor-tip'
23524         },
23525         justifycenter : {
23526             title: 'Center Text',
23527             text: 'Center text in the editor.',
23528             cls: 'x-html-editor-tip'
23529         },
23530         justifyright : {
23531             title: 'Align Text Right',
23532             text: 'Align text to the right.',
23533             cls: 'x-html-editor-tip'
23534         },
23535         insertunorderedlist : {
23536             title: 'Bullet List',
23537             text: 'Start a bulleted list.',
23538             cls: 'x-html-editor-tip'
23539         },
23540         insertorderedlist : {
23541             title: 'Numbered List',
23542             text: 'Start a numbered list.',
23543             cls: 'x-html-editor-tip'
23544         },
23545         createlink : {
23546             title: 'Hyperlink',
23547             text: 'Make the selected text a hyperlink.',
23548             cls: 'x-html-editor-tip'
23549         },
23550         sourceedit : {
23551             title: 'Source Edit',
23552             text: 'Switch to source editing mode.',
23553             cls: 'x-html-editor-tip'
23554         }
23555     },
23556     // private
23557     onDestroy : function(){
23558         if(this.rendered){
23559             
23560             this.tb.items.each(function(item){
23561                 if(item.menu){
23562                     item.menu.removeAll();
23563                     if(item.menu.el){
23564                         item.menu.el.destroy();
23565                     }
23566                 }
23567                 item.destroy();
23568             });
23569              
23570         }
23571     },
23572     onFirstFocus: function() {
23573         this.tb.items.each(function(item){
23574            item.enable();
23575         });
23576     }
23577 });
23578
23579
23580
23581
23582 // <script type="text/javascript">
23583 /*
23584  * Based on
23585  * Ext JS Library 1.1.1
23586  * Copyright(c) 2006-2007, Ext JS, LLC.
23587  *  
23588  
23589  */
23590
23591  
23592 /**
23593  * @class Roo.form.HtmlEditor.ToolbarContext
23594  * Context Toolbar
23595  * 
23596  * Usage:
23597  *
23598  new Roo.form.HtmlEditor({
23599     ....
23600     toolbars : [
23601         { xtype: 'ToolbarStandard', styles : {} }
23602         { xtype: 'ToolbarContext', disable : {} }
23603     ]
23604 })
23605
23606      
23607  * 
23608  * @config : {Object} disable List of elements to disable.. (not done yet.)
23609  * @config : {Object} styles  Map of styles available.
23610  * 
23611  */
23612
23613 Roo.form.HtmlEditor.ToolbarContext = function(config)
23614 {
23615     
23616     Roo.apply(this, config);
23617     //Roo.form.HtmlEditorToolbar1.superclass.constructor.call(this, editor.wrap.dom.firstChild, [], config);
23618     // dont call parent... till later.
23619     this.styles = this.styles || {};
23620 }
23621
23622  
23623
23624 Roo.form.HtmlEditor.ToolbarContext.types = {
23625     'IMG' : {
23626         width : {
23627             title: "Width",
23628             width: 40
23629         },
23630         height:  {
23631             title: "Height",
23632             width: 40
23633         },
23634         align: {
23635             title: "Align",
23636             opts : [ [""],[ "left"],[ "right"],[ "center"],[ "top"]],
23637             width : 80
23638             
23639         },
23640         border: {
23641             title: "Border",
23642             width: 40
23643         },
23644         alt: {
23645             title: "Alt",
23646             width: 120
23647         },
23648         src : {
23649             title: "Src",
23650             width: 220
23651         }
23652         
23653     },
23654     'A' : {
23655         name : {
23656             title: "Name",
23657             width: 50
23658         },
23659         target:  {
23660             title: "Target",
23661             width: 120
23662         },
23663         href:  {
23664             title: "Href",
23665             width: 220
23666         } // border?
23667         
23668     },
23669     'TABLE' : {
23670         rows : {
23671             title: "Rows",
23672             width: 20
23673         },
23674         cols : {
23675             title: "Cols",
23676             width: 20
23677         },
23678         width : {
23679             title: "Width",
23680             width: 40
23681         },
23682         height : {
23683             title: "Height",
23684             width: 40
23685         },
23686         border : {
23687             title: "Border",
23688             width: 20
23689         }
23690     },
23691     'TD' : {
23692         width : {
23693             title: "Width",
23694             width: 40
23695         },
23696         height : {
23697             title: "Height",
23698             width: 40
23699         },   
23700         align: {
23701             title: "Align",
23702             opts : [[""],[ "left"],[ "center"],[ "right"],[ "justify"],[ "char"]],
23703             width: 80
23704         },
23705         valign: {
23706             title: "Valign",
23707             opts : [[""],[ "top"],[ "middle"],[ "bottom"],[ "baseline"]],
23708             width: 80
23709         },
23710         colspan: {
23711             title: "Colspan",
23712             width: 20
23713             
23714         },
23715          'font-family'  : {
23716             title : "Font",
23717             style : 'fontFamily',
23718             displayField: 'display',
23719             optname : 'font-family',
23720             width: 140
23721         }
23722     },
23723     'INPUT' : {
23724         name : {
23725             title: "name",
23726             width: 120
23727         },
23728         value : {
23729             title: "Value",
23730             width: 120
23731         },
23732         width : {
23733             title: "Width",
23734             width: 40
23735         }
23736     },
23737     'LABEL' : {
23738         'for' : {
23739             title: "For",
23740             width: 120
23741         }
23742     },
23743     'TEXTAREA' : {
23744           name : {
23745             title: "name",
23746             width: 120
23747         },
23748         rows : {
23749             title: "Rows",
23750             width: 20
23751         },
23752         cols : {
23753             title: "Cols",
23754             width: 20
23755         }
23756     },
23757     'SELECT' : {
23758         name : {
23759             title: "name",
23760             width: 120
23761         },
23762         selectoptions : {
23763             title: "Options",
23764             width: 200
23765         }
23766     },
23767     
23768     // should we really allow this??
23769     // should this just be 
23770     'BODY' : {
23771         title : {
23772             title: "Title",
23773             width: 200,
23774             disabled : true
23775         }
23776     },
23777     'SPAN' : {
23778         'font-family'  : {
23779             title : "Font",
23780             style : 'fontFamily',
23781             displayField: 'display',
23782             optname : 'font-family',
23783             width: 140
23784         }
23785     },
23786     'DIV' : {
23787         'font-family'  : {
23788             title : "Font",
23789             style : 'fontFamily',
23790             displayField: 'display',
23791             optname : 'font-family',
23792             width: 140
23793         }
23794     },
23795      'P' : {
23796         'font-family'  : {
23797             title : "Font",
23798             style : 'fontFamily',
23799             displayField: 'display',
23800             optname : 'font-family',
23801             width: 140
23802         }
23803     },
23804     
23805     '*' : {
23806         // empty..
23807     }
23808
23809 };
23810
23811 // this should be configurable.. - you can either set it up using stores, or modify options somehwere..
23812 Roo.form.HtmlEditor.ToolbarContext.stores = false;
23813
23814 Roo.form.HtmlEditor.ToolbarContext.options = {
23815         'font-family'  : [ 
23816                 [ 'Helvetica,Arial,sans-serif', 'Helvetica'],
23817                 [ 'Courier New', 'Courier New'],
23818                 [ 'Tahoma', 'Tahoma'],
23819                 [ 'Times New Roman,serif', 'Times'],
23820                 [ 'Verdana','Verdana' ]
23821         ]
23822 };
23823
23824 // fixme - these need to be configurable..
23825  
23826
23827 //Roo.form.HtmlEditor.ToolbarContext.types
23828
23829
23830 Roo.apply(Roo.form.HtmlEditor.ToolbarContext.prototype,  {
23831     
23832     tb: false,
23833     
23834     rendered: false,
23835     
23836     editor : false,
23837     editorcore : false,
23838     /**
23839      * @cfg {Object} disable  List of toolbar elements to disable
23840          
23841      */
23842     disable : false,
23843     /**
23844      * @cfg {Object} styles List of styles 
23845      *    eg. { '*' : [ 'headline' ] , 'TD' : [ 'underline', 'double-underline' ] } 
23846      *
23847      * These must be defined in the page, so they get rendered correctly..
23848      * .headline { }
23849      * TD.underline { }
23850      * 
23851      */
23852     styles : false,
23853     
23854     options: false,
23855     
23856     toolbars : false,
23857     
23858     init : function(editor)
23859     {
23860         this.editor = editor;
23861         this.editorcore = editor.editorcore ? editor.editorcore : editor;
23862         var editorcore = this.editorcore;
23863         
23864         var fid = editorcore.frameId;
23865         var etb = this;
23866         function btn(id, toggle, handler){
23867             var xid = fid + '-'+ id ;
23868             return {
23869                 id : xid,
23870                 cmd : id,
23871                 cls : 'x-btn-icon x-edit-'+id,
23872                 enableToggle:toggle !== false,
23873                 scope: editorcore, // was editor...
23874                 handler:handler||editorcore.relayBtnCmd,
23875                 clickEvent:'mousedown',
23876                 tooltip: etb.buttonTips[id] || undefined, ///tips ???
23877                 tabIndex:-1
23878             };
23879         }
23880         // create a new element.
23881         var wdiv = editor.wrap.createChild({
23882                 tag: 'div'
23883             }, editor.wrap.dom.firstChild.nextSibling, true);
23884         
23885         // can we do this more than once??
23886         
23887          // stop form submits
23888       
23889  
23890         // disable everything...
23891         var ty= Roo.form.HtmlEditor.ToolbarContext.types;
23892         this.toolbars = {};
23893            
23894         for (var i in  ty) {
23895           
23896             this.toolbars[i] = this.buildToolbar(ty[i],i);
23897         }
23898         this.tb = this.toolbars.BODY;
23899         this.tb.el.show();
23900         this.buildFooter();
23901         this.footer.show();
23902         editor.on('hide', function( ) { this.footer.hide() }, this);
23903         editor.on('show', function( ) { this.footer.show() }, this);
23904         
23905          
23906         this.rendered = true;
23907         
23908         // the all the btns;
23909         editor.on('editorevent', this.updateToolbar, this);
23910         // other toolbars need to implement this..
23911         //editor.on('editmodechange', this.updateToolbar, this);
23912     },
23913     
23914     
23915     
23916     /**
23917      * Protected method that will not generally be called directly. It triggers
23918      * a toolbar update by reading the markup state of the current selection in the editor.
23919      *
23920      * Note you can force an update by calling on('editorevent', scope, false)
23921      */
23922     updateToolbar: function(editor,ev,sel){
23923
23924         //Roo.log(ev);
23925         // capture mouse up - this is handy for selecting images..
23926         // perhaps should go somewhere else...
23927         if(!this.editorcore.activated){
23928              this.editor.onFirstFocus();
23929             return;
23930         }
23931         
23932         
23933         
23934         // http://developer.yahoo.com/yui/docs/simple-editor.js.html
23935         // selectNode - might want to handle IE?
23936         if (ev &&
23937             (ev.type == 'mouseup' || ev.type == 'click' ) &&
23938             ev.target && ev.target.tagName == 'IMG') {
23939             // they have click on an image...
23940             // let's see if we can change the selection...
23941             sel = ev.target;
23942          
23943               var nodeRange = sel.ownerDocument.createRange();
23944             try {
23945                 nodeRange.selectNode(sel);
23946             } catch (e) {
23947                 nodeRange.selectNodeContents(sel);
23948             }
23949             //nodeRange.collapse(true);
23950             var s = this.editorcore.win.getSelection();
23951             s.removeAllRanges();
23952             s.addRange(nodeRange);
23953         }  
23954         
23955       
23956         var updateFooter = sel ? false : true;
23957         
23958         
23959         var ans = this.editorcore.getAllAncestors();
23960         
23961         // pick
23962         var ty= Roo.form.HtmlEditor.ToolbarContext.types;
23963         
23964         if (!sel) { 
23965             sel = ans.length ? (ans[0] ?  ans[0]  : ans[1]) : this.editorcore.doc.body;
23966             sel = sel ? sel : this.editorcore.doc.body;
23967             sel = sel.tagName.length ? sel : this.editorcore.doc.body;
23968             
23969         }
23970         // pick a menu that exists..
23971         var tn = sel.tagName.toUpperCase();
23972         //sel = typeof(ty[tn]) != 'undefined' ? sel : this.editor.doc.body;
23973         
23974         tn = sel.tagName.toUpperCase();
23975         
23976         var lastSel = this.tb.selectedNode;
23977         
23978         this.tb.selectedNode = sel;
23979         
23980         // if current menu does not match..
23981         
23982         if ((this.tb.name != tn) || (lastSel != this.tb.selectedNode) || ev === false) {
23983                 
23984             this.tb.el.hide();
23985             ///console.log("show: " + tn);
23986             this.tb =  typeof(ty[tn]) != 'undefined' ? this.toolbars[tn] : this.toolbars['*'];
23987             this.tb.el.show();
23988             // update name
23989             this.tb.items.first().el.innerHTML = tn + ':&nbsp;';
23990             
23991             
23992             // update attributes
23993             if (this.tb.fields) {
23994                 this.tb.fields.each(function(e) {
23995                     if (e.stylename) {
23996                         e.setValue(sel.style[e.stylename]);
23997                         return;
23998                     } 
23999                    e.setValue(sel.getAttribute(e.attrname));
24000                 });
24001             }
24002             
24003             var hasStyles = false;
24004             for(var i in this.styles) {
24005                 hasStyles = true;
24006                 break;
24007             }
24008             
24009             // update styles
24010             if (hasStyles) { 
24011                 var st = this.tb.fields.item(0);
24012                 
24013                 st.store.removeAll();
24014                
24015                 
24016                 var cn = sel.className.split(/\s+/);
24017                 
24018                 var avs = [];
24019                 if (this.styles['*']) {
24020                     
24021                     Roo.each(this.styles['*'], function(v) {
24022                         avs.push( [ v , cn.indexOf(v) > -1 ? 1 : 0 ] );         
24023                     });
24024                 }
24025                 if (this.styles[tn]) { 
24026                     Roo.each(this.styles[tn], function(v) {
24027                         avs.push( [ v , cn.indexOf(v) > -1 ? 1 : 0 ] );         
24028                     });
24029                 }
24030                 
24031                 st.store.loadData(avs);
24032                 st.collapse();
24033                 st.setValue(cn);
24034             }
24035             // flag our selected Node.
24036             this.tb.selectedNode = sel;
24037            
24038            
24039             Roo.menu.MenuMgr.hideAll();
24040
24041         }
24042         
24043         if (!updateFooter) {
24044             //this.footDisp.dom.innerHTML = ''; 
24045             return;
24046         }
24047         // update the footer
24048         //
24049         var html = '';
24050         
24051         this.footerEls = ans.reverse();
24052         Roo.each(this.footerEls, function(a,i) {
24053             if (!a) { return; }
24054             html += html.length ? ' &gt; '  :  '';
24055             
24056             html += '<span class="x-ed-loc-' + i + '">' + a.tagName + '</span>';
24057             
24058         });
24059        
24060         // 
24061         var sz = this.footDisp.up('td').getSize();
24062         this.footDisp.dom.style.width = (sz.width -10) + 'px';
24063         this.footDisp.dom.style.marginLeft = '5px';
24064         
24065         this.footDisp.dom.style.overflow = 'hidden';
24066         
24067         this.footDisp.dom.innerHTML = html;
24068             
24069         //this.editorsyncValue();
24070     },
24071      
24072     
24073    
24074        
24075     // private
24076     onDestroy : function(){
24077         if(this.rendered){
24078             
24079             this.tb.items.each(function(item){
24080                 if(item.menu){
24081                     item.menu.removeAll();
24082                     if(item.menu.el){
24083                         item.menu.el.destroy();
24084                     }
24085                 }
24086                 item.destroy();
24087             });
24088              
24089         }
24090     },
24091     onFirstFocus: function() {
24092         // need to do this for all the toolbars..
24093         this.tb.items.each(function(item){
24094            item.enable();
24095         });
24096     },
24097     buildToolbar: function(tlist, nm)
24098     {
24099         var editor = this.editor;
24100         var editorcore = this.editorcore;
24101          // create a new element.
24102         var wdiv = editor.wrap.createChild({
24103                 tag: 'div'
24104             }, editor.wrap.dom.firstChild.nextSibling, true);
24105         
24106        
24107         var tb = new Roo.Toolbar(wdiv);
24108         // add the name..
24109         
24110         tb.add(nm+ ":&nbsp;");
24111         
24112         var styles = [];
24113         for(var i in this.styles) {
24114             styles.push(i);
24115         }
24116         
24117         // styles...
24118         if (styles && styles.length) {
24119             
24120             // this needs a multi-select checkbox...
24121             tb.addField( new Roo.form.ComboBox({
24122                 store: new Roo.data.SimpleStore({
24123                     id : 'val',
24124                     fields: ['val', 'selected'],
24125                     data : [] 
24126                 }),
24127                 name : '-roo-edit-className',
24128                 attrname : 'className',
24129                 displayField: 'val',
24130                 typeAhead: false,
24131                 mode: 'local',
24132                 editable : false,
24133                 triggerAction: 'all',
24134                 emptyText:'Select Style',
24135                 selectOnFocus:true,
24136                 width: 130,
24137                 listeners : {
24138                     'select': function(c, r, i) {
24139                         // initial support only for on class per el..
24140                         tb.selectedNode.className =  r ? r.get('val') : '';
24141                         editorcore.syncValue();
24142                     }
24143                 }
24144     
24145             }));
24146         }
24147         
24148         var tbc = Roo.form.HtmlEditor.ToolbarContext;
24149         var tbops = tbc.options;
24150         
24151         for (var i in tlist) {
24152             
24153             var item = tlist[i];
24154             tb.add(item.title + ":&nbsp;");
24155             
24156             
24157             //optname == used so you can configure the options available..
24158             var opts = item.opts ? item.opts : false;
24159             if (item.optname) {
24160                 opts = tbops[item.optname];
24161            
24162             }
24163             
24164             if (opts) {
24165                 // opts == pulldown..
24166                 tb.addField( new Roo.form.ComboBox({
24167                     store:   typeof(tbc.stores[i]) != 'undefined' ?  Roo.factory(tbc.stores[i],Roo.data) : new Roo.data.SimpleStore({
24168                         id : 'val',
24169                         fields: ['val', 'display'],
24170                         data : opts  
24171                     }),
24172                     name : '-roo-edit-' + i,
24173                     attrname : i,
24174                     stylename : item.style ? item.style : false,
24175                     displayField: item.displayField ? item.displayField : 'val',
24176                     valueField :  'val',
24177                     typeAhead: false,
24178                     mode: typeof(tbc.stores[i]) != 'undefined'  ? 'remote' : 'local',
24179                     editable : false,
24180                     triggerAction: 'all',
24181                     emptyText:'Select',
24182                     selectOnFocus:true,
24183                     width: item.width ? item.width  : 130,
24184                     listeners : {
24185                         'select': function(c, r, i) {
24186                             if (c.stylename) {
24187                                 tb.selectedNode.style[c.stylename] =  r.get('val');
24188                                 return;
24189                             }
24190                             tb.selectedNode.setAttribute(c.attrname, r.get('val'));
24191                         }
24192                     }
24193
24194                 }));
24195                 continue;
24196                     
24197                  
24198                 
24199                 tb.addField( new Roo.form.TextField({
24200                     name: i,
24201                     width: 100,
24202                     //allowBlank:false,
24203                     value: ''
24204                 }));
24205                 continue;
24206             }
24207             tb.addField( new Roo.form.TextField({
24208                 name: '-roo-edit-' + i,
24209                 attrname : i,
24210                 
24211                 width: item.width,
24212                 //allowBlank:true,
24213                 value: '',
24214                 listeners: {
24215                     'change' : function(f, nv, ov) {
24216                         tb.selectedNode.setAttribute(f.attrname, nv);
24217                         editorcore.syncValue();
24218                     }
24219                 }
24220             }));
24221              
24222         }
24223         
24224         var _this = this;
24225         
24226         if(nm == 'BODY'){
24227             tb.addSeparator();
24228         
24229             tb.addButton( {
24230                 text: 'Stylesheets',
24231
24232                 listeners : {
24233                     click : function ()
24234                     {
24235                         _this.editor.fireEvent('stylesheetsclick', _this.editor);
24236                     }
24237                 }
24238             });
24239         }
24240         
24241         tb.addFill();
24242         tb.addButton( {
24243             text: 'Remove Tag',
24244     
24245             listeners : {
24246                 click : function ()
24247                 {
24248                     // remove
24249                     // undo does not work.
24250                      
24251                     var sn = tb.selectedNode;
24252                     
24253                     var pn = sn.parentNode;
24254                     
24255                     var stn =  sn.childNodes[0];
24256                     var en = sn.childNodes[sn.childNodes.length - 1 ];
24257                     while (sn.childNodes.length) {
24258                         var node = sn.childNodes[0];
24259                         sn.removeChild(node);
24260                         //Roo.log(node);
24261                         pn.insertBefore(node, sn);
24262                         
24263                     }
24264                     pn.removeChild(sn);
24265                     var range = editorcore.createRange();
24266         
24267                     range.setStart(stn,0);
24268                     range.setEnd(en,0); //????
24269                     //range.selectNode(sel);
24270                     
24271                     
24272                     var selection = editorcore.getSelection();
24273                     selection.removeAllRanges();
24274                     selection.addRange(range);
24275                     
24276                     
24277                     
24278                     //_this.updateToolbar(null, null, pn);
24279                     _this.updateToolbar(null, null, null);
24280                     _this.footDisp.dom.innerHTML = ''; 
24281                 }
24282             }
24283             
24284                     
24285                 
24286             
24287         });
24288         
24289         
24290         tb.el.on('click', function(e){
24291             e.preventDefault(); // what does this do?
24292         });
24293         tb.el.setVisibilityMode( Roo.Element.DISPLAY);
24294         tb.el.hide();
24295         tb.name = nm;
24296         // dont need to disable them... as they will get hidden
24297         return tb;
24298          
24299         
24300     },
24301     buildFooter : function()
24302     {
24303         
24304         var fel = this.editor.wrap.createChild();
24305         this.footer = new Roo.Toolbar(fel);
24306         // toolbar has scrolly on left / right?
24307         var footDisp= new Roo.Toolbar.Fill();
24308         var _t = this;
24309         this.footer.add(
24310             {
24311                 text : '&lt;',
24312                 xtype: 'Button',
24313                 handler : function() {
24314                     _t.footDisp.scrollTo('left',0,true)
24315                 }
24316             }
24317         );
24318         this.footer.add( footDisp );
24319         this.footer.add( 
24320             {
24321                 text : '&gt;',
24322                 xtype: 'Button',
24323                 handler : function() {
24324                     // no animation..
24325                     _t.footDisp.select('span').last().scrollIntoView(_t.footDisp,true);
24326                 }
24327             }
24328         );
24329         var fel = Roo.get(footDisp.el);
24330         fel.addClass('x-editor-context');
24331         this.footDispWrap = fel; 
24332         this.footDispWrap.overflow  = 'hidden';
24333         
24334         this.footDisp = fel.createChild();
24335         this.footDispWrap.on('click', this.onContextClick, this)
24336         
24337         
24338     },
24339     onContextClick : function (ev,dom)
24340     {
24341         ev.preventDefault();
24342         var  cn = dom.className;
24343         //Roo.log(cn);
24344         if (!cn.match(/x-ed-loc-/)) {
24345             return;
24346         }
24347         var n = cn.split('-').pop();
24348         var ans = this.footerEls;
24349         var sel = ans[n];
24350         
24351          // pick
24352         var range = this.editorcore.createRange();
24353         
24354         range.selectNodeContents(sel);
24355         //range.selectNode(sel);
24356         
24357         
24358         var selection = this.editorcore.getSelection();
24359         selection.removeAllRanges();
24360         selection.addRange(range);
24361         
24362         
24363         
24364         this.updateToolbar(null, null, sel);
24365         
24366         
24367     }
24368     
24369     
24370     
24371     
24372     
24373 });
24374
24375
24376
24377
24378
24379 /*
24380  * Based on:
24381  * Ext JS Library 1.1.1
24382  * Copyright(c) 2006-2007, Ext JS, LLC.
24383  *
24384  * Originally Released Under LGPL - original licence link has changed is not relivant.
24385  *
24386  * Fork - LGPL
24387  * <script type="text/javascript">
24388  */
24389  
24390 /**
24391  * @class Roo.form.BasicForm
24392  * @extends Roo.util.Observable
24393  * Supplies the functionality to do "actions" on forms and initialize Roo.form.Field types on existing markup.
24394  * @constructor
24395  * @param {String/HTMLElement/Roo.Element} el The form element or its id
24396  * @param {Object} config Configuration options
24397  */
24398 Roo.form.BasicForm = function(el, config){
24399     this.allItems = [];
24400     this.childForms = [];
24401     Roo.apply(this, config);
24402     /*
24403      * The Roo.form.Field items in this form.
24404      * @type MixedCollection
24405      */
24406      
24407      
24408     this.items = new Roo.util.MixedCollection(false, function(o){
24409         return o.id || (o.id = Roo.id());
24410     });
24411     this.addEvents({
24412         /**
24413          * @event beforeaction
24414          * Fires before any action is performed. Return false to cancel the action.
24415          * @param {Form} this
24416          * @param {Action} action The action to be performed
24417          */
24418         beforeaction: true,
24419         /**
24420          * @event actionfailed
24421          * Fires when an action fails.
24422          * @param {Form} this
24423          * @param {Action} action The action that failed
24424          */
24425         actionfailed : true,
24426         /**
24427          * @event actioncomplete
24428          * Fires when an action is completed.
24429          * @param {Form} this
24430          * @param {Action} action The action that completed
24431          */
24432         actioncomplete : true
24433     });
24434     if(el){
24435         this.initEl(el);
24436     }
24437     Roo.form.BasicForm.superclass.constructor.call(this);
24438     
24439     Roo.form.BasicForm.popover.apply();
24440 };
24441
24442 Roo.extend(Roo.form.BasicForm, Roo.util.Observable, {
24443     /**
24444      * @cfg {String} method
24445      * The request method to use (GET or POST) for form actions if one isn't supplied in the action options.
24446      */
24447     /**
24448      * @cfg {DataReader} reader
24449      * An Roo.data.DataReader (e.g. {@link Roo.data.XmlReader}) to be used to read data when executing "load" actions.
24450      * This is optional as there is built-in support for processing JSON.
24451      */
24452     /**
24453      * @cfg {DataReader} errorReader
24454      * An Roo.data.DataReader (e.g. {@link Roo.data.XmlReader}) to be used to read data when reading validation errors on "submit" actions.
24455      * This is completely optional as there is built-in support for processing JSON.
24456      */
24457     /**
24458      * @cfg {String} url
24459      * The URL to use for form actions if one isn't supplied in the action options.
24460      */
24461     /**
24462      * @cfg {Boolean} fileUpload
24463      * Set to true if this form is a file upload.
24464      */
24465      
24466     /**
24467      * @cfg {Object} baseParams
24468      * Parameters to pass with all requests. e.g. baseParams: {id: '123', foo: 'bar'}.
24469      */
24470      /**
24471      
24472     /**
24473      * @cfg {Number} timeout Timeout for form actions in seconds (default is 30 seconds).
24474      */
24475     timeout: 30,
24476
24477     // private
24478     activeAction : null,
24479
24480     /**
24481      * @cfg {Boolean} trackResetOnLoad If set to true, form.reset() resets to the last loaded
24482      * or setValues() data instead of when the form was first created.
24483      */
24484     trackResetOnLoad : false,
24485     
24486     
24487     /**
24488      * childForms - used for multi-tab forms
24489      * @type {Array}
24490      */
24491     childForms : false,
24492     
24493     /**
24494      * allItems - full list of fields.
24495      * @type {Array}
24496      */
24497     allItems : false,
24498     
24499     /**
24500      * By default wait messages are displayed with Roo.MessageBox.wait. You can target a specific
24501      * element by passing it or its id or mask the form itself by passing in true.
24502      * @type Mixed
24503      */
24504     waitMsgTarget : false,
24505     
24506     /**
24507      * @type Boolean
24508      */
24509     disableMask : false,
24510     
24511     /**
24512      * @cfg {Boolean} errorMask (true|false) default false
24513      */
24514     errorMask : false,
24515     
24516     /**
24517      * @cfg {Number} maskOffset Default 100
24518      */
24519     maskOffset : 100,
24520
24521     // private
24522     initEl : function(el){
24523         this.el = Roo.get(el);
24524         this.id = this.el.id || Roo.id();
24525         this.el.on('submit', this.onSubmit, this);
24526         this.el.addClass('x-form');
24527     },
24528
24529     // private
24530     onSubmit : function(e){
24531         e.stopEvent();
24532     },
24533
24534     /**
24535      * Returns true if client-side validation on the form is successful.
24536      * @return Boolean
24537      */
24538     isValid : function(){
24539         var valid = true;
24540         var target = false;
24541         this.items.each(function(f){
24542             if(f.validate()){
24543                 return;
24544             }
24545             
24546             valid = false;
24547                 
24548             if(!target && f.el.isVisible(true)){
24549                 target = f;
24550             }
24551         });
24552         
24553         if(this.errorMask && !valid){
24554             Roo.form.BasicForm.popover.mask(this, target);
24555         }
24556         
24557         return valid;
24558     },
24559
24560     /**
24561      * DEPRICATED Returns true if any fields in this form have changed since their original load. 
24562      * @return Boolean
24563      */
24564     isDirty : function(){
24565         var dirty = false;
24566         this.items.each(function(f){
24567            if(f.isDirty()){
24568                dirty = true;
24569                return false;
24570            }
24571         });
24572         return dirty;
24573     },
24574     
24575     /**
24576      * Returns true if any fields in this form have changed since their original load. (New version)
24577      * @return Boolean
24578      */
24579     
24580     hasChanged : function()
24581     {
24582         var dirty = false;
24583         this.items.each(function(f){
24584            if(f.hasChanged()){
24585                dirty = true;
24586                return false;
24587            }
24588         });
24589         return dirty;
24590         
24591     },
24592     /**
24593      * Resets all hasChanged to 'false' -
24594      * The old 'isDirty' used 'original value..' however this breaks reset() and a few other things.
24595      * So hasChanged storage is only to be used for this purpose
24596      * @return Boolean
24597      */
24598     resetHasChanged : function()
24599     {
24600         this.items.each(function(f){
24601            f.resetHasChanged();
24602         });
24603         
24604     },
24605     
24606     
24607     /**
24608      * Performs a predefined action (submit or load) or custom actions you define on this form.
24609      * @param {String} actionName The name of the action type
24610      * @param {Object} options (optional) The options to pass to the action.  All of the config options listed
24611      * below are supported by both the submit and load actions unless otherwise noted (custom actions could also
24612      * accept other config options):
24613      * <pre>
24614 Property          Type             Description
24615 ----------------  ---------------  ----------------------------------------------------------------------------------
24616 url               String           The url for the action (defaults to the form's url)
24617 method            String           The form method to use (defaults to the form's method, or POST if not defined)
24618 params            String/Object    The params to pass (defaults to the form's baseParams, or none if not defined)
24619 clientValidation  Boolean          Applies to submit only.  Pass true to call form.isValid() prior to posting to
24620                                    validate the form on the client (defaults to false)
24621      * </pre>
24622      * @return {BasicForm} this
24623      */
24624     doAction : function(action, options){
24625         if(typeof action == 'string'){
24626             action = new Roo.form.Action.ACTION_TYPES[action](this, options);
24627         }
24628         if(this.fireEvent('beforeaction', this, action) !== false){
24629             this.beforeAction(action);
24630             action.run.defer(100, action);
24631         }
24632         return this;
24633     },
24634
24635     /**
24636      * Shortcut to do a submit action.
24637      * @param {Object} options The options to pass to the action (see {@link #doAction} for details)
24638      * @return {BasicForm} this
24639      */
24640     submit : function(options){
24641         this.doAction('submit', options);
24642         return this;
24643     },
24644
24645     /**
24646      * Shortcut to do a load action.
24647      * @param {Object} options The options to pass to the action (see {@link #doAction} for details)
24648      * @return {BasicForm} this
24649      */
24650     load : function(options){
24651         this.doAction('load', options);
24652         return this;
24653     },
24654
24655     /**
24656      * Persists the values in this form into the passed Roo.data.Record object in a beginEdit/endEdit block.
24657      * @param {Record} record The record to edit
24658      * @return {BasicForm} this
24659      */
24660     updateRecord : function(record){
24661         record.beginEdit();
24662         var fs = record.fields;
24663         fs.each(function(f){
24664             var field = this.findField(f.name);
24665             if(field){
24666                 record.set(f.name, field.getValue());
24667             }
24668         }, this);
24669         record.endEdit();
24670         return this;
24671     },
24672
24673     /**
24674      * Loads an Roo.data.Record into this form.
24675      * @param {Record} record The record to load
24676      * @return {BasicForm} this
24677      */
24678     loadRecord : function(record){
24679         this.setValues(record.data);
24680         return this;
24681     },
24682
24683     // private
24684     beforeAction : function(action){
24685         var o = action.options;
24686         
24687         if(!this.disableMask) {
24688             if(this.waitMsgTarget === true){
24689                 this.el.mask(o.waitMsg || "Sending", 'x-mask-loading');
24690             }else if(this.waitMsgTarget){
24691                 this.waitMsgTarget = Roo.get(this.waitMsgTarget);
24692                 this.waitMsgTarget.mask(o.waitMsg || "Sending", 'x-mask-loading');
24693             }else {
24694                 Roo.MessageBox.wait(o.waitMsg || "Sending", o.waitTitle || this.waitTitle || 'Please Wait...');
24695             }
24696         }
24697         
24698          
24699     },
24700
24701     // private
24702     afterAction : function(action, success){
24703         this.activeAction = null;
24704         var o = action.options;
24705         
24706         if(!this.disableMask) {
24707             if(this.waitMsgTarget === true){
24708                 this.el.unmask();
24709             }else if(this.waitMsgTarget){
24710                 this.waitMsgTarget.unmask();
24711             }else{
24712                 Roo.MessageBox.updateProgress(1);
24713                 Roo.MessageBox.hide();
24714             }
24715         }
24716         
24717         if(success){
24718             if(o.reset){
24719                 this.reset();
24720             }
24721             Roo.callback(o.success, o.scope, [this, action]);
24722             this.fireEvent('actioncomplete', this, action);
24723             
24724         }else{
24725             
24726             // failure condition..
24727             // we have a scenario where updates need confirming.
24728             // eg. if a locking scenario exists..
24729             // we look for { errors : { needs_confirm : true }} in the response.
24730             if (
24731                 (typeof(action.result) != 'undefined')  &&
24732                 (typeof(action.result.errors) != 'undefined')  &&
24733                 (typeof(action.result.errors.needs_confirm) != 'undefined')
24734            ){
24735                 var _t = this;
24736                 Roo.MessageBox.confirm(
24737                     "Change requires confirmation",
24738                     action.result.errorMsg,
24739                     function(r) {
24740                         if (r != 'yes') {
24741                             return;
24742                         }
24743                         _t.doAction('submit', { params :  { _submit_confirmed : 1 } }  );
24744                     }
24745                     
24746                 );
24747                 
24748                 
24749                 
24750                 return;
24751             }
24752             
24753             Roo.callback(o.failure, o.scope, [this, action]);
24754             // show an error message if no failed handler is set..
24755             if (!this.hasListener('actionfailed')) {
24756                 Roo.MessageBox.alert("Error",
24757                     (typeof(action.result) != 'undefined' && typeof(action.result.errorMsg) != 'undefined') ?
24758                         action.result.errorMsg :
24759                         "Saving Failed, please check your entries or try again"
24760                 );
24761             }
24762             
24763             this.fireEvent('actionfailed', this, action);
24764         }
24765         
24766     },
24767
24768     /**
24769      * Find a Roo.form.Field in this form by id, dataIndex, name or hiddenName
24770      * @param {String} id The value to search for
24771      * @return Field
24772      */
24773     findField : function(id){
24774         var field = this.items.get(id);
24775         if(!field){
24776             this.items.each(function(f){
24777                 if(f.isFormField && (f.dataIndex == id || f.id == id || f.getName() == id)){
24778                     field = f;
24779                     return false;
24780                 }
24781             });
24782         }
24783         return field || null;
24784     },
24785
24786     /**
24787      * Add a secondary form to this one, 
24788      * Used to provide tabbed forms. One form is primary, with hidden values 
24789      * which mirror the elements from the other forms.
24790      * 
24791      * @param {Roo.form.Form} form to add.
24792      * 
24793      */
24794     addForm : function(form)
24795     {
24796        
24797         if (this.childForms.indexOf(form) > -1) {
24798             // already added..
24799             return;
24800         }
24801         this.childForms.push(form);
24802         var n = '';
24803         Roo.each(form.allItems, function (fe) {
24804             
24805             n = typeof(fe.getName) == 'undefined' ? fe.name : fe.getName();
24806             if (this.findField(n)) { // already added..
24807                 return;
24808             }
24809             var add = new Roo.form.Hidden({
24810                 name : n
24811             });
24812             add.render(this.el);
24813             
24814             this.add( add );
24815         }, this);
24816         
24817     },
24818     /**
24819      * Mark fields in this form invalid in bulk.
24820      * @param {Array/Object} errors Either an array in the form [{id:'fieldId', msg:'The message'},...] or an object hash of {id: msg, id2: msg2}
24821      * @return {BasicForm} this
24822      */
24823     markInvalid : function(errors){
24824         if(errors instanceof Array){
24825             for(var i = 0, len = errors.length; i < len; i++){
24826                 var fieldError = errors[i];
24827                 var f = this.findField(fieldError.id);
24828                 if(f){
24829                     f.markInvalid(fieldError.msg);
24830                 }
24831             }
24832         }else{
24833             var field, id;
24834             for(id in errors){
24835                 if(typeof errors[id] != 'function' && (field = this.findField(id))){
24836                     field.markInvalid(errors[id]);
24837                 }
24838             }
24839         }
24840         Roo.each(this.childForms || [], function (f) {
24841             f.markInvalid(errors);
24842         });
24843         
24844         return this;
24845     },
24846
24847     /**
24848      * Set values for fields in this form in bulk.
24849      * @param {Array/Object} values Either an array in the form [{id:'fieldId', value:'foo'},...] or an object hash of {id: value, id2: value2}
24850      * @return {BasicForm} this
24851      */
24852     setValues : function(values){
24853         if(values instanceof Array){ // array of objects
24854             for(var i = 0, len = values.length; i < len; i++){
24855                 var v = values[i];
24856                 var f = this.findField(v.id);
24857                 if(f){
24858                     f.setValue(v.value);
24859                     if(this.trackResetOnLoad){
24860                         f.originalValue = f.getValue();
24861                     }
24862                 }
24863             }
24864         }else{ // object hash
24865             var field, id;
24866             for(id in values){
24867                 if(typeof values[id] != 'function' && (field = this.findField(id))){
24868                     
24869                     if (field.setFromData && 
24870                         field.valueField && 
24871                         field.displayField &&
24872                         // combos' with local stores can 
24873                         // be queried via setValue()
24874                         // to set their value..
24875                         (field.store && !field.store.isLocal)
24876                         ) {
24877                         // it's a combo
24878                         var sd = { };
24879                         sd[field.valueField] = typeof(values[field.hiddenName]) == 'undefined' ? '' : values[field.hiddenName];
24880                         sd[field.displayField] = typeof(values[field.name]) == 'undefined' ? '' : values[field.name];
24881                         field.setFromData(sd);
24882                         
24883                     } else {
24884                         field.setValue(values[id]);
24885                     }
24886                     
24887                     
24888                     if(this.trackResetOnLoad){
24889                         field.originalValue = field.getValue();
24890                     }
24891                 }
24892             }
24893         }
24894         this.resetHasChanged();
24895         
24896         
24897         Roo.each(this.childForms || [], function (f) {
24898             f.setValues(values);
24899             f.resetHasChanged();
24900         });
24901                 
24902         return this;
24903     },
24904  
24905     /**
24906      * Returns the fields in this form as an object with key/value pairs. If multiple fields exist with the same name
24907      * they are returned as an array.
24908      * @param {Boolean} asString
24909      * @return {Object}
24910      */
24911     getValues : function(asString){
24912         if (this.childForms) {
24913             // copy values from the child forms
24914             Roo.each(this.childForms, function (f) {
24915                 this.setValues(f.getValues());
24916             }, this);
24917         }
24918         
24919         // use formdata
24920         if (typeof(FormData) != 'undefined' && asString !== true) {
24921             var fd = (new FormData(this.el.dom)).entries();
24922             var ret = {};
24923             var ent = fd.next();
24924             while (!ent.done) {
24925                 ret[ent.value[0]] = ent.value[1]; // not sure how this will handle duplicates..
24926                 ent = fd.next();
24927             };
24928             return ret;
24929         }
24930         
24931         
24932         var fs = Roo.lib.Ajax.serializeForm(this.el.dom);
24933         if(asString === true){
24934             return fs;
24935         }
24936         return Roo.urlDecode(fs);
24937     },
24938     
24939     /**
24940      * Returns the fields in this form as an object with key/value pairs. 
24941      * This differs from getValues as it calls getValue on each child item, rather than using dom data.
24942      * @return {Object}
24943      */
24944     getFieldValues : function(with_hidden)
24945     {
24946         if (this.childForms) {
24947             // copy values from the child forms
24948             // should this call getFieldValues - probably not as we do not currently copy
24949             // hidden fields when we generate..
24950             Roo.each(this.childForms, function (f) {
24951                 this.setValues(f.getValues());
24952             }, this);
24953         }
24954         
24955         var ret = {};
24956         this.items.each(function(f){
24957             if (!f.getName()) {
24958                 return;
24959             }
24960             var v = f.getValue();
24961             if (f.inputType =='radio') {
24962                 if (typeof(ret[f.getName()]) == 'undefined') {
24963                     ret[f.getName()] = ''; // empty..
24964                 }
24965                 
24966                 if (!f.el.dom.checked) {
24967                     return;
24968                     
24969                 }
24970                 v = f.el.dom.value;
24971                 
24972             }
24973             
24974             // not sure if this supported any more..
24975             if ((typeof(v) == 'object') && f.getRawValue) {
24976                 v = f.getRawValue() ; // dates..
24977             }
24978             // combo boxes where name != hiddenName...
24979             if (f.name != f.getName()) {
24980                 ret[f.name] = f.getRawValue();
24981             }
24982             ret[f.getName()] = v;
24983         });
24984         
24985         return ret;
24986     },
24987
24988     /**
24989      * Clears all invalid messages in this form.
24990      * @return {BasicForm} this
24991      */
24992     clearInvalid : function(){
24993         this.items.each(function(f){
24994            f.clearInvalid();
24995         });
24996         
24997         Roo.each(this.childForms || [], function (f) {
24998             f.clearInvalid();
24999         });
25000         
25001         
25002         return this;
25003     },
25004
25005     /**
25006      * Resets this form.
25007      * @return {BasicForm} this
25008      */
25009     reset : function(){
25010         this.items.each(function(f){
25011             f.reset();
25012         });
25013         
25014         Roo.each(this.childForms || [], function (f) {
25015             f.reset();
25016         });
25017         this.resetHasChanged();
25018         
25019         return this;
25020     },
25021
25022     /**
25023      * Add Roo.form components to this form.
25024      * @param {Field} field1
25025      * @param {Field} field2 (optional)
25026      * @param {Field} etc (optional)
25027      * @return {BasicForm} this
25028      */
25029     add : function(){
25030         this.items.addAll(Array.prototype.slice.call(arguments, 0));
25031         return this;
25032     },
25033
25034
25035     /**
25036      * Removes a field from the items collection (does NOT remove its markup).
25037      * @param {Field} field
25038      * @return {BasicForm} this
25039      */
25040     remove : function(field){
25041         this.items.remove(field);
25042         return this;
25043     },
25044
25045     /**
25046      * Looks at the fields in this form, checks them for an id attribute,
25047      * and calls applyTo on the existing dom element with that id.
25048      * @return {BasicForm} this
25049      */
25050     render : function(){
25051         this.items.each(function(f){
25052             if(f.isFormField && !f.rendered && document.getElementById(f.id)){ // if the element exists
25053                 f.applyTo(f.id);
25054             }
25055         });
25056         return this;
25057     },
25058
25059     /**
25060      * Calls {@link Ext#apply} for all fields in this form with the passed object.
25061      * @param {Object} values
25062      * @return {BasicForm} this
25063      */
25064     applyToFields : function(o){
25065         this.items.each(function(f){
25066            Roo.apply(f, o);
25067         });
25068         return this;
25069     },
25070
25071     /**
25072      * Calls {@link Ext#applyIf} for all field in this form with the passed object.
25073      * @param {Object} values
25074      * @return {BasicForm} this
25075      */
25076     applyIfToFields : function(o){
25077         this.items.each(function(f){
25078            Roo.applyIf(f, o);
25079         });
25080         return this;
25081     }
25082 });
25083
25084 // back compat
25085 Roo.BasicForm = Roo.form.BasicForm;
25086
25087 Roo.apply(Roo.form.BasicForm, {
25088     
25089     popover : {
25090         
25091         padding : 5,
25092         
25093         isApplied : false,
25094         
25095         isMasked : false,
25096         
25097         form : false,
25098         
25099         target : false,
25100         
25101         intervalID : false,
25102         
25103         maskEl : false,
25104         
25105         apply : function()
25106         {
25107             if(this.isApplied){
25108                 return;
25109             }
25110             
25111             this.maskEl = {
25112                 top : Roo.DomHelper.append(Roo.get(document.body), { tag: "div", cls:"x-dlg-mask roo-form-top-mask" }, true),
25113                 left : Roo.DomHelper.append(Roo.get(document.body), { tag: "div", cls:"x-dlg-mask roo-form-left-mask" }, true),
25114                 bottom : Roo.DomHelper.append(Roo.get(document.body), { tag: "div", cls:"x-dlg-mask roo-form-bottom-mask" }, true),
25115                 right : Roo.DomHelper.append(Roo.get(document.body), { tag: "div", cls:"x-dlg-mask roo-form-right-mask" }, true)
25116             };
25117             
25118             this.maskEl.top.enableDisplayMode("block");
25119             this.maskEl.left.enableDisplayMode("block");
25120             this.maskEl.bottom.enableDisplayMode("block");
25121             this.maskEl.right.enableDisplayMode("block");
25122             
25123             Roo.get(document.body).on('click', function(){
25124                 this.unmask();
25125             }, this);
25126             
25127             Roo.get(document.body).on('touchstart', function(){
25128                 this.unmask();
25129             }, this);
25130             
25131             this.isApplied = true
25132         },
25133         
25134         mask : function(form, target)
25135         {
25136             this.form = form;
25137             
25138             this.target = target;
25139             
25140             if(!this.form.errorMask || !target.el){
25141                 return;
25142             }
25143             
25144             var scrollable = this.target.el.findScrollableParent() || this.target.el.findParent('div.x-layout-active-content', 100, true) || Roo.get(document.body);
25145             
25146             var ot = this.target.el.calcOffsetsTo(scrollable);
25147             
25148             var scrollTo = ot[1] - this.form.maskOffset;
25149             
25150             scrollTo = Math.min(scrollTo, scrollable.dom.scrollHeight);
25151             
25152             scrollable.scrollTo('top', scrollTo);
25153             
25154             var el = this.target.wrap || this.target.el;
25155             
25156             var box = el.getBox();
25157             
25158             this.maskEl.top.setStyle('position', 'absolute');
25159             this.maskEl.top.setStyle('z-index', 10000);
25160             this.maskEl.top.setSize(Roo.lib.Dom.getDocumentWidth(), box.y - this.padding);
25161             this.maskEl.top.setLeft(0);
25162             this.maskEl.top.setTop(0);
25163             this.maskEl.top.show();
25164             
25165             this.maskEl.left.setStyle('position', 'absolute');
25166             this.maskEl.left.setStyle('z-index', 10000);
25167             this.maskEl.left.setSize(box.x - this.padding, box.height + this.padding * 2);
25168             this.maskEl.left.setLeft(0);
25169             this.maskEl.left.setTop(box.y - this.padding);
25170             this.maskEl.left.show();
25171
25172             this.maskEl.bottom.setStyle('position', 'absolute');
25173             this.maskEl.bottom.setStyle('z-index', 10000);
25174             this.maskEl.bottom.setSize(Roo.lib.Dom.getDocumentWidth(), Roo.lib.Dom.getDocumentHeight() - box.bottom - this.padding);
25175             this.maskEl.bottom.setLeft(0);
25176             this.maskEl.bottom.setTop(box.bottom + this.padding);
25177             this.maskEl.bottom.show();
25178
25179             this.maskEl.right.setStyle('position', 'absolute');
25180             this.maskEl.right.setStyle('z-index', 10000);
25181             this.maskEl.right.setSize(Roo.lib.Dom.getDocumentWidth() - box.right - this.padding, box.height + this.padding * 2);
25182             this.maskEl.right.setLeft(box.right + this.padding);
25183             this.maskEl.right.setTop(box.y - this.padding);
25184             this.maskEl.right.show();
25185
25186             this.intervalID = window.setInterval(function() {
25187                 Roo.form.BasicForm.popover.unmask();
25188             }, 10000);
25189
25190             window.onwheel = function(){ return false;};
25191             
25192             (function(){ this.isMasked = true; }).defer(500, this);
25193             
25194         },
25195         
25196         unmask : function()
25197         {
25198             if(!this.isApplied || !this.isMasked || !this.form || !this.target || !this.form.errorMask){
25199                 return;
25200             }
25201             
25202             this.maskEl.top.setStyle('position', 'absolute');
25203             this.maskEl.top.setSize(0, 0).setXY([0, 0]);
25204             this.maskEl.top.hide();
25205
25206             this.maskEl.left.setStyle('position', 'absolute');
25207             this.maskEl.left.setSize(0, 0).setXY([0, 0]);
25208             this.maskEl.left.hide();
25209
25210             this.maskEl.bottom.setStyle('position', 'absolute');
25211             this.maskEl.bottom.setSize(0, 0).setXY([0, 0]);
25212             this.maskEl.bottom.hide();
25213
25214             this.maskEl.right.setStyle('position', 'absolute');
25215             this.maskEl.right.setSize(0, 0).setXY([0, 0]);
25216             this.maskEl.right.hide();
25217             
25218             window.onwheel = function(){ return true;};
25219             
25220             if(this.intervalID){
25221                 window.clearInterval(this.intervalID);
25222                 this.intervalID = false;
25223             }
25224             
25225             this.isMasked = false;
25226             
25227         }
25228         
25229     }
25230     
25231 });/*
25232  * Based on:
25233  * Ext JS Library 1.1.1
25234  * Copyright(c) 2006-2007, Ext JS, LLC.
25235  *
25236  * Originally Released Under LGPL - original licence link has changed is not relivant.
25237  *
25238  * Fork - LGPL
25239  * <script type="text/javascript">
25240  */
25241
25242 /**
25243  * @class Roo.form.Form
25244  * @extends Roo.form.BasicForm
25245  * Adds the ability to dynamically render forms with JavaScript to {@link Roo.form.BasicForm}.
25246  * @constructor
25247  * @param {Object} config Configuration options
25248  */
25249 Roo.form.Form = function(config){
25250     var xitems =  [];
25251     if (config.items) {
25252         xitems = config.items;
25253         delete config.items;
25254     }
25255    
25256     
25257     Roo.form.Form.superclass.constructor.call(this, null, config);
25258     this.url = this.url || this.action;
25259     if(!this.root){
25260         this.root = new Roo.form.Layout(Roo.applyIf({
25261             id: Roo.id()
25262         }, config));
25263     }
25264     this.active = this.root;
25265     /**
25266      * Array of all the buttons that have been added to this form via {@link addButton}
25267      * @type Array
25268      */
25269     this.buttons = [];
25270     this.allItems = [];
25271     this.addEvents({
25272         /**
25273          * @event clientvalidation
25274          * If the monitorValid config option is true, this event fires repetitively to notify of valid state
25275          * @param {Form} this
25276          * @param {Boolean} valid true if the form has passed client-side validation
25277          */
25278         clientvalidation: true,
25279         /**
25280          * @event rendered
25281          * Fires when the form is rendered
25282          * @param {Roo.form.Form} form
25283          */
25284         rendered : true
25285     });
25286     
25287     if (this.progressUrl) {
25288             // push a hidden field onto the list of fields..
25289             this.addxtype( {
25290                     xns: Roo.form, 
25291                     xtype : 'Hidden', 
25292                     name : 'UPLOAD_IDENTIFIER' 
25293             });
25294         }
25295         
25296     
25297     Roo.each(xitems, this.addxtype, this);
25298     
25299 };
25300
25301 Roo.extend(Roo.form.Form, Roo.form.BasicForm, {
25302     /**
25303      * @cfg {Number} labelWidth The width of labels. This property cascades to child containers.
25304      */
25305     /**
25306      * @cfg {String} itemCls A css class to apply to the x-form-item of fields. This property cascades to child containers.
25307      */
25308     /**
25309      * @cfg {String} buttonAlign Valid values are "left," "center" and "right" (defaults to "center")
25310      */
25311     buttonAlign:'center',
25312
25313     /**
25314      * @cfg {Number} minButtonWidth Minimum width of all buttons in pixels (defaults to 75)
25315      */
25316     minButtonWidth:75,
25317
25318     /**
25319      * @cfg {String} labelAlign Valid values are "left," "top" and "right" (defaults to "left").
25320      * This property cascades to child containers if not set.
25321      */
25322     labelAlign:'left',
25323
25324     /**
25325      * @cfg {Boolean} monitorValid If true the form monitors its valid state <b>client-side</b> and
25326      * fires a looping event with that state. This is required to bind buttons to the valid
25327      * state using the config value formBind:true on the button.
25328      */
25329     monitorValid : false,
25330
25331     /**
25332      * @cfg {Number} monitorPoll The milliseconds to poll valid state, ignored if monitorValid is not true (defaults to 200)
25333      */
25334     monitorPoll : 200,
25335     
25336     /**
25337      * @cfg {String} progressUrl - Url to return progress data 
25338      */
25339     
25340     progressUrl : false,
25341     /**
25342      * @cfg {boolean|FormData} formData - true to use new 'FormData' post, or set to a new FormData({dom form}) Object, if
25343      * sending a formdata with extra parameters - eg uploaded elements.
25344      */
25345     
25346     formData : false,
25347     
25348     /**
25349      * Opens a new {@link Roo.form.Column} container in the layout stack. If fields are passed after the config, the
25350      * fields are added and the column is closed. If no fields are passed the column remains open
25351      * until end() is called.
25352      * @param {Object} config The config to pass to the column
25353      * @param {Field} field1 (optional)
25354      * @param {Field} field2 (optional)
25355      * @param {Field} etc (optional)
25356      * @return Column The column container object
25357      */
25358     column : function(c){
25359         var col = new Roo.form.Column(c);
25360         this.start(col);
25361         if(arguments.length > 1){ // duplicate code required because of Opera
25362             this.add.apply(this, Array.prototype.slice.call(arguments, 1));
25363             this.end();
25364         }
25365         return col;
25366     },
25367
25368     /**
25369      * Opens a new {@link Roo.form.FieldSet} container in the layout stack. If fields are passed after the config, the
25370      * fields are added and the fieldset is closed. If no fields are passed the fieldset remains open
25371      * until end() is called.
25372      * @param {Object} config The config to pass to the fieldset
25373      * @param {Field} field1 (optional)
25374      * @param {Field} field2 (optional)
25375      * @param {Field} etc (optional)
25376      * @return FieldSet The fieldset container object
25377      */
25378     fieldset : function(c){
25379         var fs = new Roo.form.FieldSet(c);
25380         this.start(fs);
25381         if(arguments.length > 1){ // duplicate code required because of Opera
25382             this.add.apply(this, Array.prototype.slice.call(arguments, 1));
25383             this.end();
25384         }
25385         return fs;
25386     },
25387
25388     /**
25389      * Opens a new {@link Roo.form.Layout} container in the layout stack. If fields are passed after the config, the
25390      * fields are added and the container is closed. If no fields are passed the container remains open
25391      * until end() is called.
25392      * @param {Object} config The config to pass to the Layout
25393      * @param {Field} field1 (optional)
25394      * @param {Field} field2 (optional)
25395      * @param {Field} etc (optional)
25396      * @return Layout The container object
25397      */
25398     container : function(c){
25399         var l = new Roo.form.Layout(c);
25400         this.start(l);
25401         if(arguments.length > 1){ // duplicate code required because of Opera
25402             this.add.apply(this, Array.prototype.slice.call(arguments, 1));
25403             this.end();
25404         }
25405         return l;
25406     },
25407
25408     /**
25409      * Opens the passed container in the layout stack. The container can be any {@link Roo.form.Layout} or subclass.
25410      * @param {Object} container A Roo.form.Layout or subclass of Layout
25411      * @return {Form} this
25412      */
25413     start : function(c){
25414         // cascade label info
25415         Roo.applyIf(c, {'labelAlign': this.active.labelAlign, 'labelWidth': this.active.labelWidth, 'itemCls': this.active.itemCls});
25416         this.active.stack.push(c);
25417         c.ownerCt = this.active;
25418         this.active = c;
25419         return this;
25420     },
25421
25422     /**
25423      * Closes the current open container
25424      * @return {Form} this
25425      */
25426     end : function(){
25427         if(this.active == this.root){
25428             return this;
25429         }
25430         this.active = this.active.ownerCt;
25431         return this;
25432     },
25433
25434     /**
25435      * Add Roo.form components to the current open container (e.g. column, fieldset, etc.).  Fields added via this method
25436      * can also be passed with an additional property of fieldLabel, which if supplied, will provide the text to display
25437      * as the label of the field.
25438      * @param {Field} field1
25439      * @param {Field} field2 (optional)
25440      * @param {Field} etc. (optional)
25441      * @return {Form} this
25442      */
25443     add : function(){
25444         this.active.stack.push.apply(this.active.stack, arguments);
25445         this.allItems.push.apply(this.allItems,arguments);
25446         var r = [];
25447         for(var i = 0, a = arguments, len = a.length; i < len; i++) {
25448             if(a[i].isFormField){
25449                 r.push(a[i]);
25450             }
25451         }
25452         if(r.length > 0){
25453             Roo.form.Form.superclass.add.apply(this, r);
25454         }
25455         return this;
25456     },
25457     
25458
25459     
25460     
25461     
25462      /**
25463      * Find any element that has been added to a form, using it's ID or name
25464      * This can include framesets, columns etc. along with regular fields..
25465      * @param {String} id - id or name to find.
25466      
25467      * @return {Element} e - or false if nothing found.
25468      */
25469     findbyId : function(id)
25470     {
25471         var ret = false;
25472         if (!id) {
25473             return ret;
25474         }
25475         Roo.each(this.allItems, function(f){
25476             if (f.id == id || f.name == id ){
25477                 ret = f;
25478                 return false;
25479             }
25480         });
25481         return ret;
25482     },
25483
25484     
25485     
25486     /**
25487      * Render this form into the passed container. This should only be called once!
25488      * @param {String/HTMLElement/Element} container The element this component should be rendered into
25489      * @return {Form} this
25490      */
25491     render : function(ct)
25492     {
25493         
25494         
25495         
25496         ct = Roo.get(ct);
25497         var o = this.autoCreate || {
25498             tag: 'form',
25499             method : this.method || 'POST',
25500             id : this.id || Roo.id()
25501         };
25502         this.initEl(ct.createChild(o));
25503
25504         this.root.render(this.el);
25505         
25506        
25507              
25508         this.items.each(function(f){
25509             f.render('x-form-el-'+f.id);
25510         });
25511
25512         if(this.buttons.length > 0){
25513             // tables are required to maintain order and for correct IE layout
25514             var tb = this.el.createChild({cls:'x-form-btns-ct', cn: {
25515                 cls:"x-form-btns x-form-btns-"+this.buttonAlign,
25516                 html:'<table cellspacing="0"><tbody><tr></tr></tbody></table><div class="x-clear"></div>'
25517             }}, null, true);
25518             var tr = tb.getElementsByTagName('tr')[0];
25519             for(var i = 0, len = this.buttons.length; i < len; i++) {
25520                 var b = this.buttons[i];
25521                 var td = document.createElement('td');
25522                 td.className = 'x-form-btn-td';
25523                 b.render(tr.appendChild(td));
25524             }
25525         }
25526         if(this.monitorValid){ // initialize after render
25527             this.startMonitoring();
25528         }
25529         this.fireEvent('rendered', this);
25530         return this;
25531     },
25532
25533     /**
25534      * Adds a button to the footer of the form - this <b>must</b> be called before the form is rendered.
25535      * @param {String/Object} config A string becomes the button text, an object can either be a Button config
25536      * object or a valid Roo.DomHelper element config
25537      * @param {Function} handler The function called when the button is clicked
25538      * @param {Object} scope (optional) The scope of the handler function
25539      * @return {Roo.Button}
25540      */
25541     addButton : function(config, handler, scope){
25542         var bc = {
25543             handler: handler,
25544             scope: scope,
25545             minWidth: this.minButtonWidth,
25546             hideParent:true
25547         };
25548         if(typeof config == "string"){
25549             bc.text = config;
25550         }else{
25551             Roo.apply(bc, config);
25552         }
25553         var btn = new Roo.Button(null, bc);
25554         this.buttons.push(btn);
25555         return btn;
25556     },
25557
25558      /**
25559      * Adds a series of form elements (using the xtype property as the factory method.
25560      * Valid xtypes are:  TextField, TextArea .... Button, Layout, FieldSet, Column, (and 'end' to close a block)
25561      * @param {Object} config 
25562      */
25563     
25564     addxtype : function()
25565     {
25566         var ar = Array.prototype.slice.call(arguments, 0);
25567         var ret = false;
25568         for(var i = 0; i < ar.length; i++) {
25569             if (!ar[i]) {
25570                 continue; // skip -- if this happends something invalid got sent, we 
25571                 // should ignore it, as basically that interface element will not show up
25572                 // and that should be pretty obvious!!
25573             }
25574             
25575             if (Roo.form[ar[i].xtype]) {
25576                 ar[i].form = this;
25577                 var fe = Roo.factory(ar[i], Roo.form);
25578                 if (!ret) {
25579                     ret = fe;
25580                 }
25581                 fe.form = this;
25582                 if (fe.store) {
25583                     fe.store.form = this;
25584                 }
25585                 if (fe.isLayout) {  
25586                          
25587                     this.start(fe);
25588                     this.allItems.push(fe);
25589                     if (fe.items && fe.addxtype) {
25590                         fe.addxtype.apply(fe, fe.items);
25591                         delete fe.items;
25592                     }
25593                      this.end();
25594                     continue;
25595                 }
25596                 
25597                 
25598                  
25599                 this.add(fe);
25600               //  console.log('adding ' + ar[i].xtype);
25601             }
25602             if (ar[i].xtype == 'Button') {  
25603                 //console.log('adding button');
25604                 //console.log(ar[i]);
25605                 this.addButton(ar[i]);
25606                 this.allItems.push(fe);
25607                 continue;
25608             }
25609             
25610             if (ar[i].xtype == 'end') { // so we can add fieldsets... / layout etc.
25611                 alert('end is not supported on xtype any more, use items');
25612             //    this.end();
25613             //    //console.log('adding end');
25614             }
25615             
25616         }
25617         return ret;
25618     },
25619     
25620     /**
25621      * Starts monitoring of the valid state of this form. Usually this is done by passing the config
25622      * option "monitorValid"
25623      */
25624     startMonitoring : function(){
25625         if(!this.bound){
25626             this.bound = true;
25627             Roo.TaskMgr.start({
25628                 run : this.bindHandler,
25629                 interval : this.monitorPoll || 200,
25630                 scope: this
25631             });
25632         }
25633     },
25634
25635     /**
25636      * Stops monitoring of the valid state of this form
25637      */
25638     stopMonitoring : function(){
25639         this.bound = false;
25640     },
25641
25642     // private
25643     bindHandler : function(){
25644         if(!this.bound){
25645             return false; // stops binding
25646         }
25647         var valid = true;
25648         this.items.each(function(f){
25649             if(!f.isValid(true)){
25650                 valid = false;
25651                 return false;
25652             }
25653         });
25654         for(var i = 0, len = this.buttons.length; i < len; i++){
25655             var btn = this.buttons[i];
25656             if(btn.formBind === true && btn.disabled === valid){
25657                 btn.setDisabled(!valid);
25658             }
25659         }
25660         this.fireEvent('clientvalidation', this, valid);
25661     }
25662     
25663     
25664     
25665     
25666     
25667     
25668     
25669     
25670 });
25671
25672
25673 // back compat
25674 Roo.Form = Roo.form.Form;
25675 /*
25676  * Based on:
25677  * Ext JS Library 1.1.1
25678  * Copyright(c) 2006-2007, Ext JS, LLC.
25679  *
25680  * Originally Released Under LGPL - original licence link has changed is not relivant.
25681  *
25682  * Fork - LGPL
25683  * <script type="text/javascript">
25684  */
25685
25686 // as we use this in bootstrap.
25687 Roo.namespace('Roo.form');
25688  /**
25689  * @class Roo.form.Action
25690  * Internal Class used to handle form actions
25691  * @constructor
25692  * @param {Roo.form.BasicForm} el The form element or its id
25693  * @param {Object} config Configuration options
25694  */
25695
25696  
25697  
25698 // define the action interface
25699 Roo.form.Action = function(form, options){
25700     this.form = form;
25701     this.options = options || {};
25702 };
25703 /**
25704  * Client Validation Failed
25705  * @const 
25706  */
25707 Roo.form.Action.CLIENT_INVALID = 'client';
25708 /**
25709  * Server Validation Failed
25710  * @const 
25711  */
25712 Roo.form.Action.SERVER_INVALID = 'server';
25713  /**
25714  * Connect to Server Failed
25715  * @const 
25716  */
25717 Roo.form.Action.CONNECT_FAILURE = 'connect';
25718 /**
25719  * Reading Data from Server Failed
25720  * @const 
25721  */
25722 Roo.form.Action.LOAD_FAILURE = 'load';
25723
25724 Roo.form.Action.prototype = {
25725     type : 'default',
25726     failureType : undefined,
25727     response : undefined,
25728     result : undefined,
25729
25730     // interface method
25731     run : function(options){
25732
25733     },
25734
25735     // interface method
25736     success : function(response){
25737
25738     },
25739
25740     // interface method
25741     handleResponse : function(response){
25742
25743     },
25744
25745     // default connection failure
25746     failure : function(response){
25747         
25748         this.response = response;
25749         this.failureType = Roo.form.Action.CONNECT_FAILURE;
25750         this.form.afterAction(this, false);
25751     },
25752
25753     processResponse : function(response){
25754         this.response = response;
25755         if(!response.responseText){
25756             return true;
25757         }
25758         this.result = this.handleResponse(response);
25759         return this.result;
25760     },
25761
25762     // utility functions used internally
25763     getUrl : function(appendParams){
25764         var url = this.options.url || this.form.url || this.form.el.dom.action;
25765         if(appendParams){
25766             var p = this.getParams();
25767             if(p){
25768                 url += (url.indexOf('?') != -1 ? '&' : '?') + p;
25769             }
25770         }
25771         return url;
25772     },
25773
25774     getMethod : function(){
25775         return (this.options.method || this.form.method || this.form.el.dom.method || 'POST').toUpperCase();
25776     },
25777
25778     getParams : function(){
25779         var bp = this.form.baseParams;
25780         var p = this.options.params;
25781         if(p){
25782             if(typeof p == "object"){
25783                 p = Roo.urlEncode(Roo.applyIf(p, bp));
25784             }else if(typeof p == 'string' && bp){
25785                 p += '&' + Roo.urlEncode(bp);
25786             }
25787         }else if(bp){
25788             p = Roo.urlEncode(bp);
25789         }
25790         return p;
25791     },
25792
25793     createCallback : function(){
25794         return {
25795             success: this.success,
25796             failure: this.failure,
25797             scope: this,
25798             timeout: (this.form.timeout*1000),
25799             upload: this.form.fileUpload ? this.success : undefined
25800         };
25801     }
25802 };
25803
25804 Roo.form.Action.Submit = function(form, options){
25805     Roo.form.Action.Submit.superclass.constructor.call(this, form, options);
25806 };
25807
25808 Roo.extend(Roo.form.Action.Submit, Roo.form.Action, {
25809     type : 'submit',
25810
25811     haveProgress : false,
25812     uploadComplete : false,
25813     
25814     // uploadProgress indicator.
25815     uploadProgress : function()
25816     {
25817         if (!this.form.progressUrl) {
25818             return;
25819         }
25820         
25821         if (!this.haveProgress) {
25822             Roo.MessageBox.progress("Uploading", "Uploading");
25823         }
25824         if (this.uploadComplete) {
25825            Roo.MessageBox.hide();
25826            return;
25827         }
25828         
25829         this.haveProgress = true;
25830    
25831         var uid = this.form.findField('UPLOAD_IDENTIFIER').getValue();
25832         
25833         var c = new Roo.data.Connection();
25834         c.request({
25835             url : this.form.progressUrl,
25836             params: {
25837                 id : uid
25838             },
25839             method: 'GET',
25840             success : function(req){
25841                //console.log(data);
25842                 var rdata = false;
25843                 var edata;
25844                 try  {
25845                    rdata = Roo.decode(req.responseText)
25846                 } catch (e) {
25847                     Roo.log("Invalid data from server..");
25848                     Roo.log(edata);
25849                     return;
25850                 }
25851                 if (!rdata || !rdata.success) {
25852                     Roo.log(rdata);
25853                     Roo.MessageBox.alert(Roo.encode(rdata));
25854                     return;
25855                 }
25856                 var data = rdata.data;
25857                 
25858                 if (this.uploadComplete) {
25859                    Roo.MessageBox.hide();
25860                    return;
25861                 }
25862                    
25863                 if (data){
25864                     Roo.MessageBox.updateProgress(data.bytes_uploaded/data.bytes_total,
25865                        Math.floor((data.bytes_total - data.bytes_uploaded)/1000) + 'k remaining'
25866                     );
25867                 }
25868                 this.uploadProgress.defer(2000,this);
25869             },
25870        
25871             failure: function(data) {
25872                 Roo.log('progress url failed ');
25873                 Roo.log(data);
25874             },
25875             scope : this
25876         });
25877            
25878     },
25879     
25880     
25881     run : function()
25882     {
25883         // run get Values on the form, so it syncs any secondary forms.
25884         this.form.getValues();
25885         
25886         var o = this.options;
25887         var method = this.getMethod();
25888         var isPost = method == 'POST';
25889         if(o.clientValidation === false || this.form.isValid()){
25890             
25891             if (this.form.progressUrl) {
25892                 this.form.findField('UPLOAD_IDENTIFIER').setValue(
25893                     (new Date() * 1) + '' + Math.random());
25894                     
25895             } 
25896             
25897             
25898             Roo.Ajax.request(Roo.apply(this.createCallback(), {
25899                 form:this.form.el.dom,
25900                 url:this.getUrl(!isPost),
25901                 method: method,
25902                 params:isPost ? this.getParams() : null,
25903                 isUpload: this.form.fileUpload,
25904                 formData : this.form.formData
25905             }));
25906             
25907             this.uploadProgress();
25908
25909         }else if (o.clientValidation !== false){ // client validation failed
25910             this.failureType = Roo.form.Action.CLIENT_INVALID;
25911             this.form.afterAction(this, false);
25912         }
25913     },
25914
25915     success : function(response)
25916     {
25917         this.uploadComplete= true;
25918         if (this.haveProgress) {
25919             Roo.MessageBox.hide();
25920         }
25921         
25922         
25923         var result = this.processResponse(response);
25924         if(result === true || result.success){
25925             this.form.afterAction(this, true);
25926             return;
25927         }
25928         if(result.errors){
25929             this.form.markInvalid(result.errors);
25930             this.failureType = Roo.form.Action.SERVER_INVALID;
25931         }
25932         this.form.afterAction(this, false);
25933     },
25934     failure : function(response)
25935     {
25936         this.uploadComplete= true;
25937         if (this.haveProgress) {
25938             Roo.MessageBox.hide();
25939         }
25940         
25941         this.response = response;
25942         this.failureType = Roo.form.Action.CONNECT_FAILURE;
25943         this.form.afterAction(this, false);
25944     },
25945     
25946     handleResponse : function(response){
25947         if(this.form.errorReader){
25948             var rs = this.form.errorReader.read(response);
25949             var errors = [];
25950             if(rs.records){
25951                 for(var i = 0, len = rs.records.length; i < len; i++) {
25952                     var r = rs.records[i];
25953                     errors[i] = r.data;
25954                 }
25955             }
25956             if(errors.length < 1){
25957                 errors = null;
25958             }
25959             return {
25960                 success : rs.success,
25961                 errors : errors
25962             };
25963         }
25964         var ret = false;
25965         try {
25966             ret = Roo.decode(response.responseText);
25967         } catch (e) {
25968             ret = {
25969                 success: false,
25970                 errorMsg: "Failed to read server message: " + (response ? response.responseText : ' - no message'),
25971                 errors : []
25972             };
25973         }
25974         return ret;
25975         
25976     }
25977 });
25978
25979
25980 Roo.form.Action.Load = function(form, options){
25981     Roo.form.Action.Load.superclass.constructor.call(this, form, options);
25982     this.reader = this.form.reader;
25983 };
25984
25985 Roo.extend(Roo.form.Action.Load, Roo.form.Action, {
25986     type : 'load',
25987
25988     run : function(){
25989         
25990         Roo.Ajax.request(Roo.apply(
25991                 this.createCallback(), {
25992                     method:this.getMethod(),
25993                     url:this.getUrl(false),
25994                     params:this.getParams()
25995         }));
25996     },
25997
25998     success : function(response){
25999         
26000         var result = this.processResponse(response);
26001         if(result === true || !result.success || !result.data){
26002             this.failureType = Roo.form.Action.LOAD_FAILURE;
26003             this.form.afterAction(this, false);
26004             return;
26005         }
26006         this.form.clearInvalid();
26007         this.form.setValues(result.data);
26008         this.form.afterAction(this, true);
26009     },
26010
26011     handleResponse : function(response){
26012         if(this.form.reader){
26013             var rs = this.form.reader.read(response);
26014             var data = rs.records && rs.records[0] ? rs.records[0].data : null;
26015             return {
26016                 success : rs.success,
26017                 data : data
26018             };
26019         }
26020         return Roo.decode(response.responseText);
26021     }
26022 });
26023
26024 Roo.form.Action.ACTION_TYPES = {
26025     'load' : Roo.form.Action.Load,
26026     'submit' : Roo.form.Action.Submit
26027 };/*
26028  * Based on:
26029  * Ext JS Library 1.1.1
26030  * Copyright(c) 2006-2007, Ext JS, LLC.
26031  *
26032  * Originally Released Under LGPL - original licence link has changed is not relivant.
26033  *
26034  * Fork - LGPL
26035  * <script type="text/javascript">
26036  */
26037  
26038 /**
26039  * @class Roo.form.Layout
26040  * @extends Roo.Component
26041  * Creates a container for layout and rendering of fields in an {@link Roo.form.Form}.
26042  * @constructor
26043  * @param {Object} config Configuration options
26044  */
26045 Roo.form.Layout = function(config){
26046     var xitems = [];
26047     if (config.items) {
26048         xitems = config.items;
26049         delete config.items;
26050     }
26051     Roo.form.Layout.superclass.constructor.call(this, config);
26052     this.stack = [];
26053     Roo.each(xitems, this.addxtype, this);
26054      
26055 };
26056
26057 Roo.extend(Roo.form.Layout, Roo.Component, {
26058     /**
26059      * @cfg {String/Object} autoCreate
26060      * A DomHelper element spec used to autocreate the layout (defaults to {tag: 'div', cls: 'x-form-ct'})
26061      */
26062     /**
26063      * @cfg {String/Object/Function} style
26064      * A style specification string, e.g. "width:100px", or object in the form {width:"100px"}, or
26065      * a function which returns such a specification.
26066      */
26067     /**
26068      * @cfg {String} labelAlign
26069      * Valid values are "left," "top" and "right" (defaults to "left")
26070      */
26071     /**
26072      * @cfg {Number} labelWidth
26073      * Fixed width in pixels of all field labels (defaults to undefined)
26074      */
26075     /**
26076      * @cfg {Boolean} clear
26077      * True to add a clearing element at the end of this layout, equivalent to CSS clear: both (defaults to true)
26078      */
26079     clear : true,
26080     /**
26081      * @cfg {String} labelSeparator
26082      * The separator to use after field labels (defaults to ':')
26083      */
26084     labelSeparator : ':',
26085     /**
26086      * @cfg {Boolean} hideLabels
26087      * True to suppress the display of field labels in this layout (defaults to false)
26088      */
26089     hideLabels : false,
26090
26091     // private
26092     defaultAutoCreate : {tag: 'div', cls: 'x-form-ct'},
26093     
26094     isLayout : true,
26095     
26096     // private
26097     onRender : function(ct, position){
26098         if(this.el){ // from markup
26099             this.el = Roo.get(this.el);
26100         }else {  // generate
26101             var cfg = this.getAutoCreate();
26102             this.el = ct.createChild(cfg, position);
26103         }
26104         if(this.style){
26105             this.el.applyStyles(this.style);
26106         }
26107         if(this.labelAlign){
26108             this.el.addClass('x-form-label-'+this.labelAlign);
26109         }
26110         if(this.hideLabels){
26111             this.labelStyle = "display:none";
26112             this.elementStyle = "padding-left:0;";
26113         }else{
26114             if(typeof this.labelWidth == 'number'){
26115                 this.labelStyle = "width:"+this.labelWidth+"px;";
26116                 this.elementStyle = "padding-left:"+((this.labelWidth+(typeof this.labelPad == 'number' ? this.labelPad : 5))+'px')+";";
26117             }
26118             if(this.labelAlign == 'top'){
26119                 this.labelStyle = "width:auto;";
26120                 this.elementStyle = "padding-left:0;";
26121             }
26122         }
26123         var stack = this.stack;
26124         var slen = stack.length;
26125         if(slen > 0){
26126             if(!this.fieldTpl){
26127                 var t = new Roo.Template(
26128                     '<div class="x-form-item {5}">',
26129                         '<label for="{0}" style="{2}">{1}{4}</label>',
26130                         '<div class="x-form-element" id="x-form-el-{0}" style="{3}">',
26131                         '</div>',
26132                     '</div><div class="x-form-clear-left"></div>'
26133                 );
26134                 t.disableFormats = true;
26135                 t.compile();
26136                 Roo.form.Layout.prototype.fieldTpl = t;
26137             }
26138             for(var i = 0; i < slen; i++) {
26139                 if(stack[i].isFormField){
26140                     this.renderField(stack[i]);
26141                 }else{
26142                     this.renderComponent(stack[i]);
26143                 }
26144             }
26145         }
26146         if(this.clear){
26147             this.el.createChild({cls:'x-form-clear'});
26148         }
26149     },
26150
26151     // private
26152     renderField : function(f){
26153         f.fieldEl = Roo.get(this.fieldTpl.append(this.el, [
26154                f.id, //0
26155                f.fieldLabel, //1
26156                f.labelStyle||this.labelStyle||'', //2
26157                this.elementStyle||'', //3
26158                typeof f.labelSeparator == 'undefined' ? this.labelSeparator : f.labelSeparator, //4
26159                f.itemCls||this.itemCls||''  //5
26160        ], true).getPrevSibling());
26161     },
26162
26163     // private
26164     renderComponent : function(c){
26165         c.render(c.isLayout ? this.el : this.el.createChild());    
26166     },
26167     /**
26168      * Adds a object form elements (using the xtype property as the factory method.)
26169      * Valid xtypes are:  TextField, TextArea .... Button, Layout, FieldSet, Column
26170      * @param {Object} config 
26171      */
26172     addxtype : function(o)
26173     {
26174         // create the lement.
26175         o.form = this.form;
26176         var fe = Roo.factory(o, Roo.form);
26177         this.form.allItems.push(fe);
26178         this.stack.push(fe);
26179         
26180         if (fe.isFormField) {
26181             this.form.items.add(fe);
26182         }
26183          
26184         return fe;
26185     }
26186 });
26187
26188 /**
26189  * @class Roo.form.Column
26190  * @extends Roo.form.Layout
26191  * Creates a column container for layout and rendering of fields in an {@link Roo.form.Form}.
26192  * @constructor
26193  * @param {Object} config Configuration options
26194  */
26195 Roo.form.Column = function(config){
26196     Roo.form.Column.superclass.constructor.call(this, config);
26197 };
26198
26199 Roo.extend(Roo.form.Column, Roo.form.Layout, {
26200     /**
26201      * @cfg {Number/String} width
26202      * The fixed width of the column in pixels or CSS value (defaults to "auto")
26203      */
26204     /**
26205      * @cfg {String/Object} autoCreate
26206      * A DomHelper element spec used to autocreate the column (defaults to {tag: 'div', cls: 'x-form-ct x-form-column'})
26207      */
26208
26209     // private
26210     defaultAutoCreate : {tag: 'div', cls: 'x-form-ct x-form-column'},
26211
26212     // private
26213     onRender : function(ct, position){
26214         Roo.form.Column.superclass.onRender.call(this, ct, position);
26215         if(this.width){
26216             this.el.setWidth(this.width);
26217         }
26218     }
26219 });
26220
26221
26222 /**
26223  * @class Roo.form.Row
26224  * @extends Roo.form.Layout
26225  * Creates a row container for layout and rendering of fields in an {@link Roo.form.Form}.
26226  * @constructor
26227  * @param {Object} config Configuration options
26228  */
26229
26230  
26231 Roo.form.Row = function(config){
26232     Roo.form.Row.superclass.constructor.call(this, config);
26233 };
26234  
26235 Roo.extend(Roo.form.Row, Roo.form.Layout, {
26236       /**
26237      * @cfg {Number/String} width
26238      * The fixed width of the column in pixels or CSS value (defaults to "auto")
26239      */
26240     /**
26241      * @cfg {Number/String} height
26242      * The fixed height of the column in pixels or CSS value (defaults to "auto")
26243      */
26244     defaultAutoCreate : {tag: 'div', cls: 'x-form-ct x-form-row'},
26245     
26246     padWidth : 20,
26247     // private
26248     onRender : function(ct, position){
26249         //console.log('row render');
26250         if(!this.rowTpl){
26251             var t = new Roo.Template(
26252                 '<div class="x-form-item {5}" style="float:left;width:{6}px">',
26253                     '<label for="{0}" style="{2}">{1}{4}</label>',
26254                     '<div class="x-form-element" id="x-form-el-{0}" style="{3}">',
26255                     '</div>',
26256                 '</div>'
26257             );
26258             t.disableFormats = true;
26259             t.compile();
26260             Roo.form.Layout.prototype.rowTpl = t;
26261         }
26262         this.fieldTpl = this.rowTpl;
26263         
26264         //console.log('lw' + this.labelWidth +', la:' + this.labelAlign);
26265         var labelWidth = 100;
26266         
26267         if ((this.labelAlign != 'top')) {
26268             if (typeof this.labelWidth == 'number') {
26269                 labelWidth = this.labelWidth
26270             }
26271             this.padWidth =  20 + labelWidth;
26272             
26273         }
26274         
26275         Roo.form.Column.superclass.onRender.call(this, ct, position);
26276         if(this.width){
26277             this.el.setWidth(this.width);
26278         }
26279         if(this.height){
26280             this.el.setHeight(this.height);
26281         }
26282     },
26283     
26284     // private
26285     renderField : function(f){
26286         f.fieldEl = this.fieldTpl.append(this.el, [
26287                f.id, f.fieldLabel,
26288                f.labelStyle||this.labelStyle||'',
26289                this.elementStyle||'',
26290                typeof f.labelSeparator == 'undefined' ? this.labelSeparator : f.labelSeparator,
26291                f.itemCls||this.itemCls||'',
26292                f.width ? f.width + this.padWidth : 160 + this.padWidth
26293        ],true);
26294     }
26295 });
26296  
26297
26298 /**
26299  * @class Roo.form.FieldSet
26300  * @extends Roo.form.Layout
26301  * Creates a fieldset container for layout and rendering of fields in an {@link Roo.form.Form}.
26302  * @constructor
26303  * @param {Object} config Configuration options
26304  */
26305 Roo.form.FieldSet = function(config){
26306     Roo.form.FieldSet.superclass.constructor.call(this, config);
26307 };
26308
26309 Roo.extend(Roo.form.FieldSet, Roo.form.Layout, {
26310     /**
26311      * @cfg {String} legend
26312      * The text to display as the legend for the FieldSet (defaults to '')
26313      */
26314     /**
26315      * @cfg {String/Object} autoCreate
26316      * A DomHelper element spec used to autocreate the fieldset (defaults to {tag: 'fieldset', cn: {tag:'legend'}})
26317      */
26318
26319     // private
26320     defaultAutoCreate : {tag: 'fieldset', cn: {tag:'legend'}},
26321
26322     // private
26323     onRender : function(ct, position){
26324         Roo.form.FieldSet.superclass.onRender.call(this, ct, position);
26325         if(this.legend){
26326             this.setLegend(this.legend);
26327         }
26328     },
26329
26330     // private
26331     setLegend : function(text){
26332         if(this.rendered){
26333             this.el.child('legend').update(text);
26334         }
26335     }
26336 });/*
26337  * Based on:
26338  * Ext JS Library 1.1.1
26339  * Copyright(c) 2006-2007, Ext JS, LLC.
26340  *
26341  * Originally Released Under LGPL - original licence link has changed is not relivant.
26342  *
26343  * Fork - LGPL
26344  * <script type="text/javascript">
26345  */
26346 /**
26347  * @class Roo.form.VTypes
26348  * Overridable validation definitions. The validations provided are basic and intended to be easily customizable and extended.
26349  * @singleton
26350  */
26351 Roo.form.VTypes = function(){
26352     // closure these in so they are only created once.
26353     var alpha = /^[a-zA-Z_]+$/;
26354     var alphanum = /^[a-zA-Z0-9_]+$/;
26355     var email = /^([\w]+)(.[\w]+)*@([\w-]+\.){1,5}([A-Za-z]){2,24}$/;
26356     var url = /(((https?)|(ftp)):\/\/([\-\w]+\.)+\w{2,3}(\/[%\-\w]+(\.\w{2,})?)*(([\w\-\.\?\\\/+@&#;`~=%!]*)(\.\w{2,})?)*\/?)/i;
26357
26358     // All these messages and functions are configurable
26359     return {
26360         /**
26361          * The function used to validate email addresses
26362          * @param {String} value The email address
26363          */
26364         'email' : function(v){
26365             return email.test(v);
26366         },
26367         /**
26368          * The error text to display when the email validation function returns false
26369          * @type String
26370          */
26371         'emailText' : 'This field should be an e-mail address in the format "user@domain.com"',
26372         /**
26373          * The keystroke filter mask to be applied on email input
26374          * @type RegExp
26375          */
26376         'emailMask' : /[a-z0-9_\.\-@]/i,
26377
26378         /**
26379          * The function used to validate URLs
26380          * @param {String} value The URL
26381          */
26382         'url' : function(v){
26383             return url.test(v);
26384         },
26385         /**
26386          * The error text to display when the url validation function returns false
26387          * @type String
26388          */
26389         'urlText' : 'This field should be a URL in the format "http:/'+'/www.domain.com"',
26390         
26391         /**
26392          * The function used to validate alpha values
26393          * @param {String} value The value
26394          */
26395         'alpha' : function(v){
26396             return alpha.test(v);
26397         },
26398         /**
26399          * The error text to display when the alpha validation function returns false
26400          * @type String
26401          */
26402         'alphaText' : 'This field should only contain letters and _',
26403         /**
26404          * The keystroke filter mask to be applied on alpha input
26405          * @type RegExp
26406          */
26407         'alphaMask' : /[a-z_]/i,
26408
26409         /**
26410          * The function used to validate alphanumeric values
26411          * @param {String} value The value
26412          */
26413         'alphanum' : function(v){
26414             return alphanum.test(v);
26415         },
26416         /**
26417          * The error text to display when the alphanumeric validation function returns false
26418          * @type String
26419          */
26420         'alphanumText' : 'This field should only contain letters, numbers and _',
26421         /**
26422          * The keystroke filter mask to be applied on alphanumeric input
26423          * @type RegExp
26424          */
26425         'alphanumMask' : /[a-z0-9_]/i
26426     };
26427 }();//<script type="text/javascript">
26428
26429 /**
26430  * @class Roo.form.FCKeditor
26431  * @extends Roo.form.TextArea
26432  * Wrapper around the FCKEditor http://www.fckeditor.net
26433  * @constructor
26434  * Creates a new FCKeditor
26435  * @param {Object} config Configuration options
26436  */
26437 Roo.form.FCKeditor = function(config){
26438     Roo.form.FCKeditor.superclass.constructor.call(this, config);
26439     this.addEvents({
26440          /**
26441          * @event editorinit
26442          * Fired when the editor is initialized - you can add extra handlers here..
26443          * @param {FCKeditor} this
26444          * @param {Object} the FCK object.
26445          */
26446         editorinit : true
26447     });
26448     
26449     
26450 };
26451 Roo.form.FCKeditor.editors = { };
26452 Roo.extend(Roo.form.FCKeditor, Roo.form.TextArea,
26453 {
26454     //defaultAutoCreate : {
26455     //    tag : "textarea",style   : "width:100px;height:60px;" ,autocomplete    : "off"
26456     //},
26457     // private
26458     /**
26459      * @cfg {Object} fck options - see fck manual for details.
26460      */
26461     fckconfig : false,
26462     
26463     /**
26464      * @cfg {Object} fck toolbar set (Basic or Default)
26465      */
26466     toolbarSet : 'Basic',
26467     /**
26468      * @cfg {Object} fck BasePath
26469      */ 
26470     basePath : '/fckeditor/',
26471     
26472     
26473     frame : false,
26474     
26475     value : '',
26476     
26477    
26478     onRender : function(ct, position)
26479     {
26480         if(!this.el){
26481             this.defaultAutoCreate = {
26482                 tag: "textarea",
26483                 style:"width:300px;height:60px;",
26484                 autocomplete: "new-password"
26485             };
26486         }
26487         Roo.form.FCKeditor.superclass.onRender.call(this, ct, position);
26488         /*
26489         if(this.grow){
26490             this.textSizeEl = Roo.DomHelper.append(document.body, {tag: "pre", cls: "x-form-grow-sizer"});
26491             if(this.preventScrollbars){
26492                 this.el.setStyle("overflow", "hidden");
26493             }
26494             this.el.setHeight(this.growMin);
26495         }
26496         */
26497         //console.log('onrender' + this.getId() );
26498         Roo.form.FCKeditor.editors[this.getId()] = this;
26499          
26500
26501         this.replaceTextarea() ;
26502         
26503     },
26504     
26505     getEditor : function() {
26506         return this.fckEditor;
26507     },
26508     /**
26509      * Sets a data value into the field and validates it.  To set the value directly without validation see {@link #setRawValue}.
26510      * @param {Mixed} value The value to set
26511      */
26512     
26513     
26514     setValue : function(value)
26515     {
26516         //console.log('setValue: ' + value);
26517         
26518         if(typeof(value) == 'undefined') { // not sure why this is happending...
26519             return;
26520         }
26521         Roo.form.FCKeditor.superclass.setValue.apply(this,[value]);
26522         
26523         //if(!this.el || !this.getEditor()) {
26524         //    this.value = value;
26525             //this.setValue.defer(100,this,[value]);    
26526         //    return;
26527         //} 
26528         
26529         if(!this.getEditor()) {
26530             return;
26531         }
26532         
26533         this.getEditor().SetData(value);
26534         
26535         //
26536
26537     },
26538
26539     /**
26540      * Returns the normalized data value (undefined or emptyText will be returned as '').  To return the raw value see {@link #getRawValue}.
26541      * @return {Mixed} value The field value
26542      */
26543     getValue : function()
26544     {
26545         
26546         if (this.frame && this.frame.dom.style.display == 'none') {
26547             return Roo.form.FCKeditor.superclass.getValue.call(this);
26548         }
26549         
26550         if(!this.el || !this.getEditor()) {
26551            
26552            // this.getValue.defer(100,this); 
26553             return this.value;
26554         }
26555        
26556         
26557         var value=this.getEditor().GetData();
26558         Roo.form.FCKeditor.superclass.setValue.apply(this,[value]);
26559         return Roo.form.FCKeditor.superclass.getValue.call(this);
26560         
26561
26562     },
26563
26564     /**
26565      * Returns the raw data value which may or may not be a valid, defined value.  To return a normalized value see {@link #getValue}.
26566      * @return {Mixed} value The field value
26567      */
26568     getRawValue : function()
26569     {
26570         if (this.frame && this.frame.dom.style.display == 'none') {
26571             return Roo.form.FCKeditor.superclass.getRawValue.call(this);
26572         }
26573         
26574         if(!this.el || !this.getEditor()) {
26575             //this.getRawValue.defer(100,this); 
26576             return this.value;
26577             return;
26578         }
26579         
26580         
26581         
26582         var value=this.getEditor().GetData();
26583         Roo.form.FCKeditor.superclass.setRawValue.apply(this,[value]);
26584         return Roo.form.FCKeditor.superclass.getRawValue.call(this);
26585          
26586     },
26587     
26588     setSize : function(w,h) {
26589         
26590         
26591         
26592         //if (this.frame && this.frame.dom.style.display == 'none') {
26593         //    Roo.form.FCKeditor.superclass.setSize.apply(this, [w, h]);
26594         //    return;
26595         //}
26596         //if(!this.el || !this.getEditor()) {
26597         //    this.setSize.defer(100,this, [w,h]); 
26598         //    return;
26599         //}
26600         
26601         
26602         
26603         Roo.form.FCKeditor.superclass.setSize.apply(this, [w, h]);
26604         
26605         this.frame.dom.setAttribute('width', w);
26606         this.frame.dom.setAttribute('height', h);
26607         this.frame.setSize(w,h);
26608         
26609     },
26610     
26611     toggleSourceEdit : function(value) {
26612         
26613       
26614          
26615         this.el.dom.style.display = value ? '' : 'none';
26616         this.frame.dom.style.display = value ?  'none' : '';
26617         
26618     },
26619     
26620     
26621     focus: function(tag)
26622     {
26623         if (this.frame.dom.style.display == 'none') {
26624             return Roo.form.FCKeditor.superclass.focus.call(this);
26625         }
26626         if(!this.el || !this.getEditor()) {
26627             this.focus.defer(100,this, [tag]); 
26628             return;
26629         }
26630         
26631         
26632         
26633         
26634         var tgs = this.getEditor().EditorDocument.getElementsByTagName(tag);
26635         this.getEditor().Focus();
26636         if (tgs.length) {
26637             if (!this.getEditor().Selection.GetSelection()) {
26638                 this.focus.defer(100,this, [tag]); 
26639                 return;
26640             }
26641             
26642             
26643             var r = this.getEditor().EditorDocument.createRange();
26644             r.setStart(tgs[0],0);
26645             r.setEnd(tgs[0],0);
26646             this.getEditor().Selection.GetSelection().removeAllRanges();
26647             this.getEditor().Selection.GetSelection().addRange(r);
26648             this.getEditor().Focus();
26649         }
26650         
26651     },
26652     
26653     
26654     
26655     replaceTextarea : function()
26656     {
26657         if ( document.getElementById( this.getId() + '___Frame' ) ) {
26658             return ;
26659         }
26660         //if ( !this.checkBrowser || this._isCompatibleBrowser() )
26661         //{
26662             // We must check the elements firstly using the Id and then the name.
26663         var oTextarea = document.getElementById( this.getId() );
26664         
26665         var colElementsByName = document.getElementsByName( this.getId() ) ;
26666          
26667         oTextarea.style.display = 'none' ;
26668
26669         if ( oTextarea.tabIndex ) {            
26670             this.TabIndex = oTextarea.tabIndex ;
26671         }
26672         
26673         this._insertHtmlBefore( this._getConfigHtml(), oTextarea ) ;
26674         this._insertHtmlBefore( this._getIFrameHtml(), oTextarea ) ;
26675         this.frame = Roo.get(this.getId() + '___Frame')
26676     },
26677     
26678     _getConfigHtml : function()
26679     {
26680         var sConfig = '' ;
26681
26682         for ( var o in this.fckconfig ) {
26683             sConfig += sConfig.length > 0  ? '&amp;' : '';
26684             sConfig += encodeURIComponent( o ) + '=' + encodeURIComponent( this.fckconfig[o] ) ;
26685         }
26686
26687         return '<input type="hidden" id="' + this.getId() + '___Config" value="' + sConfig + '" style="display:none" />' ;
26688     },
26689     
26690     
26691     _getIFrameHtml : function()
26692     {
26693         var sFile = 'fckeditor.html' ;
26694         /* no idea what this is about..
26695         try
26696         {
26697             if ( (/fcksource=true/i).test( window.top.location.search ) )
26698                 sFile = 'fckeditor.original.html' ;
26699         }
26700         catch (e) { 
26701         */
26702
26703         var sLink = this.basePath + 'editor/' + sFile + '?InstanceName=' + encodeURIComponent( this.getId() ) ;
26704         sLink += this.toolbarSet ? ( '&amp;Toolbar=' + this.toolbarSet)  : '';
26705         
26706         
26707         var html = '<iframe id="' + this.getId() +
26708             '___Frame" src="' + sLink +
26709             '" width="' + this.width +
26710             '" height="' + this.height + '"' +
26711             (this.tabIndex ?  ' tabindex="' + this.tabIndex + '"' :'' ) +
26712             ' frameborder="0" scrolling="no"></iframe>' ;
26713
26714         return html ;
26715     },
26716     
26717     _insertHtmlBefore : function( html, element )
26718     {
26719         if ( element.insertAdjacentHTML )       {
26720             // IE
26721             element.insertAdjacentHTML( 'beforeBegin', html ) ;
26722         } else { // Gecko
26723             var oRange = document.createRange() ;
26724             oRange.setStartBefore( element ) ;
26725             var oFragment = oRange.createContextualFragment( html );
26726             element.parentNode.insertBefore( oFragment, element ) ;
26727         }
26728     }
26729     
26730     
26731   
26732     
26733     
26734     
26735     
26736
26737 });
26738
26739 //Roo.reg('fckeditor', Roo.form.FCKeditor);
26740
26741 function FCKeditor_OnComplete(editorInstance){
26742     var f = Roo.form.FCKeditor.editors[editorInstance.Name];
26743     f.fckEditor = editorInstance;
26744     //console.log("loaded");
26745     f.fireEvent('editorinit', f, editorInstance);
26746
26747   
26748
26749  
26750
26751
26752
26753
26754
26755
26756
26757
26758
26759
26760
26761
26762
26763
26764
26765 //<script type="text/javascript">
26766 /**
26767  * @class Roo.form.GridField
26768  * @extends Roo.form.Field
26769  * Embed a grid (or editable grid into a form)
26770  * STATUS ALPHA
26771  * 
26772  * This embeds a grid in a form, the value of the field should be the json encoded array of rows
26773  * it needs 
26774  * xgrid.store = Roo.data.Store
26775  * xgrid.store.proxy = Roo.data.MemoryProxy (data = [] )
26776  * xgrid.store.reader = Roo.data.JsonReader 
26777  * 
26778  * 
26779  * @constructor
26780  * Creates a new GridField
26781  * @param {Object} config Configuration options
26782  */
26783 Roo.form.GridField = function(config){
26784     Roo.form.GridField.superclass.constructor.call(this, config);
26785      
26786 };
26787
26788 Roo.extend(Roo.form.GridField, Roo.form.Field,  {
26789     /**
26790      * @cfg {Number} width  - used to restrict width of grid..
26791      */
26792     width : 100,
26793     /**
26794      * @cfg {Number} height - used to restrict height of grid..
26795      */
26796     height : 50,
26797      /**
26798      * @cfg {Object} xgrid (xtype'd description of grid) { xtype : 'Grid', dataSource: .... }
26799          * 
26800          *}
26801      */
26802     xgrid : false, 
26803     /**
26804      * @cfg {String/Object} autoCreate A DomHelper element spec, or true for a default element spec (defaults to
26805      * {tag: "input", type: "checkbox", autocomplete: "off"})
26806      */
26807    // defaultAutoCreate : { tag: 'div' },
26808     defaultAutoCreate : { tag: 'input', type: 'hidden', autocomplete: 'new-password'},
26809     /**
26810      * @cfg {String} addTitle Text to include for adding a title.
26811      */
26812     addTitle : false,
26813     //
26814     onResize : function(){
26815         Roo.form.Field.superclass.onResize.apply(this, arguments);
26816     },
26817
26818     initEvents : function(){
26819         // Roo.form.Checkbox.superclass.initEvents.call(this);
26820         // has no events...
26821        
26822     },
26823
26824
26825     getResizeEl : function(){
26826         return this.wrap;
26827     },
26828
26829     getPositionEl : function(){
26830         return this.wrap;
26831     },
26832
26833     // private
26834     onRender : function(ct, position){
26835         
26836         this.style = this.style || 'overflow: hidden; border:1px solid #c3daf9;';
26837         var style = this.style;
26838         delete this.style;
26839         
26840         Roo.form.GridField.superclass.onRender.call(this, ct, position);
26841         this.wrap = this.el.wrap({cls: ''}); // not sure why ive done thsi...
26842         this.viewEl = this.wrap.createChild({ tag: 'div' });
26843         if (style) {
26844             this.viewEl.applyStyles(style);
26845         }
26846         if (this.width) {
26847             this.viewEl.setWidth(this.width);
26848         }
26849         if (this.height) {
26850             this.viewEl.setHeight(this.height);
26851         }
26852         //if(this.inputValue !== undefined){
26853         //this.setValue(this.value);
26854         
26855         
26856         this.grid = new Roo.grid[this.xgrid.xtype](this.viewEl, this.xgrid);
26857         
26858         
26859         this.grid.render();
26860         this.grid.getDataSource().on('remove', this.refreshValue, this);
26861         this.grid.getDataSource().on('update', this.refreshValue, this);
26862         this.grid.on('afteredit', this.refreshValue, this);
26863  
26864     },
26865      
26866     
26867     /**
26868      * Sets the value of the item. 
26869      * @param {String} either an object  or a string..
26870      */
26871     setValue : function(v){
26872         //this.value = v;
26873         v = v || []; // empty set..
26874         // this does not seem smart - it really only affects memoryproxy grids..
26875         if (this.grid && this.grid.getDataSource() && typeof(v) != 'undefined') {
26876             var ds = this.grid.getDataSource();
26877             // assumes a json reader..
26878             var data = {}
26879             data[ds.reader.meta.root ] =  typeof(v) == 'string' ? Roo.decode(v) : v;
26880             ds.loadData( data);
26881         }
26882         // clear selection so it does not get stale.
26883         if (this.grid.sm) { 
26884             this.grid.sm.clearSelections();
26885         }
26886         
26887         Roo.form.GridField.superclass.setValue.call(this, v);
26888         this.refreshValue();
26889         // should load data in the grid really....
26890     },
26891     
26892     // private
26893     refreshValue: function() {
26894          var val = [];
26895         this.grid.getDataSource().each(function(r) {
26896             val.push(r.data);
26897         });
26898         this.el.dom.value = Roo.encode(val);
26899     }
26900     
26901      
26902     
26903     
26904 });/*
26905  * Based on:
26906  * Ext JS Library 1.1.1
26907  * Copyright(c) 2006-2007, Ext JS, LLC.
26908  *
26909  * Originally Released Under LGPL - original licence link has changed is not relivant.
26910  *
26911  * Fork - LGPL
26912  * <script type="text/javascript">
26913  */
26914 /**
26915  * @class Roo.form.DisplayField
26916  * @extends Roo.form.Field
26917  * A generic Field to display non-editable data.
26918  * @cfg {Boolean} closable (true|false) default false
26919  * @constructor
26920  * Creates a new Display Field item.
26921  * @param {Object} config Configuration options
26922  */
26923 Roo.form.DisplayField = function(config){
26924     Roo.form.DisplayField.superclass.constructor.call(this, config);
26925     
26926     this.addEvents({
26927         /**
26928          * @event close
26929          * Fires after the click the close btn
26930              * @param {Roo.form.DisplayField} this
26931              */
26932         close : true
26933     });
26934 };
26935
26936 Roo.extend(Roo.form.DisplayField, Roo.form.TextField,  {
26937     inputType:      'hidden',
26938     allowBlank:     true,
26939     readOnly:         true,
26940     
26941  
26942     /**
26943      * @cfg {String} focusClass The CSS class to use when the checkbox receives focus (defaults to undefined)
26944      */
26945     focusClass : undefined,
26946     /**
26947      * @cfg {String} fieldClass The default CSS class for the checkbox (defaults to "x-form-field")
26948      */
26949     fieldClass: 'x-form-field',
26950     
26951      /**
26952      * @cfg {Function} valueRenderer The renderer for the field (so you can reformat output). should return raw HTML
26953      */
26954     valueRenderer: undefined,
26955     
26956     width: 100,
26957     /**
26958      * @cfg {String/Object} autoCreate A DomHelper element spec, or true for a default element spec (defaults to
26959      * {tag: "input", type: "checkbox", autocomplete: "off"})
26960      */
26961      
26962  //   defaultAutoCreate : { tag: 'input', type: 'hidden', autocomplete: 'off'},
26963  
26964     closable : false,
26965     
26966     onResize : function(){
26967         Roo.form.DisplayField.superclass.onResize.apply(this, arguments);
26968         
26969     },
26970
26971     initEvents : function(){
26972         // Roo.form.Checkbox.superclass.initEvents.call(this);
26973         // has no events...
26974         
26975         if(this.closable){
26976             this.closeEl.on('click', this.onClose, this);
26977         }
26978        
26979     },
26980
26981
26982     getResizeEl : function(){
26983         return this.wrap;
26984     },
26985
26986     getPositionEl : function(){
26987         return this.wrap;
26988     },
26989
26990     // private
26991     onRender : function(ct, position){
26992         
26993         Roo.form.DisplayField.superclass.onRender.call(this, ct, position);
26994         //if(this.inputValue !== undefined){
26995         this.wrap = this.el.wrap();
26996         
26997         this.viewEl = this.wrap.createChild({ tag: 'div', cls: 'x-form-displayfield'});
26998         
26999         if(this.closable){
27000             this.closeEl = this.wrap.createChild({ tag: 'div', cls: 'x-dlg-close'});
27001         }
27002         
27003         if (this.bodyStyle) {
27004             this.viewEl.applyStyles(this.bodyStyle);
27005         }
27006         //this.viewEl.setStyle('padding', '2px');
27007         
27008         this.setValue(this.value);
27009         
27010     },
27011 /*
27012     // private
27013     initValue : Roo.emptyFn,
27014
27015   */
27016
27017         // private
27018     onClick : function(){
27019         
27020     },
27021
27022     /**
27023      * Sets the checked state of the checkbox.
27024      * @param {Boolean/String} checked True, 'true', '1', or 'on' to check the checkbox, any other value will uncheck it.
27025      */
27026     setValue : function(v){
27027         this.value = v;
27028         var html = this.valueRenderer ?  this.valueRenderer(v) : String.format('{0}', v);
27029         // this might be called before we have a dom element..
27030         if (!this.viewEl) {
27031             return;
27032         }
27033         this.viewEl.dom.innerHTML = html;
27034         Roo.form.DisplayField.superclass.setValue.call(this, v);
27035
27036     },
27037     
27038     onClose : function(e)
27039     {
27040         e.preventDefault();
27041         
27042         this.fireEvent('close', this);
27043     }
27044 });/*
27045  * 
27046  * Licence- LGPL
27047  * 
27048  */
27049
27050 /**
27051  * @class Roo.form.DayPicker
27052  * @extends Roo.form.Field
27053  * A Day picker show [M] [T] [W] ....
27054  * @constructor
27055  * Creates a new Day Picker
27056  * @param {Object} config Configuration options
27057  */
27058 Roo.form.DayPicker= function(config){
27059     Roo.form.DayPicker.superclass.constructor.call(this, config);
27060      
27061 };
27062
27063 Roo.extend(Roo.form.DayPicker, Roo.form.Field,  {
27064     /**
27065      * @cfg {String} focusClass The CSS class to use when the checkbox receives focus (defaults to undefined)
27066      */
27067     focusClass : undefined,
27068     /**
27069      * @cfg {String} fieldClass The default CSS class for the checkbox (defaults to "x-form-field")
27070      */
27071     fieldClass: "x-form-field",
27072    
27073     /**
27074      * @cfg {String/Object} autoCreate A DomHelper element spec, or true for a default element spec (defaults to
27075      * {tag: "input", type: "checkbox", autocomplete: "off"})
27076      */
27077     defaultAutoCreate : { tag: "input", type: 'hidden', autocomplete: "new-password"},
27078     
27079    
27080     actionMode : 'viewEl', 
27081     //
27082     // private
27083  
27084     inputType : 'hidden',
27085     
27086      
27087     inputElement: false, // real input element?
27088     basedOn: false, // ????
27089     
27090     isFormField: true, // not sure where this is needed!!!!
27091
27092     onResize : function(){
27093         Roo.form.Checkbox.superclass.onResize.apply(this, arguments);
27094         if(!this.boxLabel){
27095             this.el.alignTo(this.wrap, 'c-c');
27096         }
27097     },
27098
27099     initEvents : function(){
27100         Roo.form.Checkbox.superclass.initEvents.call(this);
27101         this.el.on("click", this.onClick,  this);
27102         this.el.on("change", this.onClick,  this);
27103     },
27104
27105
27106     getResizeEl : function(){
27107         return this.wrap;
27108     },
27109
27110     getPositionEl : function(){
27111         return this.wrap;
27112     },
27113
27114     
27115     // private
27116     onRender : function(ct, position){
27117         Roo.form.Checkbox.superclass.onRender.call(this, ct, position);
27118        
27119         this.wrap = this.el.wrap({cls: 'x-form-daypick-item '});
27120         
27121         var r1 = '<table><tr>';
27122         var r2 = '<tr class="x-form-daypick-icons">';
27123         for (var i=0; i < 7; i++) {
27124             r1+= '<td><div>' + Date.dayNames[i].substring(0,3) + '</div></td>';
27125             r2+= '<td><img class="x-menu-item-icon" src="' + Roo.BLANK_IMAGE_URL  +'"></td>';
27126         }
27127         
27128         var viewEl = this.wrap.createChild( r1 + '</tr>' + r2 + '</tr></table>');
27129         viewEl.select('img').on('click', this.onClick, this);
27130         this.viewEl = viewEl;   
27131         
27132         
27133         // this will not work on Chrome!!!
27134         this.el.on('DOMAttrModified', this.setFromHidden,  this); //ff
27135         this.el.on('propertychange', this.setFromHidden,  this);  //ie
27136         
27137         
27138           
27139
27140     },
27141
27142     // private
27143     initValue : Roo.emptyFn,
27144
27145     /**
27146      * Returns the checked state of the checkbox.
27147      * @return {Boolean} True if checked, else false
27148      */
27149     getValue : function(){
27150         return this.el.dom.value;
27151         
27152     },
27153
27154         // private
27155     onClick : function(e){ 
27156         //this.setChecked(!this.checked);
27157         Roo.get(e.target).toggleClass('x-menu-item-checked');
27158         this.refreshValue();
27159         //if(this.el.dom.checked != this.checked){
27160         //    this.setValue(this.el.dom.checked);
27161        // }
27162     },
27163     
27164     // private
27165     refreshValue : function()
27166     {
27167         var val = '';
27168         this.viewEl.select('img',true).each(function(e,i,n)  {
27169             val += e.is(".x-menu-item-checked") ? String(n) : '';
27170         });
27171         this.setValue(val, true);
27172     },
27173
27174     /**
27175      * Sets the checked state of the checkbox.
27176      * On is always based on a string comparison between inputValue and the param.
27177      * @param {Boolean/String} value - the value to set 
27178      * @param {Boolean/String} suppressEvent - whether to suppress the checkchange event.
27179      */
27180     setValue : function(v,suppressEvent){
27181         if (!this.el.dom) {
27182             return;
27183         }
27184         var old = this.el.dom.value ;
27185         this.el.dom.value = v;
27186         if (suppressEvent) {
27187             return ;
27188         }
27189          
27190         // update display..
27191         this.viewEl.select('img',true).each(function(e,i,n)  {
27192             
27193             var on = e.is(".x-menu-item-checked");
27194             var newv = v.indexOf(String(n)) > -1;
27195             if (on != newv) {
27196                 e.toggleClass('x-menu-item-checked');
27197             }
27198             
27199         });
27200         
27201         
27202         this.fireEvent('change', this, v, old);
27203         
27204         
27205     },
27206    
27207     // handle setting of hidden value by some other method!!?!?
27208     setFromHidden: function()
27209     {
27210         if(!this.el){
27211             return;
27212         }
27213         //console.log("SET FROM HIDDEN");
27214         //alert('setFrom hidden');
27215         this.setValue(this.el.dom.value);
27216     },
27217     
27218     onDestroy : function()
27219     {
27220         if(this.viewEl){
27221             Roo.get(this.viewEl).remove();
27222         }
27223          
27224         Roo.form.DayPicker.superclass.onDestroy.call(this);
27225     }
27226
27227 });/*
27228  * RooJS Library 1.1.1
27229  * Copyright(c) 2008-2011  Alan Knowles
27230  *
27231  * License - LGPL
27232  */
27233  
27234
27235 /**
27236  * @class Roo.form.ComboCheck
27237  * @extends Roo.form.ComboBox
27238  * A combobox for multiple select items.
27239  *
27240  * FIXME - could do with a reset button..
27241  * 
27242  * @constructor
27243  * Create a new ComboCheck
27244  * @param {Object} config Configuration options
27245  */
27246 Roo.form.ComboCheck = function(config){
27247     Roo.form.ComboCheck.superclass.constructor.call(this, config);
27248     // should verify some data...
27249     // like
27250     // hiddenName = required..
27251     // displayField = required
27252     // valudField == required
27253     var req= [ 'hiddenName', 'displayField', 'valueField' ];
27254     var _t = this;
27255     Roo.each(req, function(e) {
27256         if ((typeof(_t[e]) == 'undefined' ) || !_t[e].length) {
27257             throw "Roo.form.ComboCheck : missing value for: " + e;
27258         }
27259     });
27260     
27261     
27262 };
27263
27264 Roo.extend(Roo.form.ComboCheck, Roo.form.ComboBox, {
27265      
27266      
27267     editable : false,
27268      
27269     selectedClass: 'x-menu-item-checked', 
27270     
27271     // private
27272     onRender : function(ct, position){
27273         var _t = this;
27274         
27275         
27276         
27277         if(!this.tpl){
27278             var cls = 'x-combo-list';
27279
27280             
27281             this.tpl =  new Roo.Template({
27282                 html :  '<div class="'+cls+'-item x-menu-check-item">' +
27283                    '<img class="x-menu-item-icon" style="margin: 0px;" src="' + Roo.BLANK_IMAGE_URL + '">' + 
27284                    '<span>{' + this.displayField + '}</span>' +
27285                     '</div>' 
27286                 
27287             });
27288         }
27289  
27290         
27291         Roo.form.ComboCheck.superclass.onRender.call(this, ct, position);
27292         this.view.singleSelect = false;
27293         this.view.multiSelect = true;
27294         this.view.toggleSelect = true;
27295         this.pageTb.add(new Roo.Toolbar.Fill(), {
27296             
27297             text: 'Done',
27298             handler: function()
27299             {
27300                 _t.collapse();
27301             }
27302         });
27303     },
27304     
27305     onViewOver : function(e, t){
27306         // do nothing...
27307         return;
27308         
27309     },
27310     
27311     onViewClick : function(doFocus,index){
27312         return;
27313         
27314     },
27315     select: function () {
27316         //Roo.log("SELECT CALLED");
27317     },
27318      
27319     selectByValue : function(xv, scrollIntoView){
27320         var ar = this.getValueArray();
27321         var sels = [];
27322         
27323         Roo.each(ar, function(v) {
27324             if(v === undefined || v === null){
27325                 return;
27326             }
27327             var r = this.findRecord(this.valueField, v);
27328             if(r){
27329                 sels.push(this.store.indexOf(r))
27330                 
27331             }
27332         },this);
27333         this.view.select(sels);
27334         return false;
27335     },
27336     
27337     
27338     
27339     onSelect : function(record, index){
27340        // Roo.log("onselect Called");
27341        // this is only called by the clear button now..
27342         this.view.clearSelections();
27343         this.setValue('[]');
27344         if (this.value != this.valueBefore) {
27345             this.fireEvent('change', this, this.value, this.valueBefore);
27346             this.valueBefore = this.value;
27347         }
27348     },
27349     getValueArray : function()
27350     {
27351         var ar = [] ;
27352         
27353         try {
27354             //Roo.log(this.value);
27355             if (typeof(this.value) == 'undefined') {
27356                 return [];
27357             }
27358             var ar = Roo.decode(this.value);
27359             return  ar instanceof Array ? ar : []; //?? valid?
27360             
27361         } catch(e) {
27362             Roo.log(e + "\nRoo.form.ComboCheck:getValueArray  invalid data:" + this.getValue());
27363             return [];
27364         }
27365          
27366     },
27367     expand : function ()
27368     {
27369         
27370         Roo.form.ComboCheck.superclass.expand.call(this);
27371         this.valueBefore = typeof(this.value) == 'undefined' ? '' : this.value;
27372         //this.valueBefore = typeof(this.valueBefore) == 'undefined' ? '' : this.valueBefore;
27373         
27374
27375     },
27376     
27377     collapse : function(){
27378         Roo.form.ComboCheck.superclass.collapse.call(this);
27379         var sl = this.view.getSelectedIndexes();
27380         var st = this.store;
27381         var nv = [];
27382         var tv = [];
27383         var r;
27384         Roo.each(sl, function(i) {
27385             r = st.getAt(i);
27386             nv.push(r.get(this.valueField));
27387         },this);
27388         this.setValue(Roo.encode(nv));
27389         if (this.value != this.valueBefore) {
27390
27391             this.fireEvent('change', this, this.value, this.valueBefore);
27392             this.valueBefore = this.value;
27393         }
27394         
27395     },
27396     
27397     setValue : function(v){
27398         // Roo.log(v);
27399         this.value = v;
27400         
27401         var vals = this.getValueArray();
27402         var tv = [];
27403         Roo.each(vals, function(k) {
27404             var r = this.findRecord(this.valueField, k);
27405             if(r){
27406                 tv.push(r.data[this.displayField]);
27407             }else if(this.valueNotFoundText !== undefined){
27408                 tv.push( this.valueNotFoundText );
27409             }
27410         },this);
27411        // Roo.log(tv);
27412         
27413         Roo.form.ComboBox.superclass.setValue.call(this, tv.join(', '));
27414         this.hiddenField.value = v;
27415         this.value = v;
27416     }
27417     
27418 });/*
27419  * Based on:
27420  * Ext JS Library 1.1.1
27421  * Copyright(c) 2006-2007, Ext JS, LLC.
27422  *
27423  * Originally Released Under LGPL - original licence link has changed is not relivant.
27424  *
27425  * Fork - LGPL
27426  * <script type="text/javascript">
27427  */
27428  
27429 /**
27430  * @class Roo.form.Signature
27431  * @extends Roo.form.Field
27432  * Signature field.  
27433  * @constructor
27434  * 
27435  * @param {Object} config Configuration options
27436  */
27437
27438 Roo.form.Signature = function(config){
27439     Roo.form.Signature.superclass.constructor.call(this, config);
27440     
27441     this.addEvents({// not in used??
27442          /**
27443          * @event confirm
27444          * Fires when the 'confirm' icon is pressed (add a listener to enable add button)
27445              * @param {Roo.form.Signature} combo This combo box
27446              */
27447         'confirm' : true,
27448         /**
27449          * @event reset
27450          * Fires when the 'edit' icon is pressed (add a listener to enable add button)
27451              * @param {Roo.form.ComboBox} combo This combo box
27452              * @param {Roo.data.Record|false} record The data record returned from the underlying store (or false on nothing selected)
27453              */
27454         'reset' : true
27455     });
27456 };
27457
27458 Roo.extend(Roo.form.Signature, Roo.form.Field,  {
27459     /**
27460      * @cfg {Object} labels Label to use when rendering a form.
27461      * defaults to 
27462      * labels : { 
27463      *      clear : "Clear",
27464      *      confirm : "Confirm"
27465      *  }
27466      */
27467     labels : { 
27468         clear : "Clear",
27469         confirm : "Confirm"
27470     },
27471     /**
27472      * @cfg {Number} width The signature panel width (defaults to 300)
27473      */
27474     width: 300,
27475     /**
27476      * @cfg {Number} height The signature panel height (defaults to 100)
27477      */
27478     height : 100,
27479     /**
27480      * @cfg {Boolean} allowBlank False to validate that the value length > 0 (defaults to false)
27481      */
27482     allowBlank : false,
27483     
27484     //private
27485     // {Object} signPanel The signature SVG panel element (defaults to {})
27486     signPanel : {},
27487     // {Boolean} isMouseDown False to validate that the mouse down event (defaults to false)
27488     isMouseDown : false,
27489     // {Boolean} isConfirmed validate the signature is confirmed or not for submitting form (defaults to false)
27490     isConfirmed : false,
27491     // {String} signatureTmp SVG mapping string (defaults to empty string)
27492     signatureTmp : '',
27493     
27494     
27495     defaultAutoCreate : { // modified by initCompnoent..
27496         tag: "input",
27497         type:"hidden"
27498     },
27499
27500     // private
27501     onRender : function(ct, position){
27502         
27503         Roo.form.Signature.superclass.onRender.call(this, ct, position);
27504         
27505         this.wrap = this.el.wrap({
27506             cls:'x-form-signature-wrap', style : 'width: ' + this.width + 'px', cn:{cls:'x-form-signature'}
27507         });
27508         
27509         this.createToolbar(this);
27510         this.signPanel = this.wrap.createChild({
27511                 tag: 'div',
27512                 style: 'width: ' + this.width + 'px; height: ' + this.height + 'px; border: 0;'
27513             }, this.el
27514         );
27515             
27516         this.svgID = Roo.id();
27517         this.svgEl = this.signPanel.createChild({
27518               xmlns : 'http://www.w3.org/2000/svg',
27519               tag : 'svg',
27520               id : this.svgID + "-svg",
27521               width: this.width,
27522               height: this.height,
27523               viewBox: '0 0 '+this.width+' '+this.height,
27524               cn : [
27525                 {
27526                     tag: "rect",
27527                     id: this.svgID + "-svg-r",
27528                     width: this.width,
27529                     height: this.height,
27530                     fill: "#ffa"
27531                 },
27532                 {
27533                     tag: "line",
27534                     id: this.svgID + "-svg-l",
27535                     x1: "0", // start
27536                     y1: (this.height*0.8), // start set the line in 80% of height
27537                     x2: this.width, // end
27538                     y2: (this.height*0.8), // end set the line in 80% of height
27539                     'stroke': "#666",
27540                     'stroke-width': "1",
27541                     'stroke-dasharray': "3",
27542                     'shape-rendering': "crispEdges",
27543                     'pointer-events': "none"
27544                 },
27545                 {
27546                     tag: "path",
27547                     id: this.svgID + "-svg-p",
27548                     'stroke': "navy",
27549                     'stroke-width': "3",
27550                     'fill': "none",
27551                     'pointer-events': 'none'
27552                 }
27553               ]
27554         });
27555         this.createSVG();
27556         this.svgBox = this.svgEl.dom.getScreenCTM();
27557     },
27558     createSVG : function(){ 
27559         var svg = this.signPanel;
27560         var r = svg.select('#'+ this.svgID + '-svg-r', true).first().dom;
27561         var t = this;
27562
27563         r.addEventListener('mousedown', function(e) { return t.down(e); }, false);
27564         r.addEventListener('mousemove', function(e) { return t.move(e); }, false);
27565         r.addEventListener('mouseup', function(e) { return t.up(e); }, false);
27566         r.addEventListener('mouseout', function(e) { return t.up(e); }, false);
27567         r.addEventListener('touchstart', function(e) { return t.down(e); }, false);
27568         r.addEventListener('touchmove', function(e) { return t.move(e); }, false);
27569         r.addEventListener('touchend', function(e) { return t.up(e); }, false);
27570         
27571     },
27572     isTouchEvent : function(e){
27573         return e.type.match(/^touch/);
27574     },
27575     getCoords : function (e) {
27576         var pt    = this.svgEl.dom.createSVGPoint();
27577         pt.x = e.clientX; 
27578         pt.y = e.clientY;
27579         if (this.isTouchEvent(e)) {
27580             pt.x =  e.targetTouches[0].clientX;
27581             pt.y = e.targetTouches[0].clientY;
27582         }
27583         var a = this.svgEl.dom.getScreenCTM();
27584         var b = a.inverse();
27585         var mx = pt.matrixTransform(b);
27586         return mx.x + ',' + mx.y;
27587     },
27588     //mouse event headler 
27589     down : function (e) {
27590         this.signatureTmp += 'M' + this.getCoords(e) + ' ';
27591         this.signPanel.select('#'+ this.svgID + '-svg-p', true).first().attr('d', this.signatureTmp);
27592         
27593         this.isMouseDown = true;
27594         
27595         e.preventDefault();
27596     },
27597     move : function (e) {
27598         if (this.isMouseDown) {
27599             this.signatureTmp += 'L' + this.getCoords(e) + ' ';
27600             this.signPanel.select('#'+ this.svgID + '-svg-p', true).first().attr( 'd', this.signatureTmp);
27601         }
27602         
27603         e.preventDefault();
27604     },
27605     up : function (e) {
27606         this.isMouseDown = false;
27607         var sp = this.signatureTmp.split(' ');
27608         
27609         if(sp.length > 1){
27610             if(!sp[sp.length-2].match(/^L/)){
27611                 sp.pop();
27612                 sp.pop();
27613                 sp.push("");
27614                 this.signatureTmp = sp.join(" ");
27615             }
27616         }
27617         if(this.getValue() != this.signatureTmp){
27618             this.signPanel.select('#'+ this.svgID + '-svg-r', true).first().attr('fill', '#ffa');
27619             this.isConfirmed = false;
27620         }
27621         e.preventDefault();
27622     },
27623     
27624     /**
27625      * Protected method that will not generally be called directly. It
27626      * is called when the editor creates its toolbar. Override this method if you need to
27627      * add custom toolbar buttons.
27628      * @param {HtmlEditor} editor
27629      */
27630     createToolbar : function(editor){
27631          function btn(id, toggle, handler){
27632             var xid = fid + '-'+ id ;
27633             return {
27634                 id : xid,
27635                 cmd : id,
27636                 cls : 'x-btn-icon x-edit-'+id,
27637                 enableToggle:toggle !== false,
27638                 scope: editor, // was editor...
27639                 handler:handler||editor.relayBtnCmd,
27640                 clickEvent:'mousedown',
27641                 tooltip: etb.buttonTips[id] || undefined, ///tips ???
27642                 tabIndex:-1
27643             };
27644         }
27645         
27646         
27647         var tb = new Roo.Toolbar(editor.wrap.dom.firstChild);
27648         this.tb = tb;
27649         this.tb.add(
27650            {
27651                 cls : ' x-signature-btn x-signature-'+id,
27652                 scope: editor, // was editor...
27653                 handler: this.reset,
27654                 clickEvent:'mousedown',
27655                 text: this.labels.clear
27656             },
27657             {
27658                  xtype : 'Fill',
27659                  xns: Roo.Toolbar
27660             }, 
27661             {
27662                 cls : '  x-signature-btn x-signature-'+id,
27663                 scope: editor, // was editor...
27664                 handler: this.confirmHandler,
27665                 clickEvent:'mousedown',
27666                 text: this.labels.confirm
27667             }
27668         );
27669     
27670     },
27671     //public
27672     /**
27673      * when user is clicked confirm then show this image.....
27674      * 
27675      * @return {String} Image Data URI
27676      */
27677     getImageDataURI : function(){
27678         var svg = this.svgEl.dom.parentNode.innerHTML;
27679         var src = 'data:image/svg+xml;base64,'+window.btoa(svg);
27680         return src; 
27681     },
27682     /**
27683      * 
27684      * @return {Boolean} this.isConfirmed
27685      */
27686     getConfirmed : function(){
27687         return this.isConfirmed;
27688     },
27689     /**
27690      * 
27691      * @return {Number} this.width
27692      */
27693     getWidth : function(){
27694         return this.width;
27695     },
27696     /**
27697      * 
27698      * @return {Number} this.height
27699      */
27700     getHeight : function(){
27701         return this.height;
27702     },
27703     // private
27704     getSignature : function(){
27705         return this.signatureTmp;
27706     },
27707     // private
27708     reset : function(){
27709         this.signatureTmp = '';
27710         this.signPanel.select('#'+ this.svgID + '-svg-r', true).first().attr('fill', '#ffa');
27711         this.signPanel.select('#'+ this.svgID + '-svg-p', true).first().attr( 'd', '');
27712         this.isConfirmed = false;
27713         Roo.form.Signature.superclass.reset.call(this);
27714     },
27715     setSignature : function(s){
27716         this.signatureTmp = s;
27717         this.signPanel.select('#'+ this.svgID + '-svg-r', true).first().attr('fill', '#ffa');
27718         this.signPanel.select('#'+ this.svgID + '-svg-p', true).first().attr( 'd', s);
27719         this.setValue(s);
27720         this.isConfirmed = false;
27721         Roo.form.Signature.superclass.reset.call(this);
27722     }, 
27723     test : function(){
27724 //        Roo.log(this.signPanel.dom.contentWindow.up())
27725     },
27726     //private
27727     setConfirmed : function(){
27728         
27729         
27730         
27731 //        Roo.log(Roo.get(this.signPanel.dom.contentWindow.r).attr('fill', '#cfc'));
27732     },
27733     // private
27734     confirmHandler : function(){
27735         if(!this.getSignature()){
27736             return;
27737         }
27738         
27739         this.signPanel.select('#'+ this.svgID + '-svg-r', true).first().attr('fill', '#cfc');
27740         this.setValue(this.getSignature());
27741         this.isConfirmed = true;
27742         
27743         this.fireEvent('confirm', this);
27744     },
27745     // private
27746     // Subclasses should provide the validation implementation by overriding this
27747     validateValue : function(value){
27748         if(this.allowBlank){
27749             return true;
27750         }
27751         
27752         if(this.isConfirmed){
27753             return true;
27754         }
27755         return false;
27756     }
27757 });/*
27758  * Based on:
27759  * Ext JS Library 1.1.1
27760  * Copyright(c) 2006-2007, Ext JS, LLC.
27761  *
27762  * Originally Released Under LGPL - original licence link has changed is not relivant.
27763  *
27764  * Fork - LGPL
27765  * <script type="text/javascript">
27766  */
27767  
27768
27769 /**
27770  * @class Roo.form.ComboBox
27771  * @extends Roo.form.TriggerField
27772  * A combobox control with support for autocomplete, remote-loading, paging and many other features.
27773  * @constructor
27774  * Create a new ComboBox.
27775  * @param {Object} config Configuration options
27776  */
27777 Roo.form.Select = function(config){
27778     Roo.form.Select.superclass.constructor.call(this, config);
27779      
27780 };
27781
27782 Roo.extend(Roo.form.Select , Roo.form.ComboBox, {
27783     /**
27784      * @cfg {String/HTMLElement/Element} transform The id, DOM node or element of an existing select to convert to a ComboBox
27785      */
27786     /**
27787      * @cfg {Boolean} lazyRender True to prevent the ComboBox from rendering until requested (should always be used when
27788      * rendering into an Roo.Editor, defaults to false)
27789      */
27790     /**
27791      * @cfg {Boolean/Object} autoCreate A DomHelper element spec, or true for a default element spec (defaults to:
27792      * {tag: "input", type: "text", size: "24", autocomplete: "off"})
27793      */
27794     /**
27795      * @cfg {Roo.data.Store} store The data store to which this combo is bound (defaults to undefined)
27796      */
27797     /**
27798      * @cfg {String} title If supplied, a header element is created containing this text and added into the top of
27799      * the dropdown list (defaults to undefined, with no header element)
27800      */
27801
27802      /**
27803      * @cfg {String/Roo.Template} tpl The template to use to render the output
27804      */
27805      
27806     // private
27807     defaultAutoCreate : {tag: "select"  },
27808     /**
27809      * @cfg {Number} listWidth The width in pixels of the dropdown list (defaults to the width of the ComboBox field)
27810      */
27811     listWidth: undefined,
27812     /**
27813      * @cfg {String} displayField The underlying data field name to bind to this CombBox (defaults to undefined if
27814      * mode = 'remote' or 'text' if mode = 'local')
27815      */
27816     displayField: undefined,
27817     /**
27818      * @cfg {String} valueField The underlying data value name to bind to this CombBox (defaults to undefined if
27819      * mode = 'remote' or 'value' if mode = 'local'). 
27820      * Note: use of a valueField requires the user make a selection
27821      * in order for a value to be mapped.
27822      */
27823     valueField: undefined,
27824     
27825     
27826     /**
27827      * @cfg {String} hiddenName If specified, a hidden form field with this name is dynamically generated to store the
27828      * field's data value (defaults to the underlying DOM element's name)
27829      */
27830     hiddenName: undefined,
27831     /**
27832      * @cfg {String} listClass CSS class to apply to the dropdown list element (defaults to '')
27833      */
27834     listClass: '',
27835     /**
27836      * @cfg {String} selectedClass CSS class to apply to the selected item in the dropdown list (defaults to 'x-combo-selected')
27837      */
27838     selectedClass: 'x-combo-selected',
27839     /**
27840      * @cfg {String} triggerClass An additional CSS class used to style the trigger button.  The trigger will always get the
27841      * class 'x-form-trigger' and triggerClass will be <b>appended</b> if specified (defaults to 'x-form-arrow-trigger'
27842      * which displays a downward arrow icon).
27843      */
27844     triggerClass : 'x-form-arrow-trigger',
27845     /**
27846      * @cfg {Boolean/String} shadow True or "sides" for the default effect, "frame" for 4-way shadow, and "drop" for bottom-right
27847      */
27848     shadow:'sides',
27849     /**
27850      * @cfg {String} listAlign A valid anchor position value. See {@link Roo.Element#alignTo} for details on supported
27851      * anchor positions (defaults to 'tl-bl')
27852      */
27853     listAlign: 'tl-bl?',
27854     /**
27855      * @cfg {Number} maxHeight The maximum height in pixels of the dropdown list before scrollbars are shown (defaults to 300)
27856      */
27857     maxHeight: 300,
27858     /**
27859      * @cfg {String} triggerAction The action to execute when the trigger field is activated.  Use 'all' to run the
27860      * query specified by the allQuery config option (defaults to 'query')
27861      */
27862     triggerAction: 'query',
27863     /**
27864      * @cfg {Number} minChars The minimum number of characters the user must type before autocomplete and typeahead activate
27865      * (defaults to 4, does not apply if editable = false)
27866      */
27867     minChars : 4,
27868     /**
27869      * @cfg {Boolean} typeAhead True to populate and autoselect the remainder of the text being typed after a configurable
27870      * delay (typeAheadDelay) if it matches a known value (defaults to false)
27871      */
27872     typeAhead: false,
27873     /**
27874      * @cfg {Number} queryDelay The length of time in milliseconds to delay between the start of typing and sending the
27875      * query to filter the dropdown list (defaults to 500 if mode = 'remote' or 10 if mode = 'local')
27876      */
27877     queryDelay: 500,
27878     /**
27879      * @cfg {Number} pageSize If greater than 0, a paging toolbar is displayed in the footer of the dropdown list and the
27880      * filter queries will execute with page start and limit parameters.  Only applies when mode = 'remote' (defaults to 0)
27881      */
27882     pageSize: 0,
27883     /**
27884      * @cfg {Boolean} selectOnFocus True to select any existing text in the field immediately on focus.  Only applies
27885      * when editable = true (defaults to false)
27886      */
27887     selectOnFocus:false,
27888     /**
27889      * @cfg {String} queryParam Name of the query as it will be passed on the querystring (defaults to 'query')
27890      */
27891     queryParam: 'query',
27892     /**
27893      * @cfg {String} loadingText The text to display in the dropdown list while data is loading.  Only applies
27894      * when mode = 'remote' (defaults to 'Loading...')
27895      */
27896     loadingText: 'Loading...',
27897     /**
27898      * @cfg {Boolean} resizable True to add a resize handle to the bottom of the dropdown list (defaults to false)
27899      */
27900     resizable: false,
27901     /**
27902      * @cfg {Number} handleHeight The height in pixels of the dropdown list resize handle if resizable = true (defaults to 8)
27903      */
27904     handleHeight : 8,
27905     /**
27906      * @cfg {Boolean} editable False to prevent the user from typing text directly into the field, just like a
27907      * traditional select (defaults to true)
27908      */
27909     editable: true,
27910     /**
27911      * @cfg {String} allQuery The text query to send to the server to return all records for the list with no filtering (defaults to '')
27912      */
27913     allQuery: '',
27914     /**
27915      * @cfg {String} mode Set to 'local' if the ComboBox loads local data (defaults to 'remote' which loads from the server)
27916      */
27917     mode: 'remote',
27918     /**
27919      * @cfg {Number} minListWidth The minimum width of the dropdown list in pixels (defaults to 70, will be ignored if
27920      * listWidth has a higher value)
27921      */
27922     minListWidth : 70,
27923     /**
27924      * @cfg {Boolean} forceSelection True to restrict the selected value to one of the values in the list, false to
27925      * allow the user to set arbitrary text into the field (defaults to false)
27926      */
27927     forceSelection:false,
27928     /**
27929      * @cfg {Number} typeAheadDelay The length of time in milliseconds to wait until the typeahead text is displayed
27930      * if typeAhead = true (defaults to 250)
27931      */
27932     typeAheadDelay : 250,
27933     /**
27934      * @cfg {String} valueNotFoundText When using a name/value combo, if the value passed to setValue is not found in
27935      * the store, valueNotFoundText will be displayed as the field text if defined (defaults to undefined)
27936      */
27937     valueNotFoundText : undefined,
27938     
27939     /**
27940      * @cfg {String} defaultValue The value displayed after loading the store.
27941      */
27942     defaultValue: '',
27943     
27944     /**
27945      * @cfg {Boolean} blockFocus Prevents all focus calls, so it can work with things like HTML edtor bar
27946      */
27947     blockFocus : false,
27948     
27949     /**
27950      * @cfg {Boolean} disableClear Disable showing of clear button.
27951      */
27952     disableClear : false,
27953     /**
27954      * @cfg {Boolean} alwaysQuery  Disable caching of results, and always send query
27955      */
27956     alwaysQuery : false,
27957     
27958     //private
27959     addicon : false,
27960     editicon: false,
27961     
27962     // element that contains real text value.. (when hidden is used..)
27963      
27964     // private
27965     onRender : function(ct, position){
27966         Roo.form.Field.prototype.onRender.call(this, ct, position);
27967         
27968         if(this.store){
27969             this.store.on('beforeload', this.onBeforeLoad, this);
27970             this.store.on('load', this.onLoad, this);
27971             this.store.on('loadexception', this.onLoadException, this);
27972             this.store.load({});
27973         }
27974         
27975         
27976         
27977     },
27978
27979     // private
27980     initEvents : function(){
27981         //Roo.form.ComboBox.superclass.initEvents.call(this);
27982  
27983     },
27984
27985     onDestroy : function(){
27986        
27987         if(this.store){
27988             this.store.un('beforeload', this.onBeforeLoad, this);
27989             this.store.un('load', this.onLoad, this);
27990             this.store.un('loadexception', this.onLoadException, this);
27991         }
27992         //Roo.form.ComboBox.superclass.onDestroy.call(this);
27993     },
27994
27995     // private
27996     fireKey : function(e){
27997         if(e.isNavKeyPress() && !this.list.isVisible()){
27998             this.fireEvent("specialkey", this, e);
27999         }
28000     },
28001
28002     // private
28003     onResize: function(w, h){
28004         
28005         return; 
28006     
28007         
28008     },
28009
28010     /**
28011      * Allow or prevent the user from directly editing the field text.  If false is passed,
28012      * the user will only be able to select from the items defined in the dropdown list.  This method
28013      * is the runtime equivalent of setting the 'editable' config option at config time.
28014      * @param {Boolean} value True to allow the user to directly edit the field text
28015      */
28016     setEditable : function(value){
28017          
28018     },
28019
28020     // private
28021     onBeforeLoad : function(){
28022         
28023         Roo.log("Select before load");
28024         return;
28025     
28026         this.innerList.update(this.loadingText ?
28027                '<div class="loading-indicator">'+this.loadingText+'</div>' : '');
28028         //this.restrictHeight();
28029         this.selectedIndex = -1;
28030     },
28031
28032     // private
28033     onLoad : function(){
28034
28035     
28036         var dom = this.el.dom;
28037         dom.innerHTML = '';
28038          var od = dom.ownerDocument;
28039          
28040         if (this.emptyText) {
28041             var op = od.createElement('option');
28042             op.setAttribute('value', '');
28043             op.innerHTML = String.format('{0}', this.emptyText);
28044             dom.appendChild(op);
28045         }
28046         if(this.store.getCount() > 0){
28047            
28048             var vf = this.valueField;
28049             var df = this.displayField;
28050             this.store.data.each(function(r) {
28051                 // which colmsn to use... testing - cdoe / title..
28052                 var op = od.createElement('option');
28053                 op.setAttribute('value', r.data[vf]);
28054                 op.innerHTML = String.format('{0}', r.data[df]);
28055                 dom.appendChild(op);
28056             });
28057             if (typeof(this.defaultValue != 'undefined')) {
28058                 this.setValue(this.defaultValue);
28059             }
28060             
28061              
28062         }else{
28063             //this.onEmptyResults();
28064         }
28065         //this.el.focus();
28066     },
28067     // private
28068     onLoadException : function()
28069     {
28070         dom.innerHTML = '';
28071             
28072         Roo.log("Select on load exception");
28073         return;
28074     
28075         this.collapse();
28076         Roo.log(this.store.reader.jsonData);
28077         if (this.store && typeof(this.store.reader.jsonData.errorMsg) != 'undefined') {
28078             Roo.MessageBox.alert("Error loading",this.store.reader.jsonData.errorMsg);
28079         }
28080         
28081         
28082     },
28083     // private
28084     onTypeAhead : function(){
28085          
28086     },
28087
28088     // private
28089     onSelect : function(record, index){
28090         Roo.log('on select?');
28091         return;
28092         if(this.fireEvent('beforeselect', this, record, index) !== false){
28093             this.setFromData(index > -1 ? record.data : false);
28094             this.collapse();
28095             this.fireEvent('select', this, record, index);
28096         }
28097     },
28098
28099     /**
28100      * Returns the currently selected field value or empty string if no value is set.
28101      * @return {String} value The selected value
28102      */
28103     getValue : function(){
28104         var dom = this.el.dom;
28105         this.value = dom.options[dom.selectedIndex].value;
28106         return this.value;
28107         
28108     },
28109
28110     /**
28111      * Clears any text/value currently set in the field
28112      */
28113     clearValue : function(){
28114         this.value = '';
28115         this.el.dom.selectedIndex = this.emptyText ? 0 : -1;
28116         
28117     },
28118
28119     /**
28120      * Sets the specified value into the field.  If the value finds a match, the corresponding record text
28121      * will be displayed in the field.  If the value does not match the data value of an existing item,
28122      * and the valueNotFoundText config option is defined, it will be displayed as the default field text.
28123      * Otherwise the field will be blank (although the value will still be set).
28124      * @param {String} value The value to match
28125      */
28126     setValue : function(v){
28127         var d = this.el.dom;
28128         for (var i =0; i < d.options.length;i++) {
28129             if (v == d.options[i].value) {
28130                 d.selectedIndex = i;
28131                 this.value = v;
28132                 return;
28133             }
28134         }
28135         this.clearValue();
28136     },
28137     /**
28138      * @property {Object} the last set data for the element
28139      */
28140     
28141     lastData : false,
28142     /**
28143      * Sets the value of the field based on a object which is related to the record format for the store.
28144      * @param {Object} value the value to set as. or false on reset?
28145      */
28146     setFromData : function(o){
28147         Roo.log('setfrom data?');
28148          
28149         
28150         
28151     },
28152     // private
28153     reset : function(){
28154         this.clearValue();
28155     },
28156     // private
28157     findRecord : function(prop, value){
28158         
28159         return false;
28160     
28161         var record;
28162         if(this.store.getCount() > 0){
28163             this.store.each(function(r){
28164                 if(r.data[prop] == value){
28165                     record = r;
28166                     return false;
28167                 }
28168                 return true;
28169             });
28170         }
28171         return record;
28172     },
28173     
28174     getName: function()
28175     {
28176         // returns hidden if it's set..
28177         if (!this.rendered) {return ''};
28178         return !this.hiddenName && this.el.dom.name  ? this.el.dom.name : (this.hiddenName || '');
28179         
28180     },
28181      
28182
28183     
28184
28185     // private
28186     onEmptyResults : function(){
28187         Roo.log('empty results');
28188         //this.collapse();
28189     },
28190
28191     /**
28192      * Returns true if the dropdown list is expanded, else false.
28193      */
28194     isExpanded : function(){
28195         return false;
28196     },
28197
28198     /**
28199      * Select an item in the dropdown list by its data value. This function does NOT cause the select event to fire.
28200      * The store must be loaded and the list expanded for this function to work, otherwise use setValue.
28201      * @param {String} value The data value of the item to select
28202      * @param {Boolean} scrollIntoView False to prevent the dropdown list from autoscrolling to display the
28203      * selected item if it is not currently in view (defaults to true)
28204      * @return {Boolean} True if the value matched an item in the list, else false
28205      */
28206     selectByValue : function(v, scrollIntoView){
28207         Roo.log('select By Value');
28208         return false;
28209     
28210         if(v !== undefined && v !== null){
28211             var r = this.findRecord(this.valueField || this.displayField, v);
28212             if(r){
28213                 this.select(this.store.indexOf(r), scrollIntoView);
28214                 return true;
28215             }
28216         }
28217         return false;
28218     },
28219
28220     /**
28221      * Select an item in the dropdown list by its numeric index in the list. This function does NOT cause the select event to fire.
28222      * The store must be loaded and the list expanded for this function to work, otherwise use setValue.
28223      * @param {Number} index The zero-based index of the list item to select
28224      * @param {Boolean} scrollIntoView False to prevent the dropdown list from autoscrolling to display the
28225      * selected item if it is not currently in view (defaults to true)
28226      */
28227     select : function(index, scrollIntoView){
28228         Roo.log('select ');
28229         return  ;
28230         
28231         this.selectedIndex = index;
28232         this.view.select(index);
28233         if(scrollIntoView !== false){
28234             var el = this.view.getNode(index);
28235             if(el){
28236                 this.innerList.scrollChildIntoView(el, false);
28237             }
28238         }
28239     },
28240
28241       
28242
28243     // private
28244     validateBlur : function(){
28245         
28246         return;
28247         
28248     },
28249
28250     // private
28251     initQuery : function(){
28252         this.doQuery(this.getRawValue());
28253     },
28254
28255     // private
28256     doForce : function(){
28257         if(this.el.dom.value.length > 0){
28258             this.el.dom.value =
28259                 this.lastSelectionText === undefined ? '' : this.lastSelectionText;
28260              
28261         }
28262     },
28263
28264     /**
28265      * Execute a query to filter the dropdown list.  Fires the beforequery event prior to performing the
28266      * query allowing the query action to be canceled if needed.
28267      * @param {String} query The SQL query to execute
28268      * @param {Boolean} forceAll True to force the query to execute even if there are currently fewer characters
28269      * in the field than the minimum specified by the minChars config option.  It also clears any filter previously
28270      * saved in the current store (defaults to false)
28271      */
28272     doQuery : function(q, forceAll){
28273         
28274         Roo.log('doQuery?');
28275         if(q === undefined || q === null){
28276             q = '';
28277         }
28278         var qe = {
28279             query: q,
28280             forceAll: forceAll,
28281             combo: this,
28282             cancel:false
28283         };
28284         if(this.fireEvent('beforequery', qe)===false || qe.cancel){
28285             return false;
28286         }
28287         q = qe.query;
28288         forceAll = qe.forceAll;
28289         if(forceAll === true || (q.length >= this.minChars)){
28290             if(this.lastQuery != q || this.alwaysQuery){
28291                 this.lastQuery = q;
28292                 if(this.mode == 'local'){
28293                     this.selectedIndex = -1;
28294                     if(forceAll){
28295                         this.store.clearFilter();
28296                     }else{
28297                         this.store.filter(this.displayField, q);
28298                     }
28299                     this.onLoad();
28300                 }else{
28301                     this.store.baseParams[this.queryParam] = q;
28302                     this.store.load({
28303                         params: this.getParams(q)
28304                     });
28305                     this.expand();
28306                 }
28307             }else{
28308                 this.selectedIndex = -1;
28309                 this.onLoad();   
28310             }
28311         }
28312     },
28313
28314     // private
28315     getParams : function(q){
28316         var p = {};
28317         //p[this.queryParam] = q;
28318         if(this.pageSize){
28319             p.start = 0;
28320             p.limit = this.pageSize;
28321         }
28322         return p;
28323     },
28324
28325     /**
28326      * Hides the dropdown list if it is currently expanded. Fires the 'collapse' event on completion.
28327      */
28328     collapse : function(){
28329         
28330     },
28331
28332     // private
28333     collapseIf : function(e){
28334         
28335     },
28336
28337     /**
28338      * Expands the dropdown list if it is currently hidden. Fires the 'expand' event on completion.
28339      */
28340     expand : function(){
28341         
28342     } ,
28343
28344     // private
28345      
28346
28347     /** 
28348     * @cfg {Boolean} grow 
28349     * @hide 
28350     */
28351     /** 
28352     * @cfg {Number} growMin 
28353     * @hide 
28354     */
28355     /** 
28356     * @cfg {Number} growMax 
28357     * @hide 
28358     */
28359     /**
28360      * @hide
28361      * @method autoSize
28362      */
28363     
28364     setWidth : function()
28365     {
28366         
28367     },
28368     getResizeEl : function(){
28369         return this.el;
28370     }
28371 });//<script type="text/javasscript">
28372  
28373
28374 /**
28375  * @class Roo.DDView
28376  * A DnD enabled version of Roo.View.
28377  * @param {Element/String} container The Element in which to create the View.
28378  * @param {String} tpl The template string used to create the markup for each element of the View
28379  * @param {Object} config The configuration properties. These include all the config options of
28380  * {@link Roo.View} plus some specific to this class.<br>
28381  * <p>
28382  * Drag/drop is implemented by adding {@link Roo.data.Record}s to the target DDView. If copying is
28383  * not being performed, the original {@link Roo.data.Record} is removed from the source DDView.<br>
28384  * <p>
28385  * The following extra CSS rules are needed to provide insertion point highlighting:<pre><code>
28386 .x-view-drag-insert-above {
28387         border-top:1px dotted #3366cc;
28388 }
28389 .x-view-drag-insert-below {
28390         border-bottom:1px dotted #3366cc;
28391 }
28392 </code></pre>
28393  * 
28394  */
28395  
28396 Roo.DDView = function(container, tpl, config) {
28397     Roo.DDView.superclass.constructor.apply(this, arguments);
28398     this.getEl().setStyle("outline", "0px none");
28399     this.getEl().unselectable();
28400     if (this.dragGroup) {
28401                 this.setDraggable(this.dragGroup.split(","));
28402     }
28403     if (this.dropGroup) {
28404                 this.setDroppable(this.dropGroup.split(","));
28405     }
28406     if (this.deletable) {
28407         this.setDeletable();
28408     }
28409     this.isDirtyFlag = false;
28410         this.addEvents({
28411                 "drop" : true
28412         });
28413 };
28414
28415 Roo.extend(Roo.DDView, Roo.View, {
28416 /**     @cfg {String/Array} dragGroup The ddgroup name(s) for the View's DragZone. */
28417 /**     @cfg {String/Array} dropGroup The ddgroup name(s) for the View's DropZone. */
28418 /**     @cfg {Boolean} copy Causes drag operations to copy nodes rather than move. */
28419 /**     @cfg {Boolean} allowCopy Causes ctrl/drag operations to copy nodes rather than move. */
28420
28421         isFormField: true,
28422
28423         reset: Roo.emptyFn,
28424         
28425         clearInvalid: Roo.form.Field.prototype.clearInvalid,
28426
28427         validate: function() {
28428                 return true;
28429         },
28430         
28431         destroy: function() {
28432                 this.purgeListeners();
28433                 this.getEl.removeAllListeners();
28434                 this.getEl().remove();
28435                 if (this.dragZone) {
28436                         if (this.dragZone.destroy) {
28437                                 this.dragZone.destroy();
28438                         }
28439                 }
28440                 if (this.dropZone) {
28441                         if (this.dropZone.destroy) {
28442                                 this.dropZone.destroy();
28443                         }
28444                 }
28445         },
28446
28447 /**     Allows this class to be an Roo.form.Field so it can be found using {@link Roo.form.BasicForm#findField}. */
28448         getName: function() {
28449                 return this.name;
28450         },
28451
28452 /**     Loads the View from a JSON string representing the Records to put into the Store. */
28453         setValue: function(v) {
28454                 if (!this.store) {
28455                         throw "DDView.setValue(). DDView must be constructed with a valid Store";
28456                 }
28457                 var data = {};
28458                 data[this.store.reader.meta.root] = v ? [].concat(v) : [];
28459                 this.store.proxy = new Roo.data.MemoryProxy(data);
28460                 this.store.load();
28461         },
28462
28463 /**     @return {String} a parenthesised list of the ids of the Records in the View. */
28464         getValue: function() {
28465                 var result = '(';
28466                 this.store.each(function(rec) {
28467                         result += rec.id + ',';
28468                 });
28469                 return result.substr(0, result.length - 1) + ')';
28470         },
28471         
28472         getIds: function() {
28473                 var i = 0, result = new Array(this.store.getCount());
28474                 this.store.each(function(rec) {
28475                         result[i++] = rec.id;
28476                 });
28477                 return result;
28478         },
28479         
28480         isDirty: function() {
28481                 return this.isDirtyFlag;
28482         },
28483
28484 /**
28485  *      Part of the Roo.dd.DropZone interface. If no target node is found, the
28486  *      whole Element becomes the target, and this causes the drop gesture to append.
28487  */
28488     getTargetFromEvent : function(e) {
28489                 var target = e.getTarget();
28490                 while ((target !== null) && (target.parentNode != this.el.dom)) {
28491                 target = target.parentNode;
28492                 }
28493                 if (!target) {
28494                         target = this.el.dom.lastChild || this.el.dom;
28495                 }
28496                 return target;
28497     },
28498
28499 /**
28500  *      Create the drag data which consists of an object which has the property "ddel" as
28501  *      the drag proxy element. 
28502  */
28503     getDragData : function(e) {
28504         var target = this.findItemFromChild(e.getTarget());
28505                 if(target) {
28506                         this.handleSelection(e);
28507                         var selNodes = this.getSelectedNodes();
28508             var dragData = {
28509                 source: this,
28510                 copy: this.copy || (this.allowCopy && e.ctrlKey),
28511                 nodes: selNodes,
28512                 records: []
28513                         };
28514                         var selectedIndices = this.getSelectedIndexes();
28515                         for (var i = 0; i < selectedIndices.length; i++) {
28516                                 dragData.records.push(this.store.getAt(selectedIndices[i]));
28517                         }
28518                         if (selNodes.length == 1) {
28519                                 dragData.ddel = target.cloneNode(true); // the div element
28520                         } else {
28521                                 var div = document.createElement('div'); // create the multi element drag "ghost"
28522                                 div.className = 'multi-proxy';
28523                                 for (var i = 0, len = selNodes.length; i < len; i++) {
28524                                         div.appendChild(selNodes[i].cloneNode(true));
28525                                 }
28526                                 dragData.ddel = div;
28527                         }
28528             //console.log(dragData)
28529             //console.log(dragData.ddel.innerHTML)
28530                         return dragData;
28531                 }
28532         //console.log('nodragData')
28533                 return false;
28534     },
28535     
28536 /**     Specify to which ddGroup items in this DDView may be dragged. */
28537     setDraggable: function(ddGroup) {
28538         if (ddGroup instanceof Array) {
28539                 Roo.each(ddGroup, this.setDraggable, this);
28540                 return;
28541         }
28542         if (this.dragZone) {
28543                 this.dragZone.addToGroup(ddGroup);
28544         } else {
28545                         this.dragZone = new Roo.dd.DragZone(this.getEl(), {
28546                                 containerScroll: true,
28547                                 ddGroup: ddGroup 
28548
28549                         });
28550 //                      Draggability implies selection. DragZone's mousedown selects the element.
28551                         if (!this.multiSelect) { this.singleSelect = true; }
28552
28553 //                      Wire the DragZone's handlers up to methods in *this*
28554                         this.dragZone.getDragData = this.getDragData.createDelegate(this);
28555                 }
28556     },
28557
28558 /**     Specify from which ddGroup this DDView accepts drops. */
28559     setDroppable: function(ddGroup) {
28560         if (ddGroup instanceof Array) {
28561                 Roo.each(ddGroup, this.setDroppable, this);
28562                 return;
28563         }
28564         if (this.dropZone) {
28565                 this.dropZone.addToGroup(ddGroup);
28566         } else {
28567                         this.dropZone = new Roo.dd.DropZone(this.getEl(), {
28568                                 containerScroll: true,
28569                                 ddGroup: ddGroup
28570                         });
28571
28572 //                      Wire the DropZone's handlers up to methods in *this*
28573                         this.dropZone.getTargetFromEvent = this.getTargetFromEvent.createDelegate(this);
28574                         this.dropZone.onNodeEnter = this.onNodeEnter.createDelegate(this);
28575                         this.dropZone.onNodeOver = this.onNodeOver.createDelegate(this);
28576                         this.dropZone.onNodeOut = this.onNodeOut.createDelegate(this);
28577                         this.dropZone.onNodeDrop = this.onNodeDrop.createDelegate(this);
28578                 }
28579     },
28580
28581 /**     Decide whether to drop above or below a View node. */
28582     getDropPoint : function(e, n, dd){
28583         if (n == this.el.dom) { return "above"; }
28584                 var t = Roo.lib.Dom.getY(n), b = t + n.offsetHeight;
28585                 var c = t + (b - t) / 2;
28586                 var y = Roo.lib.Event.getPageY(e);
28587                 if(y <= c) {
28588                         return "above";
28589                 }else{
28590                         return "below";
28591                 }
28592     },
28593
28594     onNodeEnter : function(n, dd, e, data){
28595                 return false;
28596     },
28597     
28598     onNodeOver : function(n, dd, e, data){
28599                 var pt = this.getDropPoint(e, n, dd);
28600                 // set the insert point style on the target node
28601                 var dragElClass = this.dropNotAllowed;
28602                 if (pt) {
28603                         var targetElClass;
28604                         if (pt == "above"){
28605                                 dragElClass = n.previousSibling ? "x-tree-drop-ok-between" : "x-tree-drop-ok-above";
28606                                 targetElClass = "x-view-drag-insert-above";
28607                         } else {
28608                                 dragElClass = n.nextSibling ? "x-tree-drop-ok-between" : "x-tree-drop-ok-below";
28609                                 targetElClass = "x-view-drag-insert-below";
28610                         }
28611                         if (this.lastInsertClass != targetElClass){
28612                                 Roo.fly(n).replaceClass(this.lastInsertClass, targetElClass);
28613                                 this.lastInsertClass = targetElClass;
28614                         }
28615                 }
28616                 return dragElClass;
28617         },
28618
28619     onNodeOut : function(n, dd, e, data){
28620                 this.removeDropIndicators(n);
28621     },
28622
28623     onNodeDrop : function(n, dd, e, data){
28624         if (this.fireEvent("drop", this, n, dd, e, data) === false) {
28625                 return false;
28626         }
28627         var pt = this.getDropPoint(e, n, dd);
28628                 var insertAt = (n == this.el.dom) ? this.nodes.length : n.nodeIndex;
28629                 if (pt == "below") { insertAt++; }
28630                 for (var i = 0; i < data.records.length; i++) {
28631                         var r = data.records[i];
28632                         var dup = this.store.getById(r.id);
28633                         if (dup && (dd != this.dragZone)) {
28634                                 Roo.fly(this.getNode(this.store.indexOf(dup))).frame("red", 1);
28635                         } else {
28636                                 if (data.copy) {
28637                                         this.store.insert(insertAt++, r.copy());
28638                                 } else {
28639                                         data.source.isDirtyFlag = true;
28640                                         r.store.remove(r);
28641                                         this.store.insert(insertAt++, r);
28642                                 }
28643                                 this.isDirtyFlag = true;
28644                         }
28645                 }
28646                 this.dragZone.cachedTarget = null;
28647                 return true;
28648     },
28649
28650     removeDropIndicators : function(n){
28651                 if(n){
28652                         Roo.fly(n).removeClass([
28653                                 "x-view-drag-insert-above",
28654                                 "x-view-drag-insert-below"]);
28655                         this.lastInsertClass = "_noclass";
28656                 }
28657     },
28658
28659 /**
28660  *      Utility method. Add a delete option to the DDView's context menu.
28661  *      @param {String} imageUrl The URL of the "delete" icon image.
28662  */
28663         setDeletable: function(imageUrl) {
28664                 if (!this.singleSelect && !this.multiSelect) {
28665                         this.singleSelect = true;
28666                 }
28667                 var c = this.getContextMenu();
28668                 this.contextMenu.on("itemclick", function(item) {
28669                         switch (item.id) {
28670                                 case "delete":
28671                                         this.remove(this.getSelectedIndexes());
28672                                         break;
28673                         }
28674                 }, this);
28675                 this.contextMenu.add({
28676                         icon: imageUrl,
28677                         id: "delete",
28678                         text: 'Delete'
28679                 });
28680         },
28681         
28682 /**     Return the context menu for this DDView. */
28683         getContextMenu: function() {
28684                 if (!this.contextMenu) {
28685 //                      Create the View's context menu
28686                         this.contextMenu = new Roo.menu.Menu({
28687                                 id: this.id + "-contextmenu"
28688                         });
28689                         this.el.on("contextmenu", this.showContextMenu, this);
28690                 }
28691                 return this.contextMenu;
28692         },
28693         
28694         disableContextMenu: function() {
28695                 if (this.contextMenu) {
28696                         this.el.un("contextmenu", this.showContextMenu, this);
28697                 }
28698         },
28699
28700         showContextMenu: function(e, item) {
28701         item = this.findItemFromChild(e.getTarget());
28702                 if (item) {
28703                         e.stopEvent();
28704                         this.select(this.getNode(item), this.multiSelect && e.ctrlKey, true);
28705                         this.contextMenu.showAt(e.getXY());
28706             }
28707     },
28708
28709 /**
28710  *      Remove {@link Roo.data.Record}s at the specified indices.
28711  *      @param {Array/Number} selectedIndices The index (or Array of indices) of Records to remove.
28712  */
28713     remove: function(selectedIndices) {
28714                 selectedIndices = [].concat(selectedIndices);
28715                 for (var i = 0; i < selectedIndices.length; i++) {
28716                         var rec = this.store.getAt(selectedIndices[i]);
28717                         this.store.remove(rec);
28718                 }
28719     },
28720
28721 /**
28722  *      Double click fires the event, but also, if this is draggable, and there is only one other
28723  *      related DropZone, it transfers the selected node.
28724  */
28725     onDblClick : function(e){
28726         var item = this.findItemFromChild(e.getTarget());
28727         if(item){
28728             if (this.fireEvent("dblclick", this, this.indexOf(item), item, e) === false) {
28729                 return false;
28730             }
28731             if (this.dragGroup) {
28732                     var targets = Roo.dd.DragDropMgr.getRelated(this.dragZone, true);
28733                     while (targets.indexOf(this.dropZone) > -1) {
28734                             targets.remove(this.dropZone);
28735                                 }
28736                     if (targets.length == 1) {
28737                                         this.dragZone.cachedTarget = null;
28738                         var el = Roo.get(targets[0].getEl());
28739                         var box = el.getBox(true);
28740                         targets[0].onNodeDrop(el.dom, {
28741                                 target: el.dom,
28742                                 xy: [box.x, box.y + box.height - 1]
28743                         }, null, this.getDragData(e));
28744                     }
28745                 }
28746         }
28747     },
28748     
28749     handleSelection: function(e) {
28750                 this.dragZone.cachedTarget = null;
28751         var item = this.findItemFromChild(e.getTarget());
28752         if (!item) {
28753                 this.clearSelections(true);
28754                 return;
28755         }
28756                 if (item && (this.multiSelect || this.singleSelect)){
28757                         if(this.multiSelect && e.shiftKey && (!e.ctrlKey) && this.lastSelection){
28758                                 this.select(this.getNodes(this.indexOf(this.lastSelection), item.nodeIndex), false);
28759                         }else if (this.isSelected(this.getNode(item)) && e.ctrlKey){
28760                                 this.unselect(item);
28761                         } else {
28762                                 this.select(item, this.multiSelect && e.ctrlKey);
28763                                 this.lastSelection = item;
28764                         }
28765                 }
28766     },
28767
28768     onItemClick : function(item, index, e){
28769                 if(this.fireEvent("beforeclick", this, index, item, e) === false){
28770                         return false;
28771                 }
28772                 return true;
28773     },
28774
28775     unselect : function(nodeInfo, suppressEvent){
28776                 var node = this.getNode(nodeInfo);
28777                 if(node && this.isSelected(node)){
28778                         if(this.fireEvent("beforeselect", this, node, this.selections) !== false){
28779                                 Roo.fly(node).removeClass(this.selectedClass);
28780                                 this.selections.remove(node);
28781                                 if(!suppressEvent){
28782                                         this.fireEvent("selectionchange", this, this.selections);
28783                                 }
28784                         }
28785                 }
28786     }
28787 });
28788 /*
28789  * Based on:
28790  * Ext JS Library 1.1.1
28791  * Copyright(c) 2006-2007, Ext JS, LLC.
28792  *
28793  * Originally Released Under LGPL - original licence link has changed is not relivant.
28794  *
28795  * Fork - LGPL
28796  * <script type="text/javascript">
28797  */
28798  
28799 /**
28800  * @class Roo.LayoutManager
28801  * @extends Roo.util.Observable
28802  * Base class for layout managers.
28803  */
28804 Roo.LayoutManager = function(container, config){
28805     Roo.LayoutManager.superclass.constructor.call(this);
28806     this.el = Roo.get(container);
28807     // ie scrollbar fix
28808     if(this.el.dom == document.body && Roo.isIE && !config.allowScroll){
28809         document.body.scroll = "no";
28810     }else if(this.el.dom != document.body && this.el.getStyle('position') == 'static'){
28811         this.el.position('relative');
28812     }
28813     this.id = this.el.id;
28814     this.el.addClass("x-layout-container");
28815     /** false to disable window resize monitoring @type Boolean */
28816     this.monitorWindowResize = true;
28817     this.regions = {};
28818     this.addEvents({
28819         /**
28820          * @event layout
28821          * Fires when a layout is performed. 
28822          * @param {Roo.LayoutManager} this
28823          */
28824         "layout" : true,
28825         /**
28826          * @event regionresized
28827          * Fires when the user resizes a region. 
28828          * @param {Roo.LayoutRegion} region The resized region
28829          * @param {Number} newSize The new size (width for east/west, height for north/south)
28830          */
28831         "regionresized" : true,
28832         /**
28833          * @event regioncollapsed
28834          * Fires when a region is collapsed. 
28835          * @param {Roo.LayoutRegion} region The collapsed region
28836          */
28837         "regioncollapsed" : true,
28838         /**
28839          * @event regionexpanded
28840          * Fires when a region is expanded.  
28841          * @param {Roo.LayoutRegion} region The expanded region
28842          */
28843         "regionexpanded" : true
28844     });
28845     this.updating = false;
28846     Roo.EventManager.onWindowResize(this.onWindowResize, this, true);
28847 };
28848
28849 Roo.extend(Roo.LayoutManager, Roo.util.Observable, {
28850     /**
28851      * Returns true if this layout is currently being updated
28852      * @return {Boolean}
28853      */
28854     isUpdating : function(){
28855         return this.updating; 
28856     },
28857     
28858     /**
28859      * Suspend the LayoutManager from doing auto-layouts while
28860      * making multiple add or remove calls
28861      */
28862     beginUpdate : function(){
28863         this.updating = true;    
28864     },
28865     
28866     /**
28867      * Restore auto-layouts and optionally disable the manager from performing a layout
28868      * @param {Boolean} noLayout true to disable a layout update 
28869      */
28870     endUpdate : function(noLayout){
28871         this.updating = false;
28872         if(!noLayout){
28873             this.layout();
28874         }    
28875     },
28876     
28877     layout: function(){
28878         
28879     },
28880     
28881     onRegionResized : function(region, newSize){
28882         this.fireEvent("regionresized", region, newSize);
28883         this.layout();
28884     },
28885     
28886     onRegionCollapsed : function(region){
28887         this.fireEvent("regioncollapsed", region);
28888     },
28889     
28890     onRegionExpanded : function(region){
28891         this.fireEvent("regionexpanded", region);
28892     },
28893         
28894     /**
28895      * Returns the size of the current view. This method normalizes document.body and element embedded layouts and
28896      * performs box-model adjustments.
28897      * @return {Object} The size as an object {width: (the width), height: (the height)}
28898      */
28899     getViewSize : function(){
28900         var size;
28901         if(this.el.dom != document.body){
28902             size = this.el.getSize();
28903         }else{
28904             size = {width: Roo.lib.Dom.getViewWidth(), height: Roo.lib.Dom.getViewHeight()};
28905         }
28906         size.width -= this.el.getBorderWidth("lr")-this.el.getPadding("lr");
28907         size.height -= this.el.getBorderWidth("tb")-this.el.getPadding("tb");
28908         return size;
28909     },
28910     
28911     /**
28912      * Returns the Element this layout is bound to.
28913      * @return {Roo.Element}
28914      */
28915     getEl : function(){
28916         return this.el;
28917     },
28918     
28919     /**
28920      * Returns the specified region.
28921      * @param {String} target The region key ('center', 'north', 'south', 'east' or 'west')
28922      * @return {Roo.LayoutRegion}
28923      */
28924     getRegion : function(target){
28925         return this.regions[target.toLowerCase()];
28926     },
28927     
28928     onWindowResize : function(){
28929         if(this.monitorWindowResize){
28930             this.layout();
28931         }
28932     }
28933 });/*
28934  * Based on:
28935  * Ext JS Library 1.1.1
28936  * Copyright(c) 2006-2007, Ext JS, LLC.
28937  *
28938  * Originally Released Under LGPL - original licence link has changed is not relivant.
28939  *
28940  * Fork - LGPL
28941  * <script type="text/javascript">
28942  */
28943 /**
28944  * @class Roo.BorderLayout
28945  * @extends Roo.LayoutManager
28946  * This class represents a common layout manager used in desktop applications. For screenshots and more details,
28947  * please see: <br><br>
28948  * <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>
28949  * <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>
28950  * Example:
28951  <pre><code>
28952  var layout = new Roo.BorderLayout(document.body, {
28953     north: {
28954         initialSize: 25,
28955         titlebar: false
28956     },
28957     west: {
28958         split:true,
28959         initialSize: 200,
28960         minSize: 175,
28961         maxSize: 400,
28962         titlebar: true,
28963         collapsible: true
28964     },
28965     east: {
28966         split:true,
28967         initialSize: 202,
28968         minSize: 175,
28969         maxSize: 400,
28970         titlebar: true,
28971         collapsible: true
28972     },
28973     south: {
28974         split:true,
28975         initialSize: 100,
28976         minSize: 100,
28977         maxSize: 200,
28978         titlebar: true,
28979         collapsible: true
28980     },
28981     center: {
28982         titlebar: true,
28983         autoScroll:true,
28984         resizeTabs: true,
28985         minTabWidth: 50,
28986         preferredTabWidth: 150
28987     }
28988 });
28989
28990 // shorthand
28991 var CP = Roo.ContentPanel;
28992
28993 layout.beginUpdate();
28994 layout.add("north", new CP("north", "North"));
28995 layout.add("south", new CP("south", {title: "South", closable: true}));
28996 layout.add("west", new CP("west", {title: "West"}));
28997 layout.add("east", new CP("autoTabs", {title: "Auto Tabs", closable: true}));
28998 layout.add("center", new CP("center1", {title: "Close Me", closable: true}));
28999 layout.add("center", new CP("center2", {title: "Center Panel", closable: false}));
29000 layout.getRegion("center").showPanel("center1");
29001 layout.endUpdate();
29002 </code></pre>
29003
29004 <b>The container the layout is rendered into can be either the body element or any other element.
29005 If it is not the body element, the container needs to either be an absolute positioned element,
29006 or you will need to add "position:relative" to the css of the container.  You will also need to specify
29007 the container size if it is not the body element.</b>
29008
29009 * @constructor
29010 * Create a new BorderLayout
29011 * @param {String/HTMLElement/Element} container The container this layout is bound to
29012 * @param {Object} config Configuration options
29013  */
29014 Roo.BorderLayout = function(container, config){
29015     config = config || {};
29016     Roo.BorderLayout.superclass.constructor.call(this, container, config);
29017     this.factory = config.factory || Roo.BorderLayout.RegionFactory;
29018     for(var i = 0, len = this.factory.validRegions.length; i < len; i++) {
29019         var target = this.factory.validRegions[i];
29020         if(config[target]){
29021             this.addRegion(target, config[target]);
29022         }
29023     }
29024 };
29025
29026 Roo.extend(Roo.BorderLayout, Roo.LayoutManager, {
29027     /**
29028      * Creates and adds a new region if it doesn't already exist.
29029      * @param {String} target The target region key (north, south, east, west or center).
29030      * @param {Object} config The regions config object
29031      * @return {BorderLayoutRegion} The new region
29032      */
29033     addRegion : function(target, config){
29034         if(!this.regions[target]){
29035             var r = this.factory.create(target, this, config);
29036             this.bindRegion(target, r);
29037         }
29038         return this.regions[target];
29039     },
29040
29041     // private (kinda)
29042     bindRegion : function(name, r){
29043         this.regions[name] = r;
29044         r.on("visibilitychange", this.layout, this);
29045         r.on("paneladded", this.layout, this);
29046         r.on("panelremoved", this.layout, this);
29047         r.on("invalidated", this.layout, this);
29048         r.on("resized", this.onRegionResized, this);
29049         r.on("collapsed", this.onRegionCollapsed, this);
29050         r.on("expanded", this.onRegionExpanded, this);
29051     },
29052
29053     /**
29054      * Performs a layout update.
29055      */
29056     layout : function(){
29057         if(this.updating) {
29058             return;
29059         }
29060         var size = this.getViewSize();
29061         var w = size.width;
29062         var h = size.height;
29063         var centerW = w;
29064         var centerH = h;
29065         var centerY = 0;
29066         var centerX = 0;
29067         //var x = 0, y = 0;
29068
29069         var rs = this.regions;
29070         var north = rs["north"];
29071         var south = rs["south"]; 
29072         var west = rs["west"];
29073         var east = rs["east"];
29074         var center = rs["center"];
29075         //if(this.hideOnLayout){ // not supported anymore
29076             //c.el.setStyle("display", "none");
29077         //}
29078         if(north && north.isVisible()){
29079             var b = north.getBox();
29080             var m = north.getMargins();
29081             b.width = w - (m.left+m.right);
29082             b.x = m.left;
29083             b.y = m.top;
29084             centerY = b.height + b.y + m.bottom;
29085             centerH -= centerY;
29086             north.updateBox(this.safeBox(b));
29087         }
29088         if(south && south.isVisible()){
29089             var b = south.getBox();
29090             var m = south.getMargins();
29091             b.width = w - (m.left+m.right);
29092             b.x = m.left;
29093             var totalHeight = (b.height + m.top + m.bottom);
29094             b.y = h - totalHeight + m.top;
29095             centerH -= totalHeight;
29096             south.updateBox(this.safeBox(b));
29097         }
29098         if(west && west.isVisible()){
29099             var b = west.getBox();
29100             var m = west.getMargins();
29101             b.height = centerH - (m.top+m.bottom);
29102             b.x = m.left;
29103             b.y = centerY + m.top;
29104             var totalWidth = (b.width + m.left + m.right);
29105             centerX += totalWidth;
29106             centerW -= totalWidth;
29107             west.updateBox(this.safeBox(b));
29108         }
29109         if(east && east.isVisible()){
29110             var b = east.getBox();
29111             var m = east.getMargins();
29112             b.height = centerH - (m.top+m.bottom);
29113             var totalWidth = (b.width + m.left + m.right);
29114             b.x = w - totalWidth + m.left;
29115             b.y = centerY + m.top;
29116             centerW -= totalWidth;
29117             east.updateBox(this.safeBox(b));
29118         }
29119         if(center){
29120             var m = center.getMargins();
29121             var centerBox = {
29122                 x: centerX + m.left,
29123                 y: centerY + m.top,
29124                 width: centerW - (m.left+m.right),
29125                 height: centerH - (m.top+m.bottom)
29126             };
29127             //if(this.hideOnLayout){
29128                 //center.el.setStyle("display", "block");
29129             //}
29130             center.updateBox(this.safeBox(centerBox));
29131         }
29132         this.el.repaint();
29133         this.fireEvent("layout", this);
29134     },
29135
29136     // private
29137     safeBox : function(box){
29138         box.width = Math.max(0, box.width);
29139         box.height = Math.max(0, box.height);
29140         return box;
29141     },
29142
29143     /**
29144      * Adds a ContentPanel (or subclass) to this layout.
29145      * @param {String} target The target region key (north, south, east, west or center).
29146      * @param {Roo.ContentPanel} panel The panel to add
29147      * @return {Roo.ContentPanel} The added panel
29148      */
29149     add : function(target, panel){
29150          
29151         target = target.toLowerCase();
29152         return this.regions[target].add(panel);
29153     },
29154
29155     /**
29156      * Remove a ContentPanel (or subclass) to this layout.
29157      * @param {String} target The target region key (north, south, east, west or center).
29158      * @param {Number/String/Roo.ContentPanel} panel The index, id or panel to remove
29159      * @return {Roo.ContentPanel} The removed panel
29160      */
29161     remove : function(target, panel){
29162         target = target.toLowerCase();
29163         return this.regions[target].remove(panel);
29164     },
29165
29166     /**
29167      * Searches all regions for a panel with the specified id
29168      * @param {String} panelId
29169      * @return {Roo.ContentPanel} The panel or null if it wasn't found
29170      */
29171     findPanel : function(panelId){
29172         var rs = this.regions;
29173         for(var target in rs){
29174             if(typeof rs[target] != "function"){
29175                 var p = rs[target].getPanel(panelId);
29176                 if(p){
29177                     return p;
29178                 }
29179             }
29180         }
29181         return null;
29182     },
29183
29184     /**
29185      * Searches all regions for a panel with the specified id and activates (shows) it.
29186      * @param {String/ContentPanel} panelId The panels id or the panel itself
29187      * @return {Roo.ContentPanel} The shown panel or null
29188      */
29189     showPanel : function(panelId) {
29190       var rs = this.regions;
29191       for(var target in rs){
29192          var r = rs[target];
29193          if(typeof r != "function"){
29194             if(r.hasPanel(panelId)){
29195                return r.showPanel(panelId);
29196             }
29197          }
29198       }
29199       return null;
29200    },
29201
29202    /**
29203      * Restores this layout's state using Roo.state.Manager or the state provided by the passed provider.
29204      * @param {Roo.state.Provider} provider (optional) An alternate state provider
29205      */
29206     restoreState : function(provider){
29207         if(!provider){
29208             provider = Roo.state.Manager;
29209         }
29210         var sm = new Roo.LayoutStateManager();
29211         sm.init(this, provider);
29212     },
29213
29214     /**
29215      * Adds a batch of multiple ContentPanels dynamically by passing a special regions config object.  This config
29216      * object should contain properties for each region to add ContentPanels to, and each property's value should be
29217      * a valid ContentPanel config object.  Example:
29218      * <pre><code>
29219 // Create the main layout
29220 var layout = new Roo.BorderLayout('main-ct', {
29221     west: {
29222         split:true,
29223         minSize: 175,
29224         titlebar: true
29225     },
29226     center: {
29227         title:'Components'
29228     }
29229 }, 'main-ct');
29230
29231 // Create and add multiple ContentPanels at once via configs
29232 layout.batchAdd({
29233    west: {
29234        id: 'source-files',
29235        autoCreate:true,
29236        title:'Ext Source Files',
29237        autoScroll:true,
29238        fitToFrame:true
29239    },
29240    center : {
29241        el: cview,
29242        autoScroll:true,
29243        fitToFrame:true,
29244        toolbar: tb,
29245        resizeEl:'cbody'
29246    }
29247 });
29248 </code></pre>
29249      * @param {Object} regions An object containing ContentPanel configs by region name
29250      */
29251     batchAdd : function(regions){
29252         this.beginUpdate();
29253         for(var rname in regions){
29254             var lr = this.regions[rname];
29255             if(lr){
29256                 this.addTypedPanels(lr, regions[rname]);
29257             }
29258         }
29259         this.endUpdate();
29260     },
29261
29262     // private
29263     addTypedPanels : function(lr, ps){
29264         if(typeof ps == 'string'){
29265             lr.add(new Roo.ContentPanel(ps));
29266         }
29267         else if(ps instanceof Array){
29268             for(var i =0, len = ps.length; i < len; i++){
29269                 this.addTypedPanels(lr, ps[i]);
29270             }
29271         }
29272         else if(!ps.events){ // raw config?
29273             var el = ps.el;
29274             delete ps.el; // prevent conflict
29275             lr.add(new Roo.ContentPanel(el || Roo.id(), ps));
29276         }
29277         else {  // panel object assumed!
29278             lr.add(ps);
29279         }
29280     },
29281     /**
29282      * Adds a xtype elements to the layout.
29283      * <pre><code>
29284
29285 layout.addxtype({
29286        xtype : 'ContentPanel',
29287        region: 'west',
29288        items: [ .... ]
29289    }
29290 );
29291
29292 layout.addxtype({
29293         xtype : 'NestedLayoutPanel',
29294         region: 'west',
29295         layout: {
29296            center: { },
29297            west: { }   
29298         },
29299         items : [ ... list of content panels or nested layout panels.. ]
29300    }
29301 );
29302 </code></pre>
29303      * @param {Object} cfg Xtype definition of item to add.
29304      */
29305     addxtype : function(cfg)
29306     {
29307         // basically accepts a pannel...
29308         // can accept a layout region..!?!?
29309         //Roo.log('Roo.BorderLayout add ' + cfg.xtype)
29310         
29311         if (!cfg.xtype.match(/Panel$/)) {
29312             return false;
29313         }
29314         var ret = false;
29315         
29316         if (typeof(cfg.region) == 'undefined') {
29317             Roo.log("Failed to add Panel, region was not set");
29318             Roo.log(cfg);
29319             return false;
29320         }
29321         var region = cfg.region;
29322         delete cfg.region;
29323         
29324           
29325         var xitems = [];
29326         if (cfg.items) {
29327             xitems = cfg.items;
29328             delete cfg.items;
29329         }
29330         var nb = false;
29331         
29332         switch(cfg.xtype) 
29333         {
29334             case 'ContentPanel':  // ContentPanel (el, cfg)
29335             case 'ScrollPanel':  // ContentPanel (el, cfg)
29336             case 'ViewPanel': 
29337                 if(cfg.autoCreate) {
29338                     ret = new Roo[cfg.xtype](cfg); // new panel!!!!!
29339                 } else {
29340                     var el = this.el.createChild();
29341                     ret = new Roo[cfg.xtype](el, cfg); // new panel!!!!!
29342                 }
29343                 
29344                 this.add(region, ret);
29345                 break;
29346             
29347             
29348             case 'TreePanel': // our new panel!
29349                 cfg.el = this.el.createChild();
29350                 ret = new Roo[cfg.xtype](cfg); // new panel!!!!!
29351                 this.add(region, ret);
29352                 break;
29353             
29354             case 'NestedLayoutPanel': 
29355                 // create a new Layout (which is  a Border Layout...
29356                 var el = this.el.createChild();
29357                 var clayout = cfg.layout;
29358                 delete cfg.layout;
29359                 clayout.items   = clayout.items  || [];
29360                 // replace this exitems with the clayout ones..
29361                 xitems = clayout.items;
29362                  
29363                 
29364                 if (region == 'center' && this.active && this.getRegion('center').panels.length < 1) {
29365                     cfg.background = false;
29366                 }
29367                 var layout = new Roo.BorderLayout(el, clayout);
29368                 
29369                 ret = new Roo[cfg.xtype](layout, cfg); // new panel!!!!!
29370                 //console.log('adding nested layout panel '  + cfg.toSource());
29371                 this.add(region, ret);
29372                 nb = {}; /// find first...
29373                 break;
29374                 
29375             case 'GridPanel': 
29376             
29377                 // needs grid and region
29378                 
29379                 //var el = this.getRegion(region).el.createChild();
29380                 var el = this.el.createChild();
29381                 // create the grid first...
29382                 
29383                 var grid = new Roo.grid[cfg.grid.xtype](el, cfg.grid);
29384                 delete cfg.grid;
29385                 if (region == 'center' && this.active ) {
29386                     cfg.background = false;
29387                 }
29388                 ret = new Roo[cfg.xtype](grid, cfg); // new panel!!!!!
29389                 
29390                 this.add(region, ret);
29391                 if (cfg.background) {
29392                     ret.on('activate', function(gp) {
29393                         if (!gp.grid.rendered) {
29394                             gp.grid.render();
29395                         }
29396                     });
29397                 } else {
29398                     grid.render();
29399                 }
29400                 break;
29401            
29402            
29403            
29404                 
29405                 
29406                 
29407             default:
29408                 if (typeof(Roo[cfg.xtype]) != 'undefined') {
29409                     
29410                     ret = new Roo[cfg.xtype](cfg); // new panel!!!!!
29411                     this.add(region, ret);
29412                 } else {
29413                 
29414                     alert("Can not add '" + cfg.xtype + "' to BorderLayout");
29415                     return null;
29416                 }
29417                 
29418              // GridPanel (grid, cfg)
29419             
29420         }
29421         this.beginUpdate();
29422         // add children..
29423         var region = '';
29424         var abn = {};
29425         Roo.each(xitems, function(i)  {
29426             region = nb && i.region ? i.region : false;
29427             
29428             var add = ret.addxtype(i);
29429            
29430             if (region) {
29431                 nb[region] = nb[region] == undefined ? 0 : nb[region]+1;
29432                 if (!i.background) {
29433                     abn[region] = nb[region] ;
29434                 }
29435             }
29436             
29437         });
29438         this.endUpdate();
29439
29440         // make the last non-background panel active..
29441         //if (nb) { Roo.log(abn); }
29442         if (nb) {
29443             
29444             for(var r in abn) {
29445                 region = this.getRegion(r);
29446                 if (region) {
29447                     // tried using nb[r], but it does not work..
29448                      
29449                     region.showPanel(abn[r]);
29450                    
29451                 }
29452             }
29453         }
29454         return ret;
29455         
29456     }
29457 });
29458
29459 /**
29460  * Shortcut for creating a new BorderLayout object and adding one or more ContentPanels to it in a single step, handling
29461  * the beginUpdate and endUpdate calls internally.  The key to this method is the <b>panels</b> property that can be
29462  * provided with each region config, which allows you to add ContentPanel configs in addition to the region configs
29463  * during creation.  The following code is equivalent to the constructor-based example at the beginning of this class:
29464  * <pre><code>
29465 // shorthand
29466 var CP = Roo.ContentPanel;
29467
29468 var layout = Roo.BorderLayout.create({
29469     north: {
29470         initialSize: 25,
29471         titlebar: false,
29472         panels: [new CP("north", "North")]
29473     },
29474     west: {
29475         split:true,
29476         initialSize: 200,
29477         minSize: 175,
29478         maxSize: 400,
29479         titlebar: true,
29480         collapsible: true,
29481         panels: [new CP("west", {title: "West"})]
29482     },
29483     east: {
29484         split:true,
29485         initialSize: 202,
29486         minSize: 175,
29487         maxSize: 400,
29488         titlebar: true,
29489         collapsible: true,
29490         panels: [new CP("autoTabs", {title: "Auto Tabs", closable: true})]
29491     },
29492     south: {
29493         split:true,
29494         initialSize: 100,
29495         minSize: 100,
29496         maxSize: 200,
29497         titlebar: true,
29498         collapsible: true,
29499         panels: [new CP("south", {title: "South", closable: true})]
29500     },
29501     center: {
29502         titlebar: true,
29503         autoScroll:true,
29504         resizeTabs: true,
29505         minTabWidth: 50,
29506         preferredTabWidth: 150,
29507         panels: [
29508             new CP("center1", {title: "Close Me", closable: true}),
29509             new CP("center2", {title: "Center Panel", closable: false})
29510         ]
29511     }
29512 }, document.body);
29513
29514 layout.getRegion("center").showPanel("center1");
29515 </code></pre>
29516  * @param config
29517  * @param targetEl
29518  */
29519 Roo.BorderLayout.create = function(config, targetEl){
29520     var layout = new Roo.BorderLayout(targetEl || document.body, config);
29521     layout.beginUpdate();
29522     var regions = Roo.BorderLayout.RegionFactory.validRegions;
29523     for(var j = 0, jlen = regions.length; j < jlen; j++){
29524         var lr = regions[j];
29525         if(layout.regions[lr] && config[lr].panels){
29526             var r = layout.regions[lr];
29527             var ps = config[lr].panels;
29528             layout.addTypedPanels(r, ps);
29529         }
29530     }
29531     layout.endUpdate();
29532     return layout;
29533 };
29534
29535 // private
29536 Roo.BorderLayout.RegionFactory = {
29537     // private
29538     validRegions : ["north","south","east","west","center"],
29539
29540     // private
29541     create : function(target, mgr, config){
29542         target = target.toLowerCase();
29543         if(config.lightweight || config.basic){
29544             return new Roo.BasicLayoutRegion(mgr, config, target);
29545         }
29546         switch(target){
29547             case "north":
29548                 return new Roo.NorthLayoutRegion(mgr, config);
29549             case "south":
29550                 return new Roo.SouthLayoutRegion(mgr, config);
29551             case "east":
29552                 return new Roo.EastLayoutRegion(mgr, config);
29553             case "west":
29554                 return new Roo.WestLayoutRegion(mgr, config);
29555             case "center":
29556                 return new Roo.CenterLayoutRegion(mgr, config);
29557         }
29558         throw 'Layout region "'+target+'" not supported.';
29559     }
29560 };/*
29561  * Based on:
29562  * Ext JS Library 1.1.1
29563  * Copyright(c) 2006-2007, Ext JS, LLC.
29564  *
29565  * Originally Released Under LGPL - original licence link has changed is not relivant.
29566  *
29567  * Fork - LGPL
29568  * <script type="text/javascript">
29569  */
29570  
29571 /**
29572  * @class Roo.BasicLayoutRegion
29573  * @extends Roo.util.Observable
29574  * This class represents a lightweight region in a layout manager. This region does not move dom nodes
29575  * and does not have a titlebar, tabs or any other features. All it does is size and position 
29576  * panels. To create a BasicLayoutRegion, add lightweight:true or basic:true to your regions config.
29577  */
29578 Roo.BasicLayoutRegion = function(mgr, config, pos, skipConfig){
29579     this.mgr = mgr;
29580     this.position  = pos;
29581     this.events = {
29582         /**
29583          * @scope Roo.BasicLayoutRegion
29584          */
29585         
29586         /**
29587          * @event beforeremove
29588          * Fires before a panel is removed (or closed). To cancel the removal set "e.cancel = true" on the event argument.
29589          * @param {Roo.LayoutRegion} this
29590          * @param {Roo.ContentPanel} panel The panel
29591          * @param {Object} e The cancel event object
29592          */
29593         "beforeremove" : true,
29594         /**
29595          * @event invalidated
29596          * Fires when the layout for this region is changed.
29597          * @param {Roo.LayoutRegion} this
29598          */
29599         "invalidated" : true,
29600         /**
29601          * @event visibilitychange
29602          * Fires when this region is shown or hidden 
29603          * @param {Roo.LayoutRegion} this
29604          * @param {Boolean} visibility true or false
29605          */
29606         "visibilitychange" : true,
29607         /**
29608          * @event paneladded
29609          * Fires when a panel is added. 
29610          * @param {Roo.LayoutRegion} this
29611          * @param {Roo.ContentPanel} panel The panel
29612          */
29613         "paneladded" : true,
29614         /**
29615          * @event panelremoved
29616          * Fires when a panel is removed. 
29617          * @param {Roo.LayoutRegion} this
29618          * @param {Roo.ContentPanel} panel The panel
29619          */
29620         "panelremoved" : true,
29621         /**
29622          * @event beforecollapse
29623          * Fires when this region before collapse.
29624          * @param {Roo.LayoutRegion} this
29625          */
29626         "beforecollapse" : true,
29627         /**
29628          * @event collapsed
29629          * Fires when this region is collapsed.
29630          * @param {Roo.LayoutRegion} this
29631          */
29632         "collapsed" : true,
29633         /**
29634          * @event expanded
29635          * Fires when this region is expanded.
29636          * @param {Roo.LayoutRegion} this
29637          */
29638         "expanded" : true,
29639         /**
29640          * @event slideshow
29641          * Fires when this region is slid into view.
29642          * @param {Roo.LayoutRegion} this
29643          */
29644         "slideshow" : true,
29645         /**
29646          * @event slidehide
29647          * Fires when this region slides out of view. 
29648          * @param {Roo.LayoutRegion} this
29649          */
29650         "slidehide" : true,
29651         /**
29652          * @event panelactivated
29653          * Fires when a panel is activated. 
29654          * @param {Roo.LayoutRegion} this
29655          * @param {Roo.ContentPanel} panel The activated panel
29656          */
29657         "panelactivated" : true,
29658         /**
29659          * @event resized
29660          * Fires when the user resizes this region. 
29661          * @param {Roo.LayoutRegion} this
29662          * @param {Number} newSize The new size (width for east/west, height for north/south)
29663          */
29664         "resized" : true
29665     };
29666     /** A collection of panels in this region. @type Roo.util.MixedCollection */
29667     this.panels = new Roo.util.MixedCollection();
29668     this.panels.getKey = this.getPanelId.createDelegate(this);
29669     this.box = null;
29670     this.activePanel = null;
29671     // ensure listeners are added...
29672     
29673     if (config.listeners || config.events) {
29674         Roo.BasicLayoutRegion.superclass.constructor.call(this, {
29675             listeners : config.listeners || {},
29676             events : config.events || {}
29677         });
29678     }
29679     
29680     if(skipConfig !== true){
29681         this.applyConfig(config);
29682     }
29683 };
29684
29685 Roo.extend(Roo.BasicLayoutRegion, Roo.util.Observable, {
29686     getPanelId : function(p){
29687         return p.getId();
29688     },
29689     
29690     applyConfig : function(config){
29691         this.margins = config.margins || this.margins || {top: 0, left: 0, right:0, bottom: 0};
29692         this.config = config;
29693         
29694     },
29695     
29696     /**
29697      * Resizes the region to the specified size. For vertical regions (west, east) this adjusts 
29698      * the width, for horizontal (north, south) the height.
29699      * @param {Number} newSize The new width or height
29700      */
29701     resizeTo : function(newSize){
29702         var el = this.el ? this.el :
29703                  (this.activePanel ? this.activePanel.getEl() : null);
29704         if(el){
29705             switch(this.position){
29706                 case "east":
29707                 case "west":
29708                     el.setWidth(newSize);
29709                     this.fireEvent("resized", this, newSize);
29710                 break;
29711                 case "north":
29712                 case "south":
29713                     el.setHeight(newSize);
29714                     this.fireEvent("resized", this, newSize);
29715                 break;                
29716             }
29717         }
29718     },
29719     
29720     getBox : function(){
29721         return this.activePanel ? this.activePanel.getEl().getBox(false, true) : null;
29722     },
29723     
29724     getMargins : function(){
29725         return this.margins;
29726     },
29727     
29728     updateBox : function(box){
29729         this.box = box;
29730         var el = this.activePanel.getEl();
29731         el.dom.style.left = box.x + "px";
29732         el.dom.style.top = box.y + "px";
29733         this.activePanel.setSize(box.width, box.height);
29734     },
29735     
29736     /**
29737      * Returns the container element for this region.
29738      * @return {Roo.Element}
29739      */
29740     getEl : function(){
29741         return this.activePanel;
29742     },
29743     
29744     /**
29745      * Returns true if this region is currently visible.
29746      * @return {Boolean}
29747      */
29748     isVisible : function(){
29749         return this.activePanel ? true : false;
29750     },
29751     
29752     setActivePanel : function(panel){
29753         panel = this.getPanel(panel);
29754         if(this.activePanel && this.activePanel != panel){
29755             this.activePanel.setActiveState(false);
29756             this.activePanel.getEl().setLeftTop(-10000,-10000);
29757         }
29758         this.activePanel = panel;
29759         panel.setActiveState(true);
29760         if(this.box){
29761             panel.setSize(this.box.width, this.box.height);
29762         }
29763         this.fireEvent("panelactivated", this, panel);
29764         this.fireEvent("invalidated");
29765     },
29766     
29767     /**
29768      * Show the specified panel.
29769      * @param {Number/String/ContentPanel} panelId The panels index, id or the panel itself
29770      * @return {Roo.ContentPanel} The shown panel or null
29771      */
29772     showPanel : function(panel){
29773         if(panel = this.getPanel(panel)){
29774             this.setActivePanel(panel);
29775         }
29776         return panel;
29777     },
29778     
29779     /**
29780      * Get the active panel for this region.
29781      * @return {Roo.ContentPanel} The active panel or null
29782      */
29783     getActivePanel : function(){
29784         return this.activePanel;
29785     },
29786     
29787     /**
29788      * Add the passed ContentPanel(s)
29789      * @param {ContentPanel...} panel The ContentPanel(s) to add (you can pass more than one)
29790      * @return {Roo.ContentPanel} The panel added (if only one was added)
29791      */
29792     add : function(panel){
29793         if(arguments.length > 1){
29794             for(var i = 0, len = arguments.length; i < len; i++) {
29795                 this.add(arguments[i]);
29796             }
29797             return null;
29798         }
29799         if(this.hasPanel(panel)){
29800             this.showPanel(panel);
29801             return panel;
29802         }
29803         var el = panel.getEl();
29804         if(el.dom.parentNode != this.mgr.el.dom){
29805             this.mgr.el.dom.appendChild(el.dom);
29806         }
29807         if(panel.setRegion){
29808             panel.setRegion(this);
29809         }
29810         this.panels.add(panel);
29811         el.setStyle("position", "absolute");
29812         if(!panel.background){
29813             this.setActivePanel(panel);
29814             if(this.config.initialSize && this.panels.getCount()==1){
29815                 this.resizeTo(this.config.initialSize);
29816             }
29817         }
29818         this.fireEvent("paneladded", this, panel);
29819         return panel;
29820     },
29821     
29822     /**
29823      * Returns true if the panel is in this region.
29824      * @param {Number/String/ContentPanel} panel The panels index, id or the panel itself
29825      * @return {Boolean}
29826      */
29827     hasPanel : function(panel){
29828         if(typeof panel == "object"){ // must be panel obj
29829             panel = panel.getId();
29830         }
29831         return this.getPanel(panel) ? true : false;
29832     },
29833     
29834     /**
29835      * Removes the specified panel. If preservePanel is not true (either here or in the config), the panel is destroyed.
29836      * @param {Number/String/ContentPanel} panel The panels index, id or the panel itself
29837      * @param {Boolean} preservePanel Overrides the config preservePanel option
29838      * @return {Roo.ContentPanel} The panel that was removed
29839      */
29840     remove : function(panel, preservePanel){
29841         panel = this.getPanel(panel);
29842         if(!panel){
29843             return null;
29844         }
29845         var e = {};
29846         this.fireEvent("beforeremove", this, panel, e);
29847         if(e.cancel === true){
29848             return null;
29849         }
29850         var panelId = panel.getId();
29851         this.panels.removeKey(panelId);
29852         return panel;
29853     },
29854     
29855     /**
29856      * Returns the panel specified or null if it's not in this region.
29857      * @param {Number/String/ContentPanel} panel The panels index, id or the panel itself
29858      * @return {Roo.ContentPanel}
29859      */
29860     getPanel : function(id){
29861         if(typeof id == "object"){ // must be panel obj
29862             return id;
29863         }
29864         return this.panels.get(id);
29865     },
29866     
29867     /**
29868      * Returns this regions position (north/south/east/west/center).
29869      * @return {String} 
29870      */
29871     getPosition: function(){
29872         return this.position;    
29873     }
29874 });/*
29875  * Based on:
29876  * Ext JS Library 1.1.1
29877  * Copyright(c) 2006-2007, Ext JS, LLC.
29878  *
29879  * Originally Released Under LGPL - original licence link has changed is not relivant.
29880  *
29881  * Fork - LGPL
29882  * <script type="text/javascript">
29883  */
29884  
29885 /**
29886  * @class Roo.LayoutRegion
29887  * @extends Roo.BasicLayoutRegion
29888  * This class represents a region in a layout manager.
29889  * @cfg {Boolean}   collapsible     False to disable collapsing (defaults to true)
29890  * @cfg {Boolean}   collapsed       True to set the initial display to collapsed (defaults to false)
29891  * @cfg {Boolean}   floatable       False to disable floating (defaults to true)
29892  * @cfg {Object}    margins         Margins for the element (defaults to {top: 0, left: 0, right:0, bottom: 0})
29893  * @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})
29894  * @cfg {String}    tabPosition     (top|bottom) "top" or "bottom" (defaults to "bottom")
29895  * @cfg {String}    collapsedTitle  Optional string message to display in the collapsed block of a north or south region
29896  * @cfg {Boolean}   alwaysShowTabs  True to always display tabs even when there is only 1 panel (defaults to false)
29897  * @cfg {Boolean}   autoScroll      True to enable overflow scrolling (defaults to false)
29898  * @cfg {Boolean}   titlebar        True to display a title bar (defaults to true)
29899  * @cfg {String}    title           The title for the region (overrides panel titles)
29900  * @cfg {Boolean}   animate         True to animate expand/collapse (defaults to false)
29901  * @cfg {Boolean}   autoHide        False to disable auto hiding when the mouse leaves the "floated" region (defaults to true)
29902  * @cfg {Boolean}   preservePanels  True to preserve removed panels so they can be readded later (defaults to false)
29903  * @cfg {Boolean}   closeOnTab      True to place the close icon on the tabs instead of the region titlebar (defaults to false)
29904  * @cfg {Boolean}   hideTabs        True to hide the tab strip (defaults to false)
29905  * @cfg {Boolean}   resizeTabs      True to enable automatic tab resizing. This will resize the tabs so they are all the same size and fit within
29906  *                      the space available, similar to FireFox 1.5 tabs (defaults to false)
29907  * @cfg {Number}    minTabWidth     The minimum tab width (defaults to 40)
29908  * @cfg {Number}    preferredTabWidth The preferred tab width (defaults to 150)
29909  * @cfg {Boolean}   showPin         True to show a pin button
29910  * @cfg {Boolean}   hidden          True to start the region hidden (defaults to false)
29911  * @cfg {Boolean}   hideWhenEmpty   True to hide the region when it has no panels
29912  * @cfg {Boolean}   disableTabTips  True to disable tab tooltips
29913  * @cfg {Number}    width           For East/West panels
29914  * @cfg {Number}    height          For North/South panels
29915  * @cfg {Boolean}   split           To show the splitter
29916  * @cfg {Boolean}   toolbar         xtype configuration for a toolbar - shows on right of tabbar
29917  */
29918 Roo.LayoutRegion = function(mgr, config, pos){
29919     Roo.LayoutRegion.superclass.constructor.call(this, mgr, config, pos, true);
29920     var dh = Roo.DomHelper;
29921     /** This region's container element 
29922     * @type Roo.Element */
29923     this.el = dh.append(mgr.el.dom, {tag: "div", cls: "x-layout-panel x-layout-panel-" + this.position}, true);
29924     /** This region's title element 
29925     * @type Roo.Element */
29926
29927     this.titleEl = dh.append(this.el.dom, {tag: "div", unselectable: "on", cls: "x-unselectable x-layout-panel-hd x-layout-title-"+this.position, children:[
29928         {tag: "span", cls: "x-unselectable x-layout-panel-hd-text", unselectable: "on", html: "&#160;"},
29929         {tag: "div", cls: "x-unselectable x-layout-panel-hd-tools", unselectable: "on"}
29930     ]}, true);
29931     this.titleEl.enableDisplayMode();
29932     /** This region's title text element 
29933     * @type HTMLElement */
29934     this.titleTextEl = this.titleEl.dom.firstChild;
29935     this.tools = Roo.get(this.titleEl.dom.childNodes[1], true);
29936     this.closeBtn = this.createTool(this.tools.dom, "x-layout-close");
29937     this.closeBtn.enableDisplayMode();
29938     this.closeBtn.on("click", this.closeClicked, this);
29939     this.closeBtn.hide();
29940
29941     this.createBody(config);
29942     this.visible = true;
29943     this.collapsed = false;
29944
29945     if(config.hideWhenEmpty){
29946         this.hide();
29947         this.on("paneladded", this.validateVisibility, this);
29948         this.on("panelremoved", this.validateVisibility, this);
29949     }
29950     this.applyConfig(config);
29951 };
29952
29953 Roo.extend(Roo.LayoutRegion, Roo.BasicLayoutRegion, {
29954
29955     createBody : function(){
29956         /** This region's body element 
29957         * @type Roo.Element */
29958         this.bodyEl = this.el.createChild({tag: "div", cls: "x-layout-panel-body"});
29959     },
29960
29961     applyConfig : function(c){
29962         if(c.collapsible && this.position != "center" && !this.collapsedEl){
29963             var dh = Roo.DomHelper;
29964             if(c.titlebar !== false){
29965                 this.collapseBtn = this.createTool(this.tools.dom, "x-layout-collapse-"+this.position);
29966                 this.collapseBtn.on("click", this.collapse, this);
29967                 this.collapseBtn.enableDisplayMode();
29968
29969                 if(c.showPin === true || this.showPin){
29970                     this.stickBtn = this.createTool(this.tools.dom, "x-layout-stick");
29971                     this.stickBtn.enableDisplayMode();
29972                     this.stickBtn.on("click", this.expand, this);
29973                     this.stickBtn.hide();
29974                 }
29975             }
29976             /** This region's collapsed element
29977             * @type Roo.Element */
29978             this.collapsedEl = dh.append(this.mgr.el.dom, {cls: "x-layout-collapsed x-layout-collapsed-"+this.position, children:[
29979                 {cls: "x-layout-collapsed-tools", children:[{cls: "x-layout-ctools-inner"}]}
29980             ]}, true);
29981             if(c.floatable !== false){
29982                this.collapsedEl.addClassOnOver("x-layout-collapsed-over");
29983                this.collapsedEl.on("click", this.collapseClick, this);
29984             }
29985
29986             if(c.collapsedTitle && (this.position == "north" || this.position== "south")) {
29987                 this.collapsedTitleTextEl = dh.append(this.collapsedEl.dom, {tag: "div", cls: "x-unselectable x-layout-panel-hd-text",
29988                    id: "message", unselectable: "on", style:{"float":"left"}});
29989                this.collapsedTitleTextEl.innerHTML = c.collapsedTitle;
29990              }
29991             this.expandBtn = this.createTool(this.collapsedEl.dom.firstChild.firstChild, "x-layout-expand-"+this.position);
29992             this.expandBtn.on("click", this.expand, this);
29993         }
29994         if(this.collapseBtn){
29995             this.collapseBtn.setVisible(c.collapsible == true);
29996         }
29997         this.cmargins = c.cmargins || this.cmargins ||
29998                          (this.position == "west" || this.position == "east" ?
29999                              {top: 0, left: 2, right:2, bottom: 0} :
30000                              {top: 2, left: 0, right:0, bottom: 2});
30001         this.margins = c.margins || this.margins || {top: 0, left: 0, right:0, bottom: 0};
30002         this.bottomTabs = c.tabPosition != "top";
30003         this.autoScroll = c.autoScroll || false;
30004         if(this.autoScroll){
30005             this.bodyEl.setStyle("overflow", "auto");
30006         }else{
30007             this.bodyEl.setStyle("overflow", "hidden");
30008         }
30009         //if(c.titlebar !== false){
30010             if((!c.titlebar && !c.title) || c.titlebar === false){
30011                 this.titleEl.hide();
30012             }else{
30013                 this.titleEl.show();
30014                 if(c.title){
30015                     this.titleTextEl.innerHTML = c.title;
30016                 }
30017             }
30018         //}
30019         this.duration = c.duration || .30;
30020         this.slideDuration = c.slideDuration || .45;
30021         this.config = c;
30022         if(c.collapsed){
30023             this.collapse(true);
30024         }
30025         if(c.hidden){
30026             this.hide();
30027         }
30028     },
30029     /**
30030      * Returns true if this region is currently visible.
30031      * @return {Boolean}
30032      */
30033     isVisible : function(){
30034         return this.visible;
30035     },
30036
30037     /**
30038      * Updates the title for collapsed north/south regions (used with {@link #collapsedTitle} config option)
30039      * @param {String} title (optional) The title text (accepts HTML markup, defaults to the numeric character reference for a non-breaking space, "&amp;#160;")
30040      */
30041     setCollapsedTitle : function(title){
30042         title = title || "&#160;";
30043         if(this.collapsedTitleTextEl){
30044             this.collapsedTitleTextEl.innerHTML = title;
30045         }
30046     },
30047
30048     getBox : function(){
30049         var b;
30050         if(!this.collapsed){
30051             b = this.el.getBox(false, true);
30052         }else{
30053             b = this.collapsedEl.getBox(false, true);
30054         }
30055         return b;
30056     },
30057
30058     getMargins : function(){
30059         return this.collapsed ? this.cmargins : this.margins;
30060     },
30061
30062     highlight : function(){
30063         this.el.addClass("x-layout-panel-dragover");
30064     },
30065
30066     unhighlight : function(){
30067         this.el.removeClass("x-layout-panel-dragover");
30068     },
30069
30070     updateBox : function(box){
30071         this.box = box;
30072         if(!this.collapsed){
30073             this.el.dom.style.left = box.x + "px";
30074             this.el.dom.style.top = box.y + "px";
30075             this.updateBody(box.width, box.height);
30076         }else{
30077             this.collapsedEl.dom.style.left = box.x + "px";
30078             this.collapsedEl.dom.style.top = box.y + "px";
30079             this.collapsedEl.setSize(box.width, box.height);
30080         }
30081         if(this.tabs){
30082             this.tabs.autoSizeTabs();
30083         }
30084     },
30085
30086     updateBody : function(w, h){
30087         if(w !== null){
30088             this.el.setWidth(w);
30089             w -= this.el.getBorderWidth("rl");
30090             if(this.config.adjustments){
30091                 w += this.config.adjustments[0];
30092             }
30093         }
30094         if(h !== null){
30095             this.el.setHeight(h);
30096             h = this.titleEl && this.titleEl.isDisplayed() ? h - (this.titleEl.getHeight()||0) : h;
30097             h -= this.el.getBorderWidth("tb");
30098             if(this.config.adjustments){
30099                 h += this.config.adjustments[1];
30100             }
30101             this.bodyEl.setHeight(h);
30102             if(this.tabs){
30103                 h = this.tabs.syncHeight(h);
30104             }
30105         }
30106         if(this.panelSize){
30107             w = w !== null ? w : this.panelSize.width;
30108             h = h !== null ? h : this.panelSize.height;
30109         }
30110         if(this.activePanel){
30111             var el = this.activePanel.getEl();
30112             w = w !== null ? w : el.getWidth();
30113             h = h !== null ? h : el.getHeight();
30114             this.panelSize = {width: w, height: h};
30115             this.activePanel.setSize(w, h);
30116         }
30117         if(Roo.isIE && this.tabs){
30118             this.tabs.el.repaint();
30119         }
30120     },
30121
30122     /**
30123      * Returns the container element for this region.
30124      * @return {Roo.Element}
30125      */
30126     getEl : function(){
30127         return this.el;
30128     },
30129
30130     /**
30131      * Hides this region.
30132      */
30133     hide : function(){
30134         if(!this.collapsed){
30135             this.el.dom.style.left = "-2000px";
30136             this.el.hide();
30137         }else{
30138             this.collapsedEl.dom.style.left = "-2000px";
30139             this.collapsedEl.hide();
30140         }
30141         this.visible = false;
30142         this.fireEvent("visibilitychange", this, false);
30143     },
30144
30145     /**
30146      * Shows this region if it was previously hidden.
30147      */
30148     show : function(){
30149         if(!this.collapsed){
30150             this.el.show();
30151         }else{
30152             this.collapsedEl.show();
30153         }
30154         this.visible = true;
30155         this.fireEvent("visibilitychange", this, true);
30156     },
30157
30158     closeClicked : function(){
30159         if(this.activePanel){
30160             this.remove(this.activePanel);
30161         }
30162     },
30163
30164     collapseClick : function(e){
30165         if(this.isSlid){
30166            e.stopPropagation();
30167            this.slideIn();
30168         }else{
30169            e.stopPropagation();
30170            this.slideOut();
30171         }
30172     },
30173
30174     /**
30175      * Collapses this region.
30176      * @param {Boolean} skipAnim (optional) true to collapse the element without animation (if animate is true)
30177      */
30178     collapse : function(skipAnim, skipCheck){
30179         if(this.collapsed) {
30180             return;
30181         }
30182         
30183         if(skipCheck || this.fireEvent("beforecollapse", this) != false){
30184             
30185             this.collapsed = true;
30186             if(this.split){
30187                 this.split.el.hide();
30188             }
30189             if(this.config.animate && skipAnim !== true){
30190                 this.fireEvent("invalidated", this);
30191                 this.animateCollapse();
30192             }else{
30193                 this.el.setLocation(-20000,-20000);
30194                 this.el.hide();
30195                 this.collapsedEl.show();
30196                 this.fireEvent("collapsed", this);
30197                 this.fireEvent("invalidated", this);
30198             }
30199         }
30200         
30201     },
30202
30203     animateCollapse : function(){
30204         // overridden
30205     },
30206
30207     /**
30208      * Expands this region if it was previously collapsed.
30209      * @param {Roo.EventObject} e The event that triggered the expand (or null if calling manually)
30210      * @param {Boolean} skipAnim (optional) true to expand the element without animation (if animate is true)
30211      */
30212     expand : function(e, skipAnim){
30213         if(e) {
30214             e.stopPropagation();
30215         }
30216         if(!this.collapsed || this.el.hasActiveFx()) {
30217             return;
30218         }
30219         if(this.isSlid){
30220             this.afterSlideIn();
30221             skipAnim = true;
30222         }
30223         this.collapsed = false;
30224         if(this.config.animate && skipAnim !== true){
30225             this.animateExpand();
30226         }else{
30227             this.el.show();
30228             if(this.split){
30229                 this.split.el.show();
30230             }
30231             this.collapsedEl.setLocation(-2000,-2000);
30232             this.collapsedEl.hide();
30233             this.fireEvent("invalidated", this);
30234             this.fireEvent("expanded", this);
30235         }
30236     },
30237
30238     animateExpand : function(){
30239         // overridden
30240     },
30241
30242     initTabs : function()
30243     {
30244         this.bodyEl.setStyle("overflow", "hidden");
30245         var ts = new Roo.TabPanel(
30246                 this.bodyEl.dom,
30247                 {
30248                     tabPosition: this.bottomTabs ? 'bottom' : 'top',
30249                     disableTooltips: this.config.disableTabTips,
30250                     toolbar : this.config.toolbar
30251                 }
30252         );
30253         if(this.config.hideTabs){
30254             ts.stripWrap.setDisplayed(false);
30255         }
30256         this.tabs = ts;
30257         ts.resizeTabs = this.config.resizeTabs === true;
30258         ts.minTabWidth = this.config.minTabWidth || 40;
30259         ts.maxTabWidth = this.config.maxTabWidth || 250;
30260         ts.preferredTabWidth = this.config.preferredTabWidth || 150;
30261         ts.monitorResize = false;
30262         ts.bodyEl.setStyle("overflow", this.config.autoScroll ? "auto" : "hidden");
30263         ts.bodyEl.addClass('x-layout-tabs-body');
30264         this.panels.each(this.initPanelAsTab, this);
30265     },
30266
30267     initPanelAsTab : function(panel){
30268         var ti = this.tabs.addTab(panel.getEl().id, panel.getTitle(), null,
30269                     this.config.closeOnTab && panel.isClosable());
30270         if(panel.tabTip !== undefined){
30271             ti.setTooltip(panel.tabTip);
30272         }
30273         ti.on("activate", function(){
30274               this.setActivePanel(panel);
30275         }, this);
30276         if(this.config.closeOnTab){
30277             ti.on("beforeclose", function(t, e){
30278                 e.cancel = true;
30279                 this.remove(panel);
30280             }, this);
30281         }
30282         return ti;
30283     },
30284
30285     updatePanelTitle : function(panel, title){
30286         if(this.activePanel == panel){
30287             this.updateTitle(title);
30288         }
30289         if(this.tabs){
30290             var ti = this.tabs.getTab(panel.getEl().id);
30291             ti.setText(title);
30292             if(panel.tabTip !== undefined){
30293                 ti.setTooltip(panel.tabTip);
30294             }
30295         }
30296     },
30297
30298     updateTitle : function(title){
30299         if(this.titleTextEl && !this.config.title){
30300             this.titleTextEl.innerHTML = (typeof title != "undefined" && title.length > 0 ? title : "&#160;");
30301         }
30302     },
30303
30304     setActivePanel : function(panel){
30305         panel = this.getPanel(panel);
30306         if(this.activePanel && this.activePanel != panel){
30307             this.activePanel.setActiveState(false);
30308         }
30309         this.activePanel = panel;
30310         panel.setActiveState(true);
30311         if(this.panelSize){
30312             panel.setSize(this.panelSize.width, this.panelSize.height);
30313         }
30314         if(this.closeBtn){
30315             this.closeBtn.setVisible(!this.config.closeOnTab && !this.isSlid && panel.isClosable());
30316         }
30317         this.updateTitle(panel.getTitle());
30318         if(this.tabs){
30319             this.fireEvent("invalidated", this);
30320         }
30321         this.fireEvent("panelactivated", this, panel);
30322     },
30323
30324     /**
30325      * Shows the specified panel.
30326      * @param {Number/String/ContentPanel} panelId The panel's index, id or the panel itself
30327      * @return {Roo.ContentPanel} The shown panel, or null if a panel could not be found from panelId
30328      */
30329     showPanel : function(panel)
30330     {
30331         panel = this.getPanel(panel);
30332         if(panel){
30333             if(this.tabs){
30334                 var tab = this.tabs.getTab(panel.getEl().id);
30335                 if(tab.isHidden()){
30336                     this.tabs.unhideTab(tab.id);
30337                 }
30338                 tab.activate();
30339             }else{
30340                 this.setActivePanel(panel);
30341             }
30342         }
30343         return panel;
30344     },
30345
30346     /**
30347      * Get the active panel for this region.
30348      * @return {Roo.ContentPanel} The active panel or null
30349      */
30350     getActivePanel : function(){
30351         return this.activePanel;
30352     },
30353
30354     validateVisibility : function(){
30355         if(this.panels.getCount() < 1){
30356             this.updateTitle("&#160;");
30357             this.closeBtn.hide();
30358             this.hide();
30359         }else{
30360             if(!this.isVisible()){
30361                 this.show();
30362             }
30363         }
30364     },
30365
30366     /**
30367      * Adds the passed ContentPanel(s) to this region.
30368      * @param {ContentPanel...} panel The ContentPanel(s) to add (you can pass more than one)
30369      * @return {Roo.ContentPanel} The panel added (if only one was added; null otherwise)
30370      */
30371     add : function(panel){
30372         if(arguments.length > 1){
30373             for(var i = 0, len = arguments.length; i < len; i++) {
30374                 this.add(arguments[i]);
30375             }
30376             return null;
30377         }
30378         if(this.hasPanel(panel)){
30379             this.showPanel(panel);
30380             return panel;
30381         }
30382         panel.setRegion(this);
30383         this.panels.add(panel);
30384         if(this.panels.getCount() == 1 && !this.config.alwaysShowTabs){
30385             this.bodyEl.dom.appendChild(panel.getEl().dom);
30386             if(panel.background !== true){
30387                 this.setActivePanel(panel);
30388             }
30389             this.fireEvent("paneladded", this, panel);
30390             return panel;
30391         }
30392         if(!this.tabs){
30393             this.initTabs();
30394         }else{
30395             this.initPanelAsTab(panel);
30396         }
30397         if(panel.background !== true){
30398             this.tabs.activate(panel.getEl().id);
30399         }
30400         this.fireEvent("paneladded", this, panel);
30401         return panel;
30402     },
30403
30404     /**
30405      * Hides the tab for the specified panel.
30406      * @param {Number/String/ContentPanel} panel The panel's index, id or the panel itself
30407      */
30408     hidePanel : function(panel){
30409         if(this.tabs && (panel = this.getPanel(panel))){
30410             this.tabs.hideTab(panel.getEl().id);
30411         }
30412     },
30413
30414     /**
30415      * Unhides the tab for a previously hidden panel.
30416      * @param {Number/String/ContentPanel} panel The panel's index, id or the panel itself
30417      */
30418     unhidePanel : function(panel){
30419         if(this.tabs && (panel = this.getPanel(panel))){
30420             this.tabs.unhideTab(panel.getEl().id);
30421         }
30422     },
30423
30424     clearPanels : function(){
30425         while(this.panels.getCount() > 0){
30426              this.remove(this.panels.first());
30427         }
30428     },
30429
30430     /**
30431      * Removes the specified panel. If preservePanel is not true (either here or in the config), the panel is destroyed.
30432      * @param {Number/String/ContentPanel} panel The panel's index, id or the panel itself
30433      * @param {Boolean} preservePanel Overrides the config preservePanel option
30434      * @return {Roo.ContentPanel} The panel that was removed
30435      */
30436     remove : function(panel, preservePanel){
30437         panel = this.getPanel(panel);
30438         if(!panel){
30439             return null;
30440         }
30441         var e = {};
30442         this.fireEvent("beforeremove", this, panel, e);
30443         if(e.cancel === true){
30444             return null;
30445         }
30446         preservePanel = (typeof preservePanel != "undefined" ? preservePanel : (this.config.preservePanels === true || panel.preserve === true));
30447         var panelId = panel.getId();
30448         this.panels.removeKey(panelId);
30449         if(preservePanel){
30450             document.body.appendChild(panel.getEl().dom);
30451         }
30452         if(this.tabs){
30453             this.tabs.removeTab(panel.getEl().id);
30454         }else if (!preservePanel){
30455             this.bodyEl.dom.removeChild(panel.getEl().dom);
30456         }
30457         if(this.panels.getCount() == 1 && this.tabs && !this.config.alwaysShowTabs){
30458             var p = this.panels.first();
30459             var tempEl = document.createElement("div"); // temp holder to keep IE from deleting the node
30460             tempEl.appendChild(p.getEl().dom);
30461             this.bodyEl.update("");
30462             this.bodyEl.dom.appendChild(p.getEl().dom);
30463             tempEl = null;
30464             this.updateTitle(p.getTitle());
30465             this.tabs = null;
30466             this.bodyEl.setStyle("overflow", this.config.autoScroll ? "auto" : "hidden");
30467             this.setActivePanel(p);
30468         }
30469         panel.setRegion(null);
30470         if(this.activePanel == panel){
30471             this.activePanel = null;
30472         }
30473         if(this.config.autoDestroy !== false && preservePanel !== true){
30474             try{panel.destroy();}catch(e){}
30475         }
30476         this.fireEvent("panelremoved", this, panel);
30477         return panel;
30478     },
30479
30480     /**
30481      * Returns the TabPanel component used by this region
30482      * @return {Roo.TabPanel}
30483      */
30484     getTabs : function(){
30485         return this.tabs;
30486     },
30487
30488     createTool : function(parentEl, className){
30489         var btn = Roo.DomHelper.append(parentEl, {tag: "div", cls: "x-layout-tools-button",
30490             children: [{tag: "div", cls: "x-layout-tools-button-inner " + className, html: "&#160;"}]}, true);
30491         btn.addClassOnOver("x-layout-tools-button-over");
30492         return btn;
30493     }
30494 });/*
30495  * Based on:
30496  * Ext JS Library 1.1.1
30497  * Copyright(c) 2006-2007, Ext JS, LLC.
30498  *
30499  * Originally Released Under LGPL - original licence link has changed is not relivant.
30500  *
30501  * Fork - LGPL
30502  * <script type="text/javascript">
30503  */
30504  
30505
30506
30507 /**
30508  * @class Roo.SplitLayoutRegion
30509  * @extends Roo.LayoutRegion
30510  * Adds a splitbar and other (private) useful functionality to a {@link Roo.LayoutRegion}.
30511  */
30512 Roo.SplitLayoutRegion = function(mgr, config, pos, cursor){
30513     this.cursor = cursor;
30514     Roo.SplitLayoutRegion.superclass.constructor.call(this, mgr, config, pos);
30515 };
30516
30517 Roo.extend(Roo.SplitLayoutRegion, Roo.LayoutRegion, {
30518     splitTip : "Drag to resize.",
30519     collapsibleSplitTip : "Drag to resize. Double click to hide.",
30520     useSplitTips : false,
30521
30522     applyConfig : function(config){
30523         Roo.SplitLayoutRegion.superclass.applyConfig.call(this, config);
30524         if(config.split){
30525             if(!this.split){
30526                 var splitEl = Roo.DomHelper.append(this.mgr.el.dom, 
30527                         {tag: "div", id: this.el.id + "-split", cls: "x-layout-split x-layout-split-"+this.position, html: "&#160;"});
30528                 /** The SplitBar for this region 
30529                 * @type Roo.SplitBar */
30530                 this.split = new Roo.SplitBar(splitEl, this.el, this.orientation);
30531                 this.split.on("moved", this.onSplitMove, this);
30532                 this.split.useShim = config.useShim === true;
30533                 this.split.getMaximumSize = this[this.position == 'north' || this.position == 'south' ? 'getVMaxSize' : 'getHMaxSize'].createDelegate(this);
30534                 if(this.useSplitTips){
30535                     this.split.el.dom.title = config.collapsible ? this.collapsibleSplitTip : this.splitTip;
30536                 }
30537                 if(config.collapsible){
30538                     this.split.el.on("dblclick", this.collapse,  this);
30539                 }
30540             }
30541             if(typeof config.minSize != "undefined"){
30542                 this.split.minSize = config.minSize;
30543             }
30544             if(typeof config.maxSize != "undefined"){
30545                 this.split.maxSize = config.maxSize;
30546             }
30547             if(config.hideWhenEmpty || config.hidden || config.collapsed){
30548                 this.hideSplitter();
30549             }
30550         }
30551     },
30552
30553     getHMaxSize : function(){
30554          var cmax = this.config.maxSize || 10000;
30555          var center = this.mgr.getRegion("center");
30556          return Math.min(cmax, (this.el.getWidth()+center.getEl().getWidth())-center.getMinWidth());
30557     },
30558
30559     getVMaxSize : function(){
30560          var cmax = this.config.maxSize || 10000;
30561          var center = this.mgr.getRegion("center");
30562          return Math.min(cmax, (this.el.getHeight()+center.getEl().getHeight())-center.getMinHeight());
30563     },
30564
30565     onSplitMove : function(split, newSize){
30566         this.fireEvent("resized", this, newSize);
30567     },
30568     
30569     /** 
30570      * Returns the {@link Roo.SplitBar} for this region.
30571      * @return {Roo.SplitBar}
30572      */
30573     getSplitBar : function(){
30574         return this.split;
30575     },
30576     
30577     hide : function(){
30578         this.hideSplitter();
30579         Roo.SplitLayoutRegion.superclass.hide.call(this);
30580     },
30581
30582     hideSplitter : function(){
30583         if(this.split){
30584             this.split.el.setLocation(-2000,-2000);
30585             this.split.el.hide();
30586         }
30587     },
30588
30589     show : function(){
30590         if(this.split){
30591             this.split.el.show();
30592         }
30593         Roo.SplitLayoutRegion.superclass.show.call(this);
30594     },
30595     
30596     beforeSlide: function(){
30597         if(Roo.isGecko){// firefox overflow auto bug workaround
30598             this.bodyEl.clip();
30599             if(this.tabs) {
30600                 this.tabs.bodyEl.clip();
30601             }
30602             if(this.activePanel){
30603                 this.activePanel.getEl().clip();
30604                 
30605                 if(this.activePanel.beforeSlide){
30606                     this.activePanel.beforeSlide();
30607                 }
30608             }
30609         }
30610     },
30611     
30612     afterSlide : function(){
30613         if(Roo.isGecko){// firefox overflow auto bug workaround
30614             this.bodyEl.unclip();
30615             if(this.tabs) {
30616                 this.tabs.bodyEl.unclip();
30617             }
30618             if(this.activePanel){
30619                 this.activePanel.getEl().unclip();
30620                 if(this.activePanel.afterSlide){
30621                     this.activePanel.afterSlide();
30622                 }
30623             }
30624         }
30625     },
30626
30627     initAutoHide : function(){
30628         if(this.autoHide !== false){
30629             if(!this.autoHideHd){
30630                 var st = new Roo.util.DelayedTask(this.slideIn, this);
30631                 this.autoHideHd = {
30632                     "mouseout": function(e){
30633                         if(!e.within(this.el, true)){
30634                             st.delay(500);
30635                         }
30636                     },
30637                     "mouseover" : function(e){
30638                         st.cancel();
30639                     },
30640                     scope : this
30641                 };
30642             }
30643             this.el.on(this.autoHideHd);
30644         }
30645     },
30646
30647     clearAutoHide : function(){
30648         if(this.autoHide !== false){
30649             this.el.un("mouseout", this.autoHideHd.mouseout);
30650             this.el.un("mouseover", this.autoHideHd.mouseover);
30651         }
30652     },
30653
30654     clearMonitor : function(){
30655         Roo.get(document).un("click", this.slideInIf, this);
30656     },
30657
30658     // these names are backwards but not changed for compat
30659     slideOut : function(){
30660         if(this.isSlid || this.el.hasActiveFx()){
30661             return;
30662         }
30663         this.isSlid = true;
30664         if(this.collapseBtn){
30665             this.collapseBtn.hide();
30666         }
30667         this.closeBtnState = this.closeBtn.getStyle('display');
30668         this.closeBtn.hide();
30669         if(this.stickBtn){
30670             this.stickBtn.show();
30671         }
30672         this.el.show();
30673         this.el.alignTo(this.collapsedEl, this.getCollapseAnchor());
30674         this.beforeSlide();
30675         this.el.setStyle("z-index", 10001);
30676         this.el.slideIn(this.getSlideAnchor(), {
30677             callback: function(){
30678                 this.afterSlide();
30679                 this.initAutoHide();
30680                 Roo.get(document).on("click", this.slideInIf, this);
30681                 this.fireEvent("slideshow", this);
30682             },
30683             scope: this,
30684             block: true
30685         });
30686     },
30687
30688     afterSlideIn : function(){
30689         this.clearAutoHide();
30690         this.isSlid = false;
30691         this.clearMonitor();
30692         this.el.setStyle("z-index", "");
30693         if(this.collapseBtn){
30694             this.collapseBtn.show();
30695         }
30696         this.closeBtn.setStyle('display', this.closeBtnState);
30697         if(this.stickBtn){
30698             this.stickBtn.hide();
30699         }
30700         this.fireEvent("slidehide", this);
30701     },
30702
30703     slideIn : function(cb){
30704         if(!this.isSlid || this.el.hasActiveFx()){
30705             Roo.callback(cb);
30706             return;
30707         }
30708         this.isSlid = false;
30709         this.beforeSlide();
30710         this.el.slideOut(this.getSlideAnchor(), {
30711             callback: function(){
30712                 this.el.setLeftTop(-10000, -10000);
30713                 this.afterSlide();
30714                 this.afterSlideIn();
30715                 Roo.callback(cb);
30716             },
30717             scope: this,
30718             block: true
30719         });
30720     },
30721     
30722     slideInIf : function(e){
30723         if(!e.within(this.el)){
30724             this.slideIn();
30725         }
30726     },
30727
30728     animateCollapse : function(){
30729         this.beforeSlide();
30730         this.el.setStyle("z-index", 20000);
30731         var anchor = this.getSlideAnchor();
30732         this.el.slideOut(anchor, {
30733             callback : function(){
30734                 this.el.setStyle("z-index", "");
30735                 this.collapsedEl.slideIn(anchor, {duration:.3});
30736                 this.afterSlide();
30737                 this.el.setLocation(-10000,-10000);
30738                 this.el.hide();
30739                 this.fireEvent("collapsed", this);
30740             },
30741             scope: this,
30742             block: true
30743         });
30744     },
30745
30746     animateExpand : function(){
30747         this.beforeSlide();
30748         this.el.alignTo(this.collapsedEl, this.getCollapseAnchor(), this.getExpandAdj());
30749         this.el.setStyle("z-index", 20000);
30750         this.collapsedEl.hide({
30751             duration:.1
30752         });
30753         this.el.slideIn(this.getSlideAnchor(), {
30754             callback : function(){
30755                 this.el.setStyle("z-index", "");
30756                 this.afterSlide();
30757                 if(this.split){
30758                     this.split.el.show();
30759                 }
30760                 this.fireEvent("invalidated", this);
30761                 this.fireEvent("expanded", this);
30762             },
30763             scope: this,
30764             block: true
30765         });
30766     },
30767
30768     anchors : {
30769         "west" : "left",
30770         "east" : "right",
30771         "north" : "top",
30772         "south" : "bottom"
30773     },
30774
30775     sanchors : {
30776         "west" : "l",
30777         "east" : "r",
30778         "north" : "t",
30779         "south" : "b"
30780     },
30781
30782     canchors : {
30783         "west" : "tl-tr",
30784         "east" : "tr-tl",
30785         "north" : "tl-bl",
30786         "south" : "bl-tl"
30787     },
30788
30789     getAnchor : function(){
30790         return this.anchors[this.position];
30791     },
30792
30793     getCollapseAnchor : function(){
30794         return this.canchors[this.position];
30795     },
30796
30797     getSlideAnchor : function(){
30798         return this.sanchors[this.position];
30799     },
30800
30801     getAlignAdj : function(){
30802         var cm = this.cmargins;
30803         switch(this.position){
30804             case "west":
30805                 return [0, 0];
30806             break;
30807             case "east":
30808                 return [0, 0];
30809             break;
30810             case "north":
30811                 return [0, 0];
30812             break;
30813             case "south":
30814                 return [0, 0];
30815             break;
30816         }
30817     },
30818
30819     getExpandAdj : function(){
30820         var c = this.collapsedEl, cm = this.cmargins;
30821         switch(this.position){
30822             case "west":
30823                 return [-(cm.right+c.getWidth()+cm.left), 0];
30824             break;
30825             case "east":
30826                 return [cm.right+c.getWidth()+cm.left, 0];
30827             break;
30828             case "north":
30829                 return [0, -(cm.top+cm.bottom+c.getHeight())];
30830             break;
30831             case "south":
30832                 return [0, cm.top+cm.bottom+c.getHeight()];
30833             break;
30834         }
30835     }
30836 });/*
30837  * Based on:
30838  * Ext JS Library 1.1.1
30839  * Copyright(c) 2006-2007, Ext JS, LLC.
30840  *
30841  * Originally Released Under LGPL - original licence link has changed is not relivant.
30842  *
30843  * Fork - LGPL
30844  * <script type="text/javascript">
30845  */
30846 /*
30847  * These classes are private internal classes
30848  */
30849 Roo.CenterLayoutRegion = function(mgr, config){
30850     Roo.LayoutRegion.call(this, mgr, config, "center");
30851     this.visible = true;
30852     this.minWidth = config.minWidth || 20;
30853     this.minHeight = config.minHeight || 20;
30854 };
30855
30856 Roo.extend(Roo.CenterLayoutRegion, Roo.LayoutRegion, {
30857     hide : function(){
30858         // center panel can't be hidden
30859     },
30860     
30861     show : function(){
30862         // center panel can't be hidden
30863     },
30864     
30865     getMinWidth: function(){
30866         return this.minWidth;
30867     },
30868     
30869     getMinHeight: function(){
30870         return this.minHeight;
30871     }
30872 });
30873
30874
30875 Roo.NorthLayoutRegion = function(mgr, config){
30876     Roo.LayoutRegion.call(this, mgr, config, "north", "n-resize");
30877     if(this.split){
30878         this.split.placement = Roo.SplitBar.TOP;
30879         this.split.orientation = Roo.SplitBar.VERTICAL;
30880         this.split.el.addClass("x-layout-split-v");
30881     }
30882     var size = config.initialSize || config.height;
30883     if(typeof size != "undefined"){
30884         this.el.setHeight(size);
30885     }
30886 };
30887 Roo.extend(Roo.NorthLayoutRegion, Roo.SplitLayoutRegion, {
30888     orientation: Roo.SplitBar.VERTICAL,
30889     getBox : function(){
30890         if(this.collapsed){
30891             return this.collapsedEl.getBox();
30892         }
30893         var box = this.el.getBox();
30894         if(this.split){
30895             box.height += this.split.el.getHeight();
30896         }
30897         return box;
30898     },
30899     
30900     updateBox : function(box){
30901         if(this.split && !this.collapsed){
30902             box.height -= this.split.el.getHeight();
30903             this.split.el.setLeft(box.x);
30904             this.split.el.setTop(box.y+box.height);
30905             this.split.el.setWidth(box.width);
30906         }
30907         if(this.collapsed){
30908             this.updateBody(box.width, null);
30909         }
30910         Roo.LayoutRegion.prototype.updateBox.call(this, box);
30911     }
30912 });
30913
30914 Roo.SouthLayoutRegion = function(mgr, config){
30915     Roo.SplitLayoutRegion.call(this, mgr, config, "south", "s-resize");
30916     if(this.split){
30917         this.split.placement = Roo.SplitBar.BOTTOM;
30918         this.split.orientation = Roo.SplitBar.VERTICAL;
30919         this.split.el.addClass("x-layout-split-v");
30920     }
30921     var size = config.initialSize || config.height;
30922     if(typeof size != "undefined"){
30923         this.el.setHeight(size);
30924     }
30925 };
30926 Roo.extend(Roo.SouthLayoutRegion, Roo.SplitLayoutRegion, {
30927     orientation: Roo.SplitBar.VERTICAL,
30928     getBox : function(){
30929         if(this.collapsed){
30930             return this.collapsedEl.getBox();
30931         }
30932         var box = this.el.getBox();
30933         if(this.split){
30934             var sh = this.split.el.getHeight();
30935             box.height += sh;
30936             box.y -= sh;
30937         }
30938         return box;
30939     },
30940     
30941     updateBox : function(box){
30942         if(this.split && !this.collapsed){
30943             var sh = this.split.el.getHeight();
30944             box.height -= sh;
30945             box.y += sh;
30946             this.split.el.setLeft(box.x);
30947             this.split.el.setTop(box.y-sh);
30948             this.split.el.setWidth(box.width);
30949         }
30950         if(this.collapsed){
30951             this.updateBody(box.width, null);
30952         }
30953         Roo.LayoutRegion.prototype.updateBox.call(this, box);
30954     }
30955 });
30956
30957 Roo.EastLayoutRegion = function(mgr, config){
30958     Roo.SplitLayoutRegion.call(this, mgr, config, "east", "e-resize");
30959     if(this.split){
30960         this.split.placement = Roo.SplitBar.RIGHT;
30961         this.split.orientation = Roo.SplitBar.HORIZONTAL;
30962         this.split.el.addClass("x-layout-split-h");
30963     }
30964     var size = config.initialSize || config.width;
30965     if(typeof size != "undefined"){
30966         this.el.setWidth(size);
30967     }
30968 };
30969 Roo.extend(Roo.EastLayoutRegion, Roo.SplitLayoutRegion, {
30970     orientation: Roo.SplitBar.HORIZONTAL,
30971     getBox : function(){
30972         if(this.collapsed){
30973             return this.collapsedEl.getBox();
30974         }
30975         var box = this.el.getBox();
30976         if(this.split){
30977             var sw = this.split.el.getWidth();
30978             box.width += sw;
30979             box.x -= sw;
30980         }
30981         return box;
30982     },
30983
30984     updateBox : function(box){
30985         if(this.split && !this.collapsed){
30986             var sw = this.split.el.getWidth();
30987             box.width -= sw;
30988             this.split.el.setLeft(box.x);
30989             this.split.el.setTop(box.y);
30990             this.split.el.setHeight(box.height);
30991             box.x += sw;
30992         }
30993         if(this.collapsed){
30994             this.updateBody(null, box.height);
30995         }
30996         Roo.LayoutRegion.prototype.updateBox.call(this, box);
30997     }
30998 });
30999
31000 Roo.WestLayoutRegion = function(mgr, config){
31001     Roo.SplitLayoutRegion.call(this, mgr, config, "west", "w-resize");
31002     if(this.split){
31003         this.split.placement = Roo.SplitBar.LEFT;
31004         this.split.orientation = Roo.SplitBar.HORIZONTAL;
31005         this.split.el.addClass("x-layout-split-h");
31006     }
31007     var size = config.initialSize || config.width;
31008     if(typeof size != "undefined"){
31009         this.el.setWidth(size);
31010     }
31011 };
31012 Roo.extend(Roo.WestLayoutRegion, Roo.SplitLayoutRegion, {
31013     orientation: Roo.SplitBar.HORIZONTAL,
31014     getBox : function(){
31015         if(this.collapsed){
31016             return this.collapsedEl.getBox();
31017         }
31018         var box = this.el.getBox();
31019         if(this.split){
31020             box.width += this.split.el.getWidth();
31021         }
31022         return box;
31023     },
31024     
31025     updateBox : function(box){
31026         if(this.split && !this.collapsed){
31027             var sw = this.split.el.getWidth();
31028             box.width -= sw;
31029             this.split.el.setLeft(box.x+box.width);
31030             this.split.el.setTop(box.y);
31031             this.split.el.setHeight(box.height);
31032         }
31033         if(this.collapsed){
31034             this.updateBody(null, box.height);
31035         }
31036         Roo.LayoutRegion.prototype.updateBox.call(this, box);
31037     }
31038 });
31039 /*
31040  * Based on:
31041  * Ext JS Library 1.1.1
31042  * Copyright(c) 2006-2007, Ext JS, LLC.
31043  *
31044  * Originally Released Under LGPL - original licence link has changed is not relivant.
31045  *
31046  * Fork - LGPL
31047  * <script type="text/javascript">
31048  */
31049  
31050  
31051 /*
31052  * Private internal class for reading and applying state
31053  */
31054 Roo.LayoutStateManager = function(layout){
31055      // default empty state
31056      this.state = {
31057         north: {},
31058         south: {},
31059         east: {},
31060         west: {}       
31061     };
31062 };
31063
31064 Roo.LayoutStateManager.prototype = {
31065     init : function(layout, provider){
31066         this.provider = provider;
31067         var state = provider.get(layout.id+"-layout-state");
31068         if(state){
31069             var wasUpdating = layout.isUpdating();
31070             if(!wasUpdating){
31071                 layout.beginUpdate();
31072             }
31073             for(var key in state){
31074                 if(typeof state[key] != "function"){
31075                     var rstate = state[key];
31076                     var r = layout.getRegion(key);
31077                     if(r && rstate){
31078                         if(rstate.size){
31079                             r.resizeTo(rstate.size);
31080                         }
31081                         if(rstate.collapsed == true){
31082                             r.collapse(true);
31083                         }else{
31084                             r.expand(null, true);
31085                         }
31086                     }
31087                 }
31088             }
31089             if(!wasUpdating){
31090                 layout.endUpdate();
31091             }
31092             this.state = state; 
31093         }
31094         this.layout = layout;
31095         layout.on("regionresized", this.onRegionResized, this);
31096         layout.on("regioncollapsed", this.onRegionCollapsed, this);
31097         layout.on("regionexpanded", this.onRegionExpanded, this);
31098     },
31099     
31100     storeState : function(){
31101         this.provider.set(this.layout.id+"-layout-state", this.state);
31102     },
31103     
31104     onRegionResized : function(region, newSize){
31105         this.state[region.getPosition()].size = newSize;
31106         this.storeState();
31107     },
31108     
31109     onRegionCollapsed : function(region){
31110         this.state[region.getPosition()].collapsed = true;
31111         this.storeState();
31112     },
31113     
31114     onRegionExpanded : function(region){
31115         this.state[region.getPosition()].collapsed = false;
31116         this.storeState();
31117     }
31118 };/*
31119  * Based on:
31120  * Ext JS Library 1.1.1
31121  * Copyright(c) 2006-2007, Ext JS, LLC.
31122  *
31123  * Originally Released Under LGPL - original licence link has changed is not relivant.
31124  *
31125  * Fork - LGPL
31126  * <script type="text/javascript">
31127  */
31128 /**
31129  * @class Roo.ContentPanel
31130  * @extends Roo.util.Observable
31131  * A basic ContentPanel element.
31132  * @cfg {Boolean}   fitToFrame    True for this panel to adjust its size to fit when the region resizes  (defaults to false)
31133  * @cfg {Boolean}   fitContainer   When using {@link #fitToFrame} and {@link #resizeEl}, you can also fit the parent container  (defaults to false)
31134  * @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
31135  * @cfg {Boolean}   closable      True if the panel can be closed/removed
31136  * @cfg {Boolean}   background    True if the panel should not be activated when it is added (defaults to false)
31137  * @cfg {String/HTMLElement/Element} resizeEl An element to resize if {@link #fitToFrame} is true (instead of this panel's element)
31138  * @cfg {Toolbar}   toolbar       A toolbar for this panel
31139  * @cfg {Boolean} autoScroll    True to scroll overflow in this panel (use with {@link #fitToFrame})
31140  * @cfg {String} title          The title for this panel
31141  * @cfg {Array} adjustments     Values to <b>add</b> to the width/height when doing a {@link #fitToFrame} (default is [0, 0])
31142  * @cfg {String} url            Calls {@link #setUrl} with this value
31143  * @cfg {String} region         (center|north|south|east|west) which region to put this panel on (when used with xtype constructors)
31144  * @cfg {String/Object} params  When used with {@link #url}, calls {@link #setUrl} with this value
31145  * @cfg {Boolean} loadOnce      When used with {@link #url}, calls {@link #setUrl} with this value
31146  * @cfg {String}    content        Raw content to fill content panel with (uses setContent on construction.)
31147
31148  * @constructor
31149  * Create a new ContentPanel.
31150  * @param {String/HTMLElement/Roo.Element} el The container element for this panel
31151  * @param {String/Object} config A string to set only the title or a config object
31152  * @param {String} content (optional) Set the HTML content for this panel
31153  * @param {String} region (optional) Used by xtype constructors to add to regions. (values center,east,west,south,north)
31154  */
31155 Roo.ContentPanel = function(el, config, content){
31156     
31157      
31158     /*
31159     if(el.autoCreate || el.xtype){ // xtype is available if this is called from factory
31160         config = el;
31161         el = Roo.id();
31162     }
31163     if (config && config.parentLayout) { 
31164         el = config.parentLayout.el.createChild(); 
31165     }
31166     */
31167     if(el.autoCreate){ // xtype is available if this is called from factory
31168         config = el;
31169         el = Roo.id();
31170     }
31171     this.el = Roo.get(el);
31172     if(!this.el && config && config.autoCreate){
31173         if(typeof config.autoCreate == "object"){
31174             if(!config.autoCreate.id){
31175                 config.autoCreate.id = config.id||el;
31176             }
31177             this.el = Roo.DomHelper.append(document.body,
31178                         config.autoCreate, true);
31179         }else{
31180             this.el = Roo.DomHelper.append(document.body,
31181                         {tag: "div", cls: "x-layout-inactive-content", id: config.id||el}, true);
31182         }
31183     }
31184     this.closable = false;
31185     this.loaded = false;
31186     this.active = false;
31187     if(typeof config == "string"){
31188         this.title = config;
31189     }else{
31190         Roo.apply(this, config);
31191     }
31192     
31193     if (this.toolbar && !this.toolbar.el && this.toolbar.xtype) {
31194         this.wrapEl = this.el.wrap();
31195         this.toolbar.container = this.el.insertSibling(false, 'before');
31196         this.toolbar = new Roo.Toolbar(this.toolbar);
31197     }
31198     
31199     // xtype created footer. - not sure if will work as we normally have to render first..
31200     if (this.footer && !this.footer.el && this.footer.xtype) {
31201         if (!this.wrapEl) {
31202             this.wrapEl = this.el.wrap();
31203         }
31204     
31205         this.footer.container = this.wrapEl.createChild();
31206          
31207         this.footer = Roo.factory(this.footer, Roo);
31208         
31209     }
31210     
31211     if(this.resizeEl){
31212         this.resizeEl = Roo.get(this.resizeEl, true);
31213     }else{
31214         this.resizeEl = this.el;
31215     }
31216     // handle view.xtype
31217     
31218  
31219     
31220     
31221     this.addEvents({
31222         /**
31223          * @event activate
31224          * Fires when this panel is activated. 
31225          * @param {Roo.ContentPanel} this
31226          */
31227         "activate" : true,
31228         /**
31229          * @event deactivate
31230          * Fires when this panel is activated. 
31231          * @param {Roo.ContentPanel} this
31232          */
31233         "deactivate" : true,
31234
31235         /**
31236          * @event resize
31237          * Fires when this panel is resized if fitToFrame is true.
31238          * @param {Roo.ContentPanel} this
31239          * @param {Number} width The width after any component adjustments
31240          * @param {Number} height The height after any component adjustments
31241          */
31242         "resize" : true,
31243         
31244          /**
31245          * @event render
31246          * Fires when this tab is created
31247          * @param {Roo.ContentPanel} this
31248          */
31249         "render" : true
31250          
31251         
31252     });
31253     
31254
31255     
31256     
31257     if(this.autoScroll){
31258         this.resizeEl.setStyle("overflow", "auto");
31259     } else {
31260         // fix randome scrolling
31261         this.el.on('scroll', function() {
31262             Roo.log('fix random scolling');
31263             this.scrollTo('top',0); 
31264         });
31265     }
31266     content = content || this.content;
31267     if(content){
31268         this.setContent(content);
31269     }
31270     if(config && config.url){
31271         this.setUrl(this.url, this.params, this.loadOnce);
31272     }
31273     
31274     
31275     
31276     Roo.ContentPanel.superclass.constructor.call(this);
31277     
31278     if (this.view && typeof(this.view.xtype) != 'undefined') {
31279         this.view.el = this.el.appendChild(document.createElement("div"));
31280         this.view = Roo.factory(this.view); 
31281         this.view.render  &&  this.view.render(false, '');  
31282     }
31283     
31284     
31285     this.fireEvent('render', this);
31286 };
31287
31288 Roo.extend(Roo.ContentPanel, Roo.util.Observable, {
31289     tabTip:'',
31290     setRegion : function(region){
31291         this.region = region;
31292         if(region){
31293            this.el.replaceClass("x-layout-inactive-content", "x-layout-active-content");
31294         }else{
31295            this.el.replaceClass("x-layout-active-content", "x-layout-inactive-content");
31296         } 
31297     },
31298     
31299     /**
31300      * Returns the toolbar for this Panel if one was configured. 
31301      * @return {Roo.Toolbar} 
31302      */
31303     getToolbar : function(){
31304         return this.toolbar;
31305     },
31306     
31307     setActiveState : function(active){
31308         this.active = active;
31309         if(!active){
31310             this.fireEvent("deactivate", this);
31311         }else{
31312             this.fireEvent("activate", this);
31313         }
31314     },
31315     /**
31316      * Updates this panel's element
31317      * @param {String} content The new content
31318      * @param {Boolean} loadScripts (optional) true to look for and process scripts
31319     */
31320     setContent : function(content, loadScripts){
31321         this.el.update(content, loadScripts);
31322     },
31323
31324     ignoreResize : function(w, h){
31325         if(this.lastSize && this.lastSize.width == w && this.lastSize.height == h){
31326             return true;
31327         }else{
31328             this.lastSize = {width: w, height: h};
31329             return false;
31330         }
31331     },
31332     /**
31333      * Get the {@link Roo.UpdateManager} for this panel. Enables you to perform Ajax updates.
31334      * @return {Roo.UpdateManager} The UpdateManager
31335      */
31336     getUpdateManager : function(){
31337         return this.el.getUpdateManager();
31338     },
31339      /**
31340      * Loads this content panel immediately with content from XHR. Note: to delay loading until the panel is activated, use {@link #setUrl}.
31341      * @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:
31342 <pre><code>
31343 panel.load({
31344     url: "your-url.php",
31345     params: {param1: "foo", param2: "bar"}, // or a URL encoded string
31346     callback: yourFunction,
31347     scope: yourObject, //(optional scope)
31348     discardUrl: false,
31349     nocache: false,
31350     text: "Loading...",
31351     timeout: 30,
31352     scripts: false
31353 });
31354 </code></pre>
31355      * The only required property is <i>url</i>. The optional properties <i>nocache</i>, <i>text</i> and <i>scripts</i>
31356      * 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.
31357      * @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}
31358      * @param {Function} callback (optional) Callback when transaction is complete -- called with signature (oElement, bSuccess, oResponse)
31359      * @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.
31360      * @return {Roo.ContentPanel} this
31361      */
31362     load : function(){
31363         var um = this.el.getUpdateManager();
31364         um.update.apply(um, arguments);
31365         return this;
31366     },
31367
31368
31369     /**
31370      * 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.
31371      * @param {String/Function} url The URL to load the content from or a function to call to get the URL
31372      * @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)
31373      * @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)
31374      * @return {Roo.UpdateManager} The UpdateManager
31375      */
31376     setUrl : function(url, params, loadOnce){
31377         if(this.refreshDelegate){
31378             this.removeListener("activate", this.refreshDelegate);
31379         }
31380         this.refreshDelegate = this._handleRefresh.createDelegate(this, [url, params, loadOnce]);
31381         this.on("activate", this.refreshDelegate);
31382         return this.el.getUpdateManager();
31383     },
31384     
31385     _handleRefresh : function(url, params, loadOnce){
31386         if(!loadOnce || !this.loaded){
31387             var updater = this.el.getUpdateManager();
31388             updater.update(url, params, this._setLoaded.createDelegate(this));
31389         }
31390     },
31391     
31392     _setLoaded : function(){
31393         this.loaded = true;
31394     }, 
31395     
31396     /**
31397      * Returns this panel's id
31398      * @return {String} 
31399      */
31400     getId : function(){
31401         return this.el.id;
31402     },
31403     
31404     /** 
31405      * Returns this panel's element - used by regiosn to add.
31406      * @return {Roo.Element} 
31407      */
31408     getEl : function(){
31409         return this.wrapEl || this.el;
31410     },
31411     
31412     adjustForComponents : function(width, height)
31413     {
31414         //Roo.log('adjustForComponents ');
31415         if(this.resizeEl != this.el){
31416             width -= this.el.getFrameWidth('lr');
31417             height -= this.el.getFrameWidth('tb');
31418         }
31419         if(this.toolbar){
31420             var te = this.toolbar.getEl();
31421             height -= te.getHeight();
31422             te.setWidth(width);
31423         }
31424         if(this.footer){
31425             var te = this.footer.getEl();
31426             //Roo.log("footer:" + te.getHeight());
31427             
31428             height -= te.getHeight();
31429             te.setWidth(width);
31430         }
31431         
31432         
31433         if(this.adjustments){
31434             width += this.adjustments[0];
31435             height += this.adjustments[1];
31436         }
31437         return {"width": width, "height": height};
31438     },
31439     
31440     setSize : function(width, height){
31441         if(this.fitToFrame && !this.ignoreResize(width, height)){
31442             if(this.fitContainer && this.resizeEl != this.el){
31443                 this.el.setSize(width, height);
31444             }
31445             var size = this.adjustForComponents(width, height);
31446             this.resizeEl.setSize(this.autoWidth ? "auto" : size.width, this.autoHeight ? "auto" : size.height);
31447             this.fireEvent('resize', this, size.width, size.height);
31448         }
31449     },
31450     
31451     /**
31452      * Returns this panel's title
31453      * @return {String} 
31454      */
31455     getTitle : function(){
31456         return this.title;
31457     },
31458     
31459     /**
31460      * Set this panel's title
31461      * @param {String} title
31462      */
31463     setTitle : function(title){
31464         this.title = title;
31465         if(this.region){
31466             this.region.updatePanelTitle(this, title);
31467         }
31468     },
31469     
31470     /**
31471      * Returns true is this panel was configured to be closable
31472      * @return {Boolean} 
31473      */
31474     isClosable : function(){
31475         return this.closable;
31476     },
31477     
31478     beforeSlide : function(){
31479         this.el.clip();
31480         this.resizeEl.clip();
31481     },
31482     
31483     afterSlide : function(){
31484         this.el.unclip();
31485         this.resizeEl.unclip();
31486     },
31487     
31488     /**
31489      *   Force a content refresh from the URL specified in the {@link #setUrl} method.
31490      *   Will fail silently if the {@link #setUrl} method has not been called.
31491      *   This does not activate the panel, just updates its content.
31492      */
31493     refresh : function(){
31494         if(this.refreshDelegate){
31495            this.loaded = false;
31496            this.refreshDelegate();
31497         }
31498     },
31499     
31500     /**
31501      * Destroys this panel
31502      */
31503     destroy : function(){
31504         this.el.removeAllListeners();
31505         var tempEl = document.createElement("span");
31506         tempEl.appendChild(this.el.dom);
31507         tempEl.innerHTML = "";
31508         this.el.remove();
31509         this.el = null;
31510     },
31511     
31512     /**
31513      * form - if the content panel contains a form - this is a reference to it.
31514      * @type {Roo.form.Form}
31515      */
31516     form : false,
31517     /**
31518      * view - if the content panel contains a view (Roo.DatePicker / Roo.View / Roo.JsonView)
31519      *    This contains a reference to it.
31520      * @type {Roo.View}
31521      */
31522     view : false,
31523     
31524       /**
31525      * Adds a xtype elements to the panel - currently only supports Forms, View, JsonView.
31526      * <pre><code>
31527
31528 layout.addxtype({
31529        xtype : 'Form',
31530        items: [ .... ]
31531    }
31532 );
31533
31534 </code></pre>
31535      * @param {Object} cfg Xtype definition of item to add.
31536      */
31537     
31538     addxtype : function(cfg) {
31539         // add form..
31540         if (cfg.xtype.match(/^Form$/)) {
31541             
31542             var el;
31543             //if (this.footer) {
31544             //    el = this.footer.container.insertSibling(false, 'before');
31545             //} else {
31546                 el = this.el.createChild();
31547             //}
31548
31549             this.form = new  Roo.form.Form(cfg);
31550             
31551             
31552             if ( this.form.allItems.length) {
31553                 this.form.render(el.dom);
31554             }
31555             return this.form;
31556         }
31557         // should only have one of theses..
31558         if ([ 'View', 'JsonView', 'DatePicker'].indexOf(cfg.xtype) > -1) {
31559             // views.. should not be just added - used named prop 'view''
31560             
31561             cfg.el = this.el.appendChild(document.createElement("div"));
31562             // factory?
31563             
31564             var ret = new Roo.factory(cfg);
31565              
31566              ret.render && ret.render(false, ''); // render blank..
31567             this.view = ret;
31568             return ret;
31569         }
31570         return false;
31571     }
31572 });
31573
31574 /**
31575  * @class Roo.GridPanel
31576  * @extends Roo.ContentPanel
31577  * @constructor
31578  * Create a new GridPanel.
31579  * @param {Roo.grid.Grid} grid The grid for this panel
31580  * @param {String/Object} config A string to set only the panel's title, or a config object
31581  */
31582 Roo.GridPanel = function(grid, config){
31583     
31584   
31585     this.wrapper = Roo.DomHelper.append(document.body, // wrapper for IE7 strict & safari scroll issue
31586         {tag: "div", cls: "x-layout-grid-wrapper x-layout-inactive-content"}, true);
31587         
31588     this.wrapper.dom.appendChild(grid.getGridEl().dom);
31589     
31590     Roo.GridPanel.superclass.constructor.call(this, this.wrapper, config);
31591     
31592     if(this.toolbar){
31593         this.toolbar.el.insertBefore(this.wrapper.dom.firstChild);
31594     }
31595     // xtype created footer. - not sure if will work as we normally have to render first..
31596     if (this.footer && !this.footer.el && this.footer.xtype) {
31597         
31598         this.footer.container = this.grid.getView().getFooterPanel(true);
31599         this.footer.dataSource = this.grid.dataSource;
31600         this.footer = Roo.factory(this.footer, Roo);
31601         
31602     }
31603     
31604     grid.monitorWindowResize = false; // turn off autosizing
31605     grid.autoHeight = false;
31606     grid.autoWidth = false;
31607     this.grid = grid;
31608     this.grid.getGridEl().replaceClass("x-layout-inactive-content", "x-layout-component-panel");
31609 };
31610
31611 Roo.extend(Roo.GridPanel, Roo.ContentPanel, {
31612     getId : function(){
31613         return this.grid.id;
31614     },
31615     
31616     /**
31617      * Returns the grid for this panel
31618      * @return {Roo.grid.Grid} 
31619      */
31620     getGrid : function(){
31621         return this.grid;    
31622     },
31623     
31624     setSize : function(width, height){
31625         if(!this.ignoreResize(width, height)){
31626             var grid = this.grid;
31627             var size = this.adjustForComponents(width, height);
31628             grid.getGridEl().setSize(size.width, size.height);
31629             grid.autoSize();
31630         }
31631     },
31632     
31633     beforeSlide : function(){
31634         this.grid.getView().scroller.clip();
31635     },
31636     
31637     afterSlide : function(){
31638         this.grid.getView().scroller.unclip();
31639     },
31640     
31641     destroy : function(){
31642         this.grid.destroy();
31643         delete this.grid;
31644         Roo.GridPanel.superclass.destroy.call(this); 
31645     }
31646 });
31647
31648
31649 /**
31650  * @class Roo.NestedLayoutPanel
31651  * @extends Roo.ContentPanel
31652  * @constructor
31653  * Create a new NestedLayoutPanel.
31654  * 
31655  * 
31656  * @param {Roo.BorderLayout} layout The layout for this panel
31657  * @param {String/Object} config A string to set only the title or a config object
31658  */
31659 Roo.NestedLayoutPanel = function(layout, config)
31660 {
31661     // construct with only one argument..
31662     /* FIXME - implement nicer consturctors
31663     if (layout.layout) {
31664         config = layout;
31665         layout = config.layout;
31666         delete config.layout;
31667     }
31668     if (layout.xtype && !layout.getEl) {
31669         // then layout needs constructing..
31670         layout = Roo.factory(layout, Roo);
31671     }
31672     */
31673     
31674     
31675     Roo.NestedLayoutPanel.superclass.constructor.call(this, layout.getEl(), config);
31676     
31677     layout.monitorWindowResize = false; // turn off autosizing
31678     this.layout = layout;
31679     this.layout.getEl().addClass("x-layout-nested-layout");
31680     
31681     
31682     
31683     
31684 };
31685
31686 Roo.extend(Roo.NestedLayoutPanel, Roo.ContentPanel, {
31687
31688     setSize : function(width, height){
31689         if(!this.ignoreResize(width, height)){
31690             var size = this.adjustForComponents(width, height);
31691             var el = this.layout.getEl();
31692             el.setSize(size.width, size.height);
31693             var touch = el.dom.offsetWidth;
31694             this.layout.layout();
31695             // ie requires a double layout on the first pass
31696             if(Roo.isIE && !this.initialized){
31697                 this.initialized = true;
31698                 this.layout.layout();
31699             }
31700         }
31701     },
31702     
31703     // activate all subpanels if not currently active..
31704     
31705     setActiveState : function(active){
31706         this.active = active;
31707         if(!active){
31708             this.fireEvent("deactivate", this);
31709             return;
31710         }
31711         
31712         this.fireEvent("activate", this);
31713         // not sure if this should happen before or after..
31714         if (!this.layout) {
31715             return; // should not happen..
31716         }
31717         var reg = false;
31718         for (var r in this.layout.regions) {
31719             reg = this.layout.getRegion(r);
31720             if (reg.getActivePanel()) {
31721                 //reg.showPanel(reg.getActivePanel()); // force it to activate.. 
31722                 reg.setActivePanel(reg.getActivePanel());
31723                 continue;
31724             }
31725             if (!reg.panels.length) {
31726                 continue;
31727             }
31728             reg.showPanel(reg.getPanel(0));
31729         }
31730         
31731         
31732         
31733         
31734     },
31735     
31736     /**
31737      * Returns the nested BorderLayout for this panel
31738      * @return {Roo.BorderLayout} 
31739      */
31740     getLayout : function(){
31741         return this.layout;
31742     },
31743     
31744      /**
31745      * Adds a xtype elements to the layout of the nested panel
31746      * <pre><code>
31747
31748 panel.addxtype({
31749        xtype : 'ContentPanel',
31750        region: 'west',
31751        items: [ .... ]
31752    }
31753 );
31754
31755 panel.addxtype({
31756         xtype : 'NestedLayoutPanel',
31757         region: 'west',
31758         layout: {
31759            center: { },
31760            west: { }   
31761         },
31762         items : [ ... list of content panels or nested layout panels.. ]
31763    }
31764 );
31765 </code></pre>
31766      * @param {Object} cfg Xtype definition of item to add.
31767      */
31768     addxtype : function(cfg) {
31769         return this.layout.addxtype(cfg);
31770     
31771     }
31772 });
31773
31774 Roo.ScrollPanel = function(el, config, content){
31775     config = config || {};
31776     config.fitToFrame = true;
31777     Roo.ScrollPanel.superclass.constructor.call(this, el, config, content);
31778     
31779     this.el.dom.style.overflow = "hidden";
31780     var wrap = this.el.wrap({cls: "x-scroller x-layout-inactive-content"});
31781     this.el.removeClass("x-layout-inactive-content");
31782     this.el.on("mousewheel", this.onWheel, this);
31783
31784     var up = wrap.createChild({cls: "x-scroller-up", html: "&#160;"}, this.el.dom);
31785     var down = wrap.createChild({cls: "x-scroller-down", html: "&#160;"});
31786     up.unselectable(); down.unselectable();
31787     up.on("click", this.scrollUp, this);
31788     down.on("click", this.scrollDown, this);
31789     up.addClassOnOver("x-scroller-btn-over");
31790     down.addClassOnOver("x-scroller-btn-over");
31791     up.addClassOnClick("x-scroller-btn-click");
31792     down.addClassOnClick("x-scroller-btn-click");
31793     this.adjustments = [0, -(up.getHeight() + down.getHeight())];
31794
31795     this.resizeEl = this.el;
31796     this.el = wrap; this.up = up; this.down = down;
31797 };
31798
31799 Roo.extend(Roo.ScrollPanel, Roo.ContentPanel, {
31800     increment : 100,
31801     wheelIncrement : 5,
31802     scrollUp : function(){
31803         this.resizeEl.scroll("up", this.increment, {callback: this.afterScroll, scope: this});
31804     },
31805
31806     scrollDown : function(){
31807         this.resizeEl.scroll("down", this.increment, {callback: this.afterScroll, scope: this});
31808     },
31809
31810     afterScroll : function(){
31811         var el = this.resizeEl;
31812         var t = el.dom.scrollTop, h = el.dom.scrollHeight, ch = el.dom.clientHeight;
31813         this.up[t == 0 ? "addClass" : "removeClass"]("x-scroller-btn-disabled");
31814         this.down[h - t <= ch ? "addClass" : "removeClass"]("x-scroller-btn-disabled");
31815     },
31816
31817     setSize : function(){
31818         Roo.ScrollPanel.superclass.setSize.apply(this, arguments);
31819         this.afterScroll();
31820     },
31821
31822     onWheel : function(e){
31823         var d = e.getWheelDelta();
31824         this.resizeEl.dom.scrollTop -= (d*this.wheelIncrement);
31825         this.afterScroll();
31826         e.stopEvent();
31827     },
31828
31829     setContent : function(content, loadScripts){
31830         this.resizeEl.update(content, loadScripts);
31831     }
31832
31833 });
31834
31835
31836
31837
31838
31839
31840
31841
31842
31843 /**
31844  * @class Roo.TreePanel
31845  * @extends Roo.ContentPanel
31846  * @constructor
31847  * Create a new TreePanel. - defaults to fit/scoll contents.
31848  * @param {String/Object} config A string to set only the panel's title, or a config object
31849  * @cfg {Roo.tree.TreePanel} tree The tree TreePanel, with config etc.
31850  */
31851 Roo.TreePanel = function(config){
31852     var el = config.el;
31853     var tree = config.tree;
31854     delete config.tree; 
31855     delete config.el; // hopefull!
31856     
31857     // wrapper for IE7 strict & safari scroll issue
31858     
31859     var treeEl = el.createChild();
31860     config.resizeEl = treeEl;
31861     
31862     
31863     
31864     Roo.TreePanel.superclass.constructor.call(this, el, config);
31865  
31866  
31867     this.tree = new Roo.tree.TreePanel(treeEl , tree);
31868     //console.log(tree);
31869     this.on('activate', function()
31870     {
31871         if (this.tree.rendered) {
31872             return;
31873         }
31874         //console.log('render tree');
31875         this.tree.render();
31876     });
31877     // this should not be needed.. - it's actually the 'el' that resizes?
31878     // actuall it breaks the containerScroll - dragging nodes auto scroll at top
31879     
31880     //this.on('resize',  function (cp, w, h) {
31881     //        this.tree.innerCt.setWidth(w);
31882     //        this.tree.innerCt.setHeight(h);
31883     //        //this.tree.innerCt.setStyle('overflow-y', 'auto');
31884     //});
31885
31886         
31887     
31888 };
31889
31890 Roo.extend(Roo.TreePanel, Roo.ContentPanel, {   
31891     fitToFrame : true,
31892     autoScroll : true
31893 });
31894
31895
31896
31897
31898
31899
31900
31901
31902
31903
31904
31905 /*
31906  * Based on:
31907  * Ext JS Library 1.1.1
31908  * Copyright(c) 2006-2007, Ext JS, LLC.
31909  *
31910  * Originally Released Under LGPL - original licence link has changed is not relivant.
31911  *
31912  * Fork - LGPL
31913  * <script type="text/javascript">
31914  */
31915  
31916
31917 /**
31918  * @class Roo.ReaderLayout
31919  * @extends Roo.BorderLayout
31920  * This is a pre-built layout that represents a classic, 5-pane application.  It consists of a header, a primary
31921  * center region containing two nested regions (a top one for a list view and one for item preview below),
31922  * and regions on either side that can be used for navigation, application commands, informational displays, etc.
31923  * The setup and configuration work exactly the same as it does for a {@link Roo.BorderLayout} - this class simply
31924  * expedites the setup of the overall layout and regions for this common application style.
31925  * Example:
31926  <pre><code>
31927 var reader = new Roo.ReaderLayout();
31928 var CP = Roo.ContentPanel;  // shortcut for adding
31929
31930 reader.beginUpdate();
31931 reader.add("north", new CP("north", "North"));
31932 reader.add("west", new CP("west", {title: "West"}));
31933 reader.add("east", new CP("east", {title: "East"}));
31934
31935 reader.regions.listView.add(new CP("listView", "List"));
31936 reader.regions.preview.add(new CP("preview", "Preview"));
31937 reader.endUpdate();
31938 </code></pre>
31939 * @constructor
31940 * Create a new ReaderLayout
31941 * @param {Object} config Configuration options
31942 * @param {String/HTMLElement/Element} container (optional) The container this layout is bound to (defaults to
31943 * document.body if omitted)
31944 */
31945 Roo.ReaderLayout = function(config, renderTo){
31946     var c = config || {size:{}};
31947     Roo.ReaderLayout.superclass.constructor.call(this, renderTo || document.body, {
31948         north: c.north !== false ? Roo.apply({
31949             split:false,
31950             initialSize: 32,
31951             titlebar: false
31952         }, c.north) : false,
31953         west: c.west !== false ? Roo.apply({
31954             split:true,
31955             initialSize: 200,
31956             minSize: 175,
31957             maxSize: 400,
31958             titlebar: true,
31959             collapsible: true,
31960             animate: true,
31961             margins:{left:5,right:0,bottom:5,top:5},
31962             cmargins:{left:5,right:5,bottom:5,top:5}
31963         }, c.west) : false,
31964         east: c.east !== false ? Roo.apply({
31965             split:true,
31966             initialSize: 200,
31967             minSize: 175,
31968             maxSize: 400,
31969             titlebar: true,
31970             collapsible: true,
31971             animate: true,
31972             margins:{left:0,right:5,bottom:5,top:5},
31973             cmargins:{left:5,right:5,bottom:5,top:5}
31974         }, c.east) : false,
31975         center: Roo.apply({
31976             tabPosition: 'top',
31977             autoScroll:false,
31978             closeOnTab: true,
31979             titlebar:false,
31980             margins:{left:c.west!==false ? 0 : 5,right:c.east!==false ? 0 : 5,bottom:5,top:2}
31981         }, c.center)
31982     });
31983
31984     this.el.addClass('x-reader');
31985
31986     this.beginUpdate();
31987
31988     var inner = new Roo.BorderLayout(Roo.get(document.body).createChild(), {
31989         south: c.preview !== false ? Roo.apply({
31990             split:true,
31991             initialSize: 200,
31992             minSize: 100,
31993             autoScroll:true,
31994             collapsible:true,
31995             titlebar: true,
31996             cmargins:{top:5,left:0, right:0, bottom:0}
31997         }, c.preview) : false,
31998         center: Roo.apply({
31999             autoScroll:false,
32000             titlebar:false,
32001             minHeight:200
32002         }, c.listView)
32003     });
32004     this.add('center', new Roo.NestedLayoutPanel(inner,
32005             Roo.apply({title: c.mainTitle || '',tabTip:''},c.innerPanelCfg)));
32006
32007     this.endUpdate();
32008
32009     this.regions.preview = inner.getRegion('south');
32010     this.regions.listView = inner.getRegion('center');
32011 };
32012
32013 Roo.extend(Roo.ReaderLayout, Roo.BorderLayout);/*
32014  * Based on:
32015  * Ext JS Library 1.1.1
32016  * Copyright(c) 2006-2007, Ext JS, LLC.
32017  *
32018  * Originally Released Under LGPL - original licence link has changed is not relivant.
32019  *
32020  * Fork - LGPL
32021  * <script type="text/javascript">
32022  */
32023  
32024 /**
32025  * @class Roo.grid.Grid
32026  * @extends Roo.util.Observable
32027  * This class represents the primary interface of a component based grid control.
32028  * <br><br>Usage:<pre><code>
32029  var grid = new Roo.grid.Grid("my-container-id", {
32030      ds: myDataStore,
32031      cm: myColModel,
32032      selModel: mySelectionModel,
32033      autoSizeColumns: true,
32034      monitorWindowResize: false,
32035      trackMouseOver: true
32036  });
32037  // set any options
32038  grid.render();
32039  * </code></pre>
32040  * <b>Common Problems:</b><br/>
32041  * - Grid does not resize properly when going smaller: Setting overflow hidden on the container
32042  * element will correct this<br/>
32043  * - If you get el.style[camel]= NaNpx or -2px or something related, be certain you have given your container element
32044  * dimensions. The grid adapts to your container's size, if your container has no size defined then the results
32045  * are unpredictable.<br/>
32046  * - Do not render the grid into an element with display:none. Try using visibility:hidden. Otherwise there is no way for the
32047  * grid to calculate dimensions/offsets.<br/>
32048   * @constructor
32049  * @param {String/HTMLElement/Roo.Element} container The element into which this grid will be rendered -
32050  * The container MUST have some type of size defined for the grid to fill. The container will be
32051  * automatically set to position relative if it isn't already.
32052  * @param {Object} config A config object that sets properties on this grid.
32053  */
32054 Roo.grid.Grid = function(container, config){
32055         // initialize the container
32056         this.container = Roo.get(container);
32057         this.container.update("");
32058         this.container.setStyle("overflow", "hidden");
32059     this.container.addClass('x-grid-container');
32060
32061     this.id = this.container.id;
32062
32063     Roo.apply(this, config);
32064     // check and correct shorthanded configs
32065     if(this.ds){
32066         this.dataSource = this.ds;
32067         delete this.ds;
32068     }
32069     if(this.cm){
32070         this.colModel = this.cm;
32071         delete this.cm;
32072     }
32073     if(this.sm){
32074         this.selModel = this.sm;
32075         delete this.sm;
32076     }
32077
32078     if (this.selModel) {
32079         this.selModel = Roo.factory(this.selModel, Roo.grid);
32080         this.sm = this.selModel;
32081         this.sm.xmodule = this.xmodule || false;
32082     }
32083     if (typeof(this.colModel.config) == 'undefined') {
32084         this.colModel = new Roo.grid.ColumnModel(this.colModel);
32085         this.cm = this.colModel;
32086         this.cm.xmodule = this.xmodule || false;
32087     }
32088     if (this.dataSource) {
32089         this.dataSource= Roo.factory(this.dataSource, Roo.data);
32090         this.ds = this.dataSource;
32091         this.ds.xmodule = this.xmodule || false;
32092          
32093     }
32094     
32095     
32096     
32097     if(this.width){
32098         this.container.setWidth(this.width);
32099     }
32100
32101     if(this.height){
32102         this.container.setHeight(this.height);
32103     }
32104     /** @private */
32105         this.addEvents({
32106         // raw events
32107         /**
32108          * @event click
32109          * The raw click event for the entire grid.
32110          * @param {Roo.EventObject} e
32111          */
32112         "click" : true,
32113         /**
32114          * @event dblclick
32115          * The raw dblclick event for the entire grid.
32116          * @param {Roo.EventObject} e
32117          */
32118         "dblclick" : true,
32119         /**
32120          * @event contextmenu
32121          * The raw contextmenu event for the entire grid.
32122          * @param {Roo.EventObject} e
32123          */
32124         "contextmenu" : true,
32125         /**
32126          * @event mousedown
32127          * The raw mousedown event for the entire grid.
32128          * @param {Roo.EventObject} e
32129          */
32130         "mousedown" : true,
32131         /**
32132          * @event mouseup
32133          * The raw mouseup event for the entire grid.
32134          * @param {Roo.EventObject} e
32135          */
32136         "mouseup" : true,
32137         /**
32138          * @event mouseover
32139          * The raw mouseover event for the entire grid.
32140          * @param {Roo.EventObject} e
32141          */
32142         "mouseover" : true,
32143         /**
32144          * @event mouseout
32145          * The raw mouseout event for the entire grid.
32146          * @param {Roo.EventObject} e
32147          */
32148         "mouseout" : true,
32149         /**
32150          * @event keypress
32151          * The raw keypress event for the entire grid.
32152          * @param {Roo.EventObject} e
32153          */
32154         "keypress" : true,
32155         /**
32156          * @event keydown
32157          * The raw keydown event for the entire grid.
32158          * @param {Roo.EventObject} e
32159          */
32160         "keydown" : true,
32161
32162         // custom events
32163
32164         /**
32165          * @event cellclick
32166          * Fires when a cell is clicked
32167          * @param {Grid} this
32168          * @param {Number} rowIndex
32169          * @param {Number} columnIndex
32170          * @param {Roo.EventObject} e
32171          */
32172         "cellclick" : true,
32173         /**
32174          * @event celldblclick
32175          * Fires when a cell is double clicked
32176          * @param {Grid} this
32177          * @param {Number} rowIndex
32178          * @param {Number} columnIndex
32179          * @param {Roo.EventObject} e
32180          */
32181         "celldblclick" : true,
32182         /**
32183          * @event rowclick
32184          * Fires when a row is clicked
32185          * @param {Grid} this
32186          * @param {Number} rowIndex
32187          * @param {Roo.EventObject} e
32188          */
32189         "rowclick" : true,
32190         /**
32191          * @event rowdblclick
32192          * Fires when a row is double clicked
32193          * @param {Grid} this
32194          * @param {Number} rowIndex
32195          * @param {Roo.EventObject} e
32196          */
32197         "rowdblclick" : true,
32198         /**
32199          * @event headerclick
32200          * Fires when a header is clicked
32201          * @param {Grid} this
32202          * @param {Number} columnIndex
32203          * @param {Roo.EventObject} e
32204          */
32205         "headerclick" : true,
32206         /**
32207          * @event headerdblclick
32208          * Fires when a header cell is double clicked
32209          * @param {Grid} this
32210          * @param {Number} columnIndex
32211          * @param {Roo.EventObject} e
32212          */
32213         "headerdblclick" : true,
32214         /**
32215          * @event rowcontextmenu
32216          * Fires when a row is right clicked
32217          * @param {Grid} this
32218          * @param {Number} rowIndex
32219          * @param {Roo.EventObject} e
32220          */
32221         "rowcontextmenu" : true,
32222         /**
32223          * @event cellcontextmenu
32224          * Fires when a cell is right clicked
32225          * @param {Grid} this
32226          * @param {Number} rowIndex
32227          * @param {Number} cellIndex
32228          * @param {Roo.EventObject} e
32229          */
32230          "cellcontextmenu" : true,
32231         /**
32232          * @event headercontextmenu
32233          * Fires when a header is right clicked
32234          * @param {Grid} this
32235          * @param {Number} columnIndex
32236          * @param {Roo.EventObject} e
32237          */
32238         "headercontextmenu" : true,
32239         /**
32240          * @event bodyscroll
32241          * Fires when the body element is scrolled
32242          * @param {Number} scrollLeft
32243          * @param {Number} scrollTop
32244          */
32245         "bodyscroll" : true,
32246         /**
32247          * @event columnresize
32248          * Fires when the user resizes a column
32249          * @param {Number} columnIndex
32250          * @param {Number} newSize
32251          */
32252         "columnresize" : true,
32253         /**
32254          * @event columnmove
32255          * Fires when the user moves a column
32256          * @param {Number} oldIndex
32257          * @param {Number} newIndex
32258          */
32259         "columnmove" : true,
32260         /**
32261          * @event startdrag
32262          * Fires when row(s) start being dragged
32263          * @param {Grid} this
32264          * @param {Roo.GridDD} dd The drag drop object
32265          * @param {event} e The raw browser event
32266          */
32267         "startdrag" : true,
32268         /**
32269          * @event enddrag
32270          * Fires when a drag operation is complete
32271          * @param {Grid} this
32272          * @param {Roo.GridDD} dd The drag drop object
32273          * @param {event} e The raw browser event
32274          */
32275         "enddrag" : true,
32276         /**
32277          * @event dragdrop
32278          * Fires when dragged row(s) are dropped on a valid DD target
32279          * @param {Grid} this
32280          * @param {Roo.GridDD} dd The drag drop object
32281          * @param {String} targetId The target drag drop object
32282          * @param {event} e The raw browser event
32283          */
32284         "dragdrop" : true,
32285         /**
32286          * @event dragover
32287          * Fires while row(s) are being dragged. "targetId" is the id of the Yahoo.util.DD object the selected rows are being dragged over.
32288          * @param {Grid} this
32289          * @param {Roo.GridDD} dd The drag drop object
32290          * @param {String} targetId The target drag drop object
32291          * @param {event} e The raw browser event
32292          */
32293         "dragover" : true,
32294         /**
32295          * @event dragenter
32296          *  Fires when the dragged row(s) first cross another DD target while being dragged
32297          * @param {Grid} this
32298          * @param {Roo.GridDD} dd The drag drop object
32299          * @param {String} targetId The target drag drop object
32300          * @param {event} e The raw browser event
32301          */
32302         "dragenter" : true,
32303         /**
32304          * @event dragout
32305          * Fires when the dragged row(s) leave another DD target while being dragged
32306          * @param {Grid} this
32307          * @param {Roo.GridDD} dd The drag drop object
32308          * @param {String} targetId The target drag drop object
32309          * @param {event} e The raw browser event
32310          */
32311         "dragout" : true,
32312         /**
32313          * @event rowclass
32314          * Fires when a row is rendered, so you can change add a style to it.
32315          * @param {GridView} gridview   The grid view
32316          * @param {Object} rowcfg   contains record  rowIndex and rowClass - set rowClass to add a style.
32317          */
32318         'rowclass' : true,
32319
32320         /**
32321          * @event render
32322          * Fires when the grid is rendered
32323          * @param {Grid} grid
32324          */
32325         'render' : true
32326     });
32327
32328     Roo.grid.Grid.superclass.constructor.call(this);
32329 };
32330 Roo.extend(Roo.grid.Grid, Roo.util.Observable, {
32331     
32332     /**
32333      * @cfg {String} ddGroup - drag drop group.
32334      */
32335
32336     /**
32337      * @cfg {Number} minColumnWidth The minimum width a column can be resized to. Default is 25.
32338      */
32339     minColumnWidth : 25,
32340
32341     /**
32342      * @cfg {Boolean} autoSizeColumns True to automatically resize the columns to fit their content
32343      * <b>on initial render.</b> It is more efficient to explicitly size the columns
32344      * through the ColumnModel's {@link Roo.grid.ColumnModel#width} config option.  Default is false.
32345      */
32346     autoSizeColumns : false,
32347
32348     /**
32349      * @cfg {Boolean} autoSizeHeaders True to measure headers with column data when auto sizing columns. Default is true.
32350      */
32351     autoSizeHeaders : true,
32352
32353     /**
32354      * @cfg {Boolean} monitorWindowResize True to autoSize the grid when the window resizes. Default is true.
32355      */
32356     monitorWindowResize : true,
32357
32358     /**
32359      * @cfg {Boolean} maxRowsToMeasure If autoSizeColumns is on, maxRowsToMeasure can be used to limit the number of
32360      * rows measured to get a columns size. Default is 0 (all rows).
32361      */
32362     maxRowsToMeasure : 0,
32363
32364     /**
32365      * @cfg {Boolean} trackMouseOver True to highlight rows when the mouse is over. Default is true.
32366      */
32367     trackMouseOver : true,
32368
32369     /**
32370     * @cfg {Boolean} enableDrag  True to enable drag of rows. Default is false. (double check if this is needed?)
32371     */
32372     
32373     /**
32374     * @cfg {Boolean} enableDragDrop True to enable drag and drop of rows. Default is false.
32375     */
32376     enableDragDrop : false,
32377     
32378     /**
32379     * @cfg {Boolean} enableColumnMove True to enable drag and drop reorder of columns. Default is true.
32380     */
32381     enableColumnMove : true,
32382     
32383     /**
32384     * @cfg {Boolean} enableColumnHide True to enable hiding of columns with the header context menu. Default is true.
32385     */
32386     enableColumnHide : true,
32387     
32388     /**
32389     * @cfg {Boolean} enableRowHeightSync True to manually sync row heights across locked and not locked rows. Default is false.
32390     */
32391     enableRowHeightSync : false,
32392     
32393     /**
32394     * @cfg {Boolean} stripeRows True to stripe the rows.  Default is true.
32395     */
32396     stripeRows : true,
32397     
32398     /**
32399     * @cfg {Boolean} autoHeight True to fit the height of the grid container to the height of the data. Default is false.
32400     */
32401     autoHeight : false,
32402
32403     /**
32404      * @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.
32405      */
32406     autoExpandColumn : false,
32407
32408     /**
32409     * @cfg {Number} autoExpandMin The minimum width the autoExpandColumn can have (if enabled).
32410     * Default is 50.
32411     */
32412     autoExpandMin : 50,
32413
32414     /**
32415     * @cfg {Number} autoExpandMax The maximum width the autoExpandColumn can have (if enabled). Default is 1000.
32416     */
32417     autoExpandMax : 1000,
32418
32419     /**
32420     * @cfg {Object} view The {@link Roo.grid.GridView} used by the grid. This can be set before a call to render().
32421     */
32422     view : null,
32423
32424     /**
32425     * @cfg {Object} loadMask An {@link Roo.LoadMask} config or true to mask the grid while loading. Default is false.
32426     */
32427     loadMask : false,
32428     /**
32429     * @cfg {Roo.dd.DropTarget} dropTarget An {@link Roo.dd.DropTarget} config
32430     */
32431     dropTarget: false,
32432     
32433    
32434     
32435     // private
32436     rendered : false,
32437
32438     /**
32439     * @cfg {Boolean} autoWidth True to set the grid's width to the default total width of the grid's columns instead
32440     * of a fixed width. Default is false.
32441     */
32442     /**
32443     * @cfg {Number} maxHeight Sets the maximum height of the grid - ignored if autoHeight is not on.
32444     */
32445     /**
32446      * Called once after all setup has been completed and the grid is ready to be rendered.
32447      * @return {Roo.grid.Grid} this
32448      */
32449     render : function()
32450     {
32451         var c = this.container;
32452         // try to detect autoHeight/width mode
32453         if((!c.dom.offsetHeight || c.dom.offsetHeight < 20) || c.getStyle("height") == "auto"){
32454             this.autoHeight = true;
32455         }
32456         var view = this.getView();
32457         view.init(this);
32458
32459         c.on("click", this.onClick, this);
32460         c.on("dblclick", this.onDblClick, this);
32461         c.on("contextmenu", this.onContextMenu, this);
32462         c.on("keydown", this.onKeyDown, this);
32463         if (Roo.isTouch) {
32464             c.on("touchstart", this.onTouchStart, this);
32465         }
32466
32467         this.relayEvents(c, ["mousedown","mouseup","mouseover","mouseout","keypress"]);
32468
32469         this.getSelectionModel().init(this);
32470
32471         view.render();
32472
32473         if(this.loadMask){
32474             this.loadMask = new Roo.LoadMask(this.container,
32475                     Roo.apply({store:this.dataSource}, this.loadMask));
32476         }
32477         
32478         
32479         if (this.toolbar && this.toolbar.xtype) {
32480             this.toolbar.container = this.getView().getHeaderPanel(true);
32481             this.toolbar = new Roo.Toolbar(this.toolbar);
32482         }
32483         if (this.footer && this.footer.xtype) {
32484             this.footer.dataSource = this.getDataSource();
32485             this.footer.container = this.getView().getFooterPanel(true);
32486             this.footer = Roo.factory(this.footer, Roo);
32487         }
32488         if (this.dropTarget && this.dropTarget.xtype) {
32489             delete this.dropTarget.xtype;
32490             this.dropTarget =  new Roo.dd.DropTarget(this.getView().mainBody, this.dropTarget);
32491         }
32492         
32493         
32494         this.rendered = true;
32495         this.fireEvent('render', this);
32496         return this;
32497     },
32498
32499         /**
32500          * Reconfigures the grid to use a different Store and Column Model.
32501          * The View will be bound to the new objects and refreshed.
32502          * @param {Roo.data.Store} dataSource The new {@link Roo.data.Store} object
32503          * @param {Roo.grid.ColumnModel} The new {@link Roo.grid.ColumnModel} object
32504          */
32505     reconfigure : function(dataSource, colModel){
32506         if(this.loadMask){
32507             this.loadMask.destroy();
32508             this.loadMask = new Roo.LoadMask(this.container,
32509                     Roo.apply({store:dataSource}, this.loadMask));
32510         }
32511         this.view.bind(dataSource, colModel);
32512         this.dataSource = dataSource;
32513         this.colModel = colModel;
32514         this.view.refresh(true);
32515     },
32516
32517     // private
32518     onKeyDown : function(e){
32519         this.fireEvent("keydown", e);
32520     },
32521
32522     /**
32523      * Destroy this grid.
32524      * @param {Boolean} removeEl True to remove the element
32525      */
32526     destroy : function(removeEl, keepListeners){
32527         if(this.loadMask){
32528             this.loadMask.destroy();
32529         }
32530         var c = this.container;
32531         c.removeAllListeners();
32532         this.view.destroy();
32533         this.colModel.purgeListeners();
32534         if(!keepListeners){
32535             this.purgeListeners();
32536         }
32537         c.update("");
32538         if(removeEl === true){
32539             c.remove();
32540         }
32541     },
32542
32543     // private
32544     processEvent : function(name, e){
32545         // does this fire select???
32546         //Roo.log('grid:processEvent '  + name);
32547         
32548         if (name != 'touchstart' ) {
32549             this.fireEvent(name, e);    
32550         }
32551         
32552         var t = e.getTarget();
32553         var v = this.view;
32554         var header = v.findHeaderIndex(t);
32555         if(header !== false){
32556             var ename = name == 'touchstart' ? 'click' : name;
32557              
32558             this.fireEvent("header" + ename, this, header, e);
32559         }else{
32560             var row = v.findRowIndex(t);
32561             var cell = v.findCellIndex(t);
32562             if (name == 'touchstart') {
32563                 // first touch is always a click.
32564                 // hopefull this happens after selection is updated.?
32565                 name = false;
32566                 
32567                 if (typeof(this.selModel.getSelectedCell) != 'undefined') {
32568                     var cs = this.selModel.getSelectedCell();
32569                     if (row == cs[0] && cell == cs[1]){
32570                         name = 'dblclick';
32571                     }
32572                 }
32573                 if (typeof(this.selModel.getSelections) != 'undefined') {
32574                     var cs = this.selModel.getSelections();
32575                     var ds = this.dataSource;
32576                     if (cs.length == 1 && ds.getAt(row) == cs[0]){
32577                         name = 'dblclick';
32578                     }
32579                 }
32580                 if (!name) {
32581                     return;
32582                 }
32583             }
32584             
32585             
32586             if(row !== false){
32587                 this.fireEvent("row" + name, this, row, e);
32588                 if(cell !== false){
32589                     this.fireEvent("cell" + name, this, row, cell, e);
32590                 }
32591             }
32592         }
32593     },
32594
32595     // private
32596     onClick : function(e){
32597         this.processEvent("click", e);
32598     },
32599    // private
32600     onTouchStart : function(e){
32601         this.processEvent("touchstart", e);
32602     },
32603
32604     // private
32605     onContextMenu : function(e, t){
32606         this.processEvent("contextmenu", e);
32607     },
32608
32609     // private
32610     onDblClick : function(e){
32611         this.processEvent("dblclick", e);
32612     },
32613
32614     // private
32615     walkCells : function(row, col, step, fn, scope){
32616         var cm = this.colModel, clen = cm.getColumnCount();
32617         var ds = this.dataSource, rlen = ds.getCount(), first = true;
32618         if(step < 0){
32619             if(col < 0){
32620                 row--;
32621                 first = false;
32622             }
32623             while(row >= 0){
32624                 if(!first){
32625                     col = clen-1;
32626                 }
32627                 first = false;
32628                 while(col >= 0){
32629                     if(fn.call(scope || this, row, col, cm) === true){
32630                         return [row, col];
32631                     }
32632                     col--;
32633                 }
32634                 row--;
32635             }
32636         } else {
32637             if(col >= clen){
32638                 row++;
32639                 first = false;
32640             }
32641             while(row < rlen){
32642                 if(!first){
32643                     col = 0;
32644                 }
32645                 first = false;
32646                 while(col < clen){
32647                     if(fn.call(scope || this, row, col, cm) === true){
32648                         return [row, col];
32649                     }
32650                     col++;
32651                 }
32652                 row++;
32653             }
32654         }
32655         return null;
32656     },
32657
32658     // private
32659     getSelections : function(){
32660         return this.selModel.getSelections();
32661     },
32662
32663     /**
32664      * Causes the grid to manually recalculate its dimensions. Generally this is done automatically,
32665      * but if manual update is required this method will initiate it.
32666      */
32667     autoSize : function(){
32668         if(this.rendered){
32669             this.view.layout();
32670             if(this.view.adjustForScroll){
32671                 this.view.adjustForScroll();
32672             }
32673         }
32674     },
32675
32676     /**
32677      * Returns the grid's underlying element.
32678      * @return {Element} The element
32679      */
32680     getGridEl : function(){
32681         return this.container;
32682     },
32683
32684     // private for compatibility, overridden by editor grid
32685     stopEditing : function(){},
32686
32687     /**
32688      * Returns the grid's SelectionModel.
32689      * @return {SelectionModel}
32690      */
32691     getSelectionModel : function(){
32692         if(!this.selModel){
32693             this.selModel = new Roo.grid.RowSelectionModel();
32694         }
32695         return this.selModel;
32696     },
32697
32698     /**
32699      * Returns the grid's DataSource.
32700      * @return {DataSource}
32701      */
32702     getDataSource : function(){
32703         return this.dataSource;
32704     },
32705
32706     /**
32707      * Returns the grid's ColumnModel.
32708      * @return {ColumnModel}
32709      */
32710     getColumnModel : function(){
32711         return this.colModel;
32712     },
32713
32714     /**
32715      * Returns the grid's GridView object.
32716      * @return {GridView}
32717      */
32718     getView : function(){
32719         if(!this.view){
32720             this.view = new Roo.grid.GridView(this.viewConfig);
32721         }
32722         return this.view;
32723     },
32724     /**
32725      * Called to get grid's drag proxy text, by default returns this.ddText.
32726      * @return {String}
32727      */
32728     getDragDropText : function(){
32729         var count = this.selModel.getCount();
32730         return String.format(this.ddText, count, count == 1 ? '' : 's');
32731     }
32732 });
32733 /**
32734  * Configures the text is the drag proxy (defaults to "%0 selected row(s)").
32735  * %0 is replaced with the number of selected rows.
32736  * @type String
32737  */
32738 Roo.grid.Grid.prototype.ddText = "{0} selected row{1}";/*
32739  * Based on:
32740  * Ext JS Library 1.1.1
32741  * Copyright(c) 2006-2007, Ext JS, LLC.
32742  *
32743  * Originally Released Under LGPL - original licence link has changed is not relivant.
32744  *
32745  * Fork - LGPL
32746  * <script type="text/javascript">
32747  */
32748  
32749 Roo.grid.AbstractGridView = function(){
32750         this.grid = null;
32751         
32752         this.events = {
32753             "beforerowremoved" : true,
32754             "beforerowsinserted" : true,
32755             "beforerefresh" : true,
32756             "rowremoved" : true,
32757             "rowsinserted" : true,
32758             "rowupdated" : true,
32759             "refresh" : true
32760         };
32761     Roo.grid.AbstractGridView.superclass.constructor.call(this);
32762 };
32763
32764 Roo.extend(Roo.grid.AbstractGridView, Roo.util.Observable, {
32765     rowClass : "x-grid-row",
32766     cellClass : "x-grid-cell",
32767     tdClass : "x-grid-td",
32768     hdClass : "x-grid-hd",
32769     splitClass : "x-grid-hd-split",
32770     
32771     init: function(grid){
32772         this.grid = grid;
32773                 var cid = this.grid.getGridEl().id;
32774         this.colSelector = "#" + cid + " ." + this.cellClass + "-";
32775         this.tdSelector = "#" + cid + " ." + this.tdClass + "-";
32776         this.hdSelector = "#" + cid + " ." + this.hdClass + "-";
32777         this.splitSelector = "#" + cid + " ." + this.splitClass + "-";
32778         },
32779         
32780     getColumnRenderers : function(){
32781         var renderers = [];
32782         var cm = this.grid.colModel;
32783         var colCount = cm.getColumnCount();
32784         for(var i = 0; i < colCount; i++){
32785             renderers[i] = cm.getRenderer(i);
32786         }
32787         return renderers;
32788     },
32789     
32790     getColumnIds : function(){
32791         var ids = [];
32792         var cm = this.grid.colModel;
32793         var colCount = cm.getColumnCount();
32794         for(var i = 0; i < colCount; i++){
32795             ids[i] = cm.getColumnId(i);
32796         }
32797         return ids;
32798     },
32799     
32800     getDataIndexes : function(){
32801         if(!this.indexMap){
32802             this.indexMap = this.buildIndexMap();
32803         }
32804         return this.indexMap.colToData;
32805     },
32806     
32807     getColumnIndexByDataIndex : function(dataIndex){
32808         if(!this.indexMap){
32809             this.indexMap = this.buildIndexMap();
32810         }
32811         return this.indexMap.dataToCol[dataIndex];
32812     },
32813     
32814     /**
32815      * Set a css style for a column dynamically. 
32816      * @param {Number} colIndex The index of the column
32817      * @param {String} name The css property name
32818      * @param {String} value The css value
32819      */
32820     setCSSStyle : function(colIndex, name, value){
32821         var selector = "#" + this.grid.id + " .x-grid-col-" + colIndex;
32822         Roo.util.CSS.updateRule(selector, name, value);
32823     },
32824     
32825     generateRules : function(cm){
32826         var ruleBuf = [], rulesId = this.grid.id + '-cssrules';
32827         Roo.util.CSS.removeStyleSheet(rulesId);
32828         for(var i = 0, len = cm.getColumnCount(); i < len; i++){
32829             var cid = cm.getColumnId(i);
32830             ruleBuf.push(this.colSelector, cid, " {\n", cm.config[i].css, "}\n",
32831                          this.tdSelector, cid, " {\n}\n",
32832                          this.hdSelector, cid, " {\n}\n",
32833                          this.splitSelector, cid, " {\n}\n");
32834         }
32835         return Roo.util.CSS.createStyleSheet(ruleBuf.join(""), rulesId);
32836     }
32837 });/*
32838  * Based on:
32839  * Ext JS Library 1.1.1
32840  * Copyright(c) 2006-2007, Ext JS, LLC.
32841  *
32842  * Originally Released Under LGPL - original licence link has changed is not relivant.
32843  *
32844  * Fork - LGPL
32845  * <script type="text/javascript">
32846  */
32847
32848 // private
32849 // This is a support class used internally by the Grid components
32850 Roo.grid.HeaderDragZone = function(grid, hd, hd2){
32851     this.grid = grid;
32852     this.view = grid.getView();
32853     this.ddGroup = "gridHeader" + this.grid.getGridEl().id;
32854     Roo.grid.HeaderDragZone.superclass.constructor.call(this, hd);
32855     if(hd2){
32856         this.setHandleElId(Roo.id(hd));
32857         this.setOuterHandleElId(Roo.id(hd2));
32858     }
32859     this.scroll = false;
32860 };
32861 Roo.extend(Roo.grid.HeaderDragZone, Roo.dd.DragZone, {
32862     maxDragWidth: 120,
32863     getDragData : function(e){
32864         var t = Roo.lib.Event.getTarget(e);
32865         var h = this.view.findHeaderCell(t);
32866         if(h){
32867             return {ddel: h.firstChild, header:h};
32868         }
32869         return false;
32870     },
32871
32872     onInitDrag : function(e){
32873         this.view.headersDisabled = true;
32874         var clone = this.dragData.ddel.cloneNode(true);
32875         clone.id = Roo.id();
32876         clone.style.width = Math.min(this.dragData.header.offsetWidth,this.maxDragWidth) + "px";
32877         this.proxy.update(clone);
32878         return true;
32879     },
32880
32881     afterValidDrop : function(){
32882         var v = this.view;
32883         setTimeout(function(){
32884             v.headersDisabled = false;
32885         }, 50);
32886     },
32887
32888     afterInvalidDrop : function(){
32889         var v = this.view;
32890         setTimeout(function(){
32891             v.headersDisabled = false;
32892         }, 50);
32893     }
32894 });
32895 /*
32896  * Based on:
32897  * Ext JS Library 1.1.1
32898  * Copyright(c) 2006-2007, Ext JS, LLC.
32899  *
32900  * Originally Released Under LGPL - original licence link has changed is not relivant.
32901  *
32902  * Fork - LGPL
32903  * <script type="text/javascript">
32904  */
32905 // private
32906 // This is a support class used internally by the Grid components
32907 Roo.grid.HeaderDropZone = function(grid, hd, hd2){
32908     this.grid = grid;
32909     this.view = grid.getView();
32910     // split the proxies so they don't interfere with mouse events
32911     this.proxyTop = Roo.DomHelper.append(document.body, {
32912         cls:"col-move-top", html:"&#160;"
32913     }, true);
32914     this.proxyBottom = Roo.DomHelper.append(document.body, {
32915         cls:"col-move-bottom", html:"&#160;"
32916     }, true);
32917     this.proxyTop.hide = this.proxyBottom.hide = function(){
32918         this.setLeftTop(-100,-100);
32919         this.setStyle("visibility", "hidden");
32920     };
32921     this.ddGroup = "gridHeader" + this.grid.getGridEl().id;
32922     // temporarily disabled
32923     //Roo.dd.ScrollManager.register(this.view.scroller.dom);
32924     Roo.grid.HeaderDropZone.superclass.constructor.call(this, grid.getGridEl().dom);
32925 };
32926 Roo.extend(Roo.grid.HeaderDropZone, Roo.dd.DropZone, {
32927     proxyOffsets : [-4, -9],
32928     fly: Roo.Element.fly,
32929
32930     getTargetFromEvent : function(e){
32931         var t = Roo.lib.Event.getTarget(e);
32932         var cindex = this.view.findCellIndex(t);
32933         if(cindex !== false){
32934             return this.view.getHeaderCell(cindex);
32935         }
32936         return null;
32937     },
32938
32939     nextVisible : function(h){
32940         var v = this.view, cm = this.grid.colModel;
32941         h = h.nextSibling;
32942         while(h){
32943             if(!cm.isHidden(v.getCellIndex(h))){
32944                 return h;
32945             }
32946             h = h.nextSibling;
32947         }
32948         return null;
32949     },
32950
32951     prevVisible : function(h){
32952         var v = this.view, cm = this.grid.colModel;
32953         h = h.prevSibling;
32954         while(h){
32955             if(!cm.isHidden(v.getCellIndex(h))){
32956                 return h;
32957             }
32958             h = h.prevSibling;
32959         }
32960         return null;
32961     },
32962
32963     positionIndicator : function(h, n, e){
32964         var x = Roo.lib.Event.getPageX(e);
32965         var r = Roo.lib.Dom.getRegion(n.firstChild);
32966         var px, pt, py = r.top + this.proxyOffsets[1];
32967         if((r.right - x) <= (r.right-r.left)/2){
32968             px = r.right+this.view.borderWidth;
32969             pt = "after";
32970         }else{
32971             px = r.left;
32972             pt = "before";
32973         }
32974         var oldIndex = this.view.getCellIndex(h);
32975         var newIndex = this.view.getCellIndex(n);
32976
32977         if(this.grid.colModel.isFixed(newIndex)){
32978             return false;
32979         }
32980
32981         var locked = this.grid.colModel.isLocked(newIndex);
32982
32983         if(pt == "after"){
32984             newIndex++;
32985         }
32986         if(oldIndex < newIndex){
32987             newIndex--;
32988         }
32989         if(oldIndex == newIndex && (locked == this.grid.colModel.isLocked(oldIndex))){
32990             return false;
32991         }
32992         px +=  this.proxyOffsets[0];
32993         this.proxyTop.setLeftTop(px, py);
32994         this.proxyTop.show();
32995         if(!this.bottomOffset){
32996             this.bottomOffset = this.view.mainHd.getHeight();
32997         }
32998         this.proxyBottom.setLeftTop(px, py+this.proxyTop.dom.offsetHeight+this.bottomOffset);
32999         this.proxyBottom.show();
33000         return pt;
33001     },
33002
33003     onNodeEnter : function(n, dd, e, data){
33004         if(data.header != n){
33005             this.positionIndicator(data.header, n, e);
33006         }
33007     },
33008
33009     onNodeOver : function(n, dd, e, data){
33010         var result = false;
33011         if(data.header != n){
33012             result = this.positionIndicator(data.header, n, e);
33013         }
33014         if(!result){
33015             this.proxyTop.hide();
33016             this.proxyBottom.hide();
33017         }
33018         return result ? this.dropAllowed : this.dropNotAllowed;
33019     },
33020
33021     onNodeOut : function(n, dd, e, data){
33022         this.proxyTop.hide();
33023         this.proxyBottom.hide();
33024     },
33025
33026     onNodeDrop : function(n, dd, e, data){
33027         var h = data.header;
33028         if(h != n){
33029             var cm = this.grid.colModel;
33030             var x = Roo.lib.Event.getPageX(e);
33031             var r = Roo.lib.Dom.getRegion(n.firstChild);
33032             var pt = (r.right - x) <= ((r.right-r.left)/2) ? "after" : "before";
33033             var oldIndex = this.view.getCellIndex(h);
33034             var newIndex = this.view.getCellIndex(n);
33035             var locked = cm.isLocked(newIndex);
33036             if(pt == "after"){
33037                 newIndex++;
33038             }
33039             if(oldIndex < newIndex){
33040                 newIndex--;
33041             }
33042             if(oldIndex == newIndex && (locked == cm.isLocked(oldIndex))){
33043                 return false;
33044             }
33045             cm.setLocked(oldIndex, locked, true);
33046             cm.moveColumn(oldIndex, newIndex);
33047             this.grid.fireEvent("columnmove", oldIndex, newIndex);
33048             return true;
33049         }
33050         return false;
33051     }
33052 });
33053 /*
33054  * Based on:
33055  * Ext JS Library 1.1.1
33056  * Copyright(c) 2006-2007, Ext JS, LLC.
33057  *
33058  * Originally Released Under LGPL - original licence link has changed is not relivant.
33059  *
33060  * Fork - LGPL
33061  * <script type="text/javascript">
33062  */
33063   
33064 /**
33065  * @class Roo.grid.GridView
33066  * @extends Roo.util.Observable
33067  *
33068  * @constructor
33069  * @param {Object} config
33070  */
33071 Roo.grid.GridView = function(config){
33072     Roo.grid.GridView.superclass.constructor.call(this);
33073     this.el = null;
33074
33075     Roo.apply(this, config);
33076 };
33077
33078 Roo.extend(Roo.grid.GridView, Roo.grid.AbstractGridView, {
33079
33080     unselectable :  'unselectable="on"',
33081     unselectableCls :  'x-unselectable',
33082     
33083     
33084     rowClass : "x-grid-row",
33085
33086     cellClass : "x-grid-col",
33087
33088     tdClass : "x-grid-td",
33089
33090     hdClass : "x-grid-hd",
33091
33092     splitClass : "x-grid-split",
33093
33094     sortClasses : ["sort-asc", "sort-desc"],
33095
33096     enableMoveAnim : false,
33097
33098     hlColor: "C3DAF9",
33099
33100     dh : Roo.DomHelper,
33101
33102     fly : Roo.Element.fly,
33103
33104     css : Roo.util.CSS,
33105
33106     borderWidth: 1,
33107
33108     splitOffset: 3,
33109
33110     scrollIncrement : 22,
33111
33112     cellRE: /(?:.*?)x-grid-(?:hd|cell|csplit)-(?:[\d]+)-([\d]+)(?:.*?)/,
33113
33114     findRE: /\s?(?:x-grid-hd|x-grid-col|x-grid-csplit)\s/,
33115
33116     bind : function(ds, cm){
33117         if(this.ds){
33118             this.ds.un("load", this.onLoad, this);
33119             this.ds.un("datachanged", this.onDataChange, this);
33120             this.ds.un("add", this.onAdd, this);
33121             this.ds.un("remove", this.onRemove, this);
33122             this.ds.un("update", this.onUpdate, this);
33123             this.ds.un("clear", this.onClear, this);
33124         }
33125         if(ds){
33126             ds.on("load", this.onLoad, this);
33127             ds.on("datachanged", this.onDataChange, this);
33128             ds.on("add", this.onAdd, this);
33129             ds.on("remove", this.onRemove, this);
33130             ds.on("update", this.onUpdate, this);
33131             ds.on("clear", this.onClear, this);
33132         }
33133         this.ds = ds;
33134
33135         if(this.cm){
33136             this.cm.un("widthchange", this.onColWidthChange, this);
33137             this.cm.un("headerchange", this.onHeaderChange, this);
33138             this.cm.un("hiddenchange", this.onHiddenChange, this);
33139             this.cm.un("columnmoved", this.onColumnMove, this);
33140             this.cm.un("columnlockchange", this.onColumnLock, this);
33141         }
33142         if(cm){
33143             this.generateRules(cm);
33144             cm.on("widthchange", this.onColWidthChange, this);
33145             cm.on("headerchange", this.onHeaderChange, this);
33146             cm.on("hiddenchange", this.onHiddenChange, this);
33147             cm.on("columnmoved", this.onColumnMove, this);
33148             cm.on("columnlockchange", this.onColumnLock, this);
33149         }
33150         this.cm = cm;
33151     },
33152
33153     init: function(grid){
33154         Roo.grid.GridView.superclass.init.call(this, grid);
33155
33156         this.bind(grid.dataSource, grid.colModel);
33157
33158         grid.on("headerclick", this.handleHeaderClick, this);
33159
33160         if(grid.trackMouseOver){
33161             grid.on("mouseover", this.onRowOver, this);
33162             grid.on("mouseout", this.onRowOut, this);
33163         }
33164         grid.cancelTextSelection = function(){};
33165         this.gridId = grid.id;
33166
33167         var tpls = this.templates || {};
33168
33169         if(!tpls.master){
33170             tpls.master = new Roo.Template(
33171                '<div class="x-grid" hidefocus="true">',
33172                 '<a href="#" class="x-grid-focus" tabIndex="-1"></a>',
33173                   '<div class="x-grid-topbar"></div>',
33174                   '<div class="x-grid-scroller"><div></div></div>',
33175                   '<div class="x-grid-locked">',
33176                       '<div class="x-grid-header">{lockedHeader}</div>',
33177                       '<div class="x-grid-body">{lockedBody}</div>',
33178                   "</div>",
33179                   '<div class="x-grid-viewport">',
33180                       '<div class="x-grid-header">{header}</div>',
33181                       '<div class="x-grid-body">{body}</div>',
33182                   "</div>",
33183                   '<div class="x-grid-bottombar"></div>',
33184                  
33185                   '<div class="x-grid-resize-proxy">&#160;</div>',
33186                "</div>"
33187             );
33188             tpls.master.disableformats = true;
33189         }
33190
33191         if(!tpls.header){
33192             tpls.header = new Roo.Template(
33193                '<table border="0" cellspacing="0" cellpadding="0">',
33194                '<tbody><tr class="x-grid-hd-row">{cells}</tr></tbody>',
33195                "</table>{splits}"
33196             );
33197             tpls.header.disableformats = true;
33198         }
33199         tpls.header.compile();
33200
33201         if(!tpls.hcell){
33202             tpls.hcell = new Roo.Template(
33203                 '<td class="x-grid-hd x-grid-td-{id} {cellId}"><div title="{title}" class="x-grid-hd-inner x-grid-hd-{id}">',
33204                 '<div class="x-grid-hd-text ' + this.unselectableCls +  '" ' + this.unselectable +'>{value}<img class="x-grid-sort-icon" src="', Roo.BLANK_IMAGE_URL, '" /></div>',
33205                 "</div></td>"
33206              );
33207              tpls.hcell.disableFormats = true;
33208         }
33209         tpls.hcell.compile();
33210
33211         if(!tpls.hsplit){
33212             tpls.hsplit = new Roo.Template('<div class="x-grid-split {splitId} x-grid-split-{id}" style="{style} ' +
33213                                             this.unselectableCls +  '" ' + this.unselectable +'>&#160;</div>');
33214             tpls.hsplit.disableFormats = true;
33215         }
33216         tpls.hsplit.compile();
33217
33218         if(!tpls.body){
33219             tpls.body = new Roo.Template(
33220                '<table border="0" cellspacing="0" cellpadding="0">',
33221                "<tbody>{rows}</tbody>",
33222                "</table>"
33223             );
33224             tpls.body.disableFormats = true;
33225         }
33226         tpls.body.compile();
33227
33228         if(!tpls.row){
33229             tpls.row = new Roo.Template('<tr class="x-grid-row {alt}">{cells}</tr>');
33230             tpls.row.disableFormats = true;
33231         }
33232         tpls.row.compile();
33233
33234         if(!tpls.cell){
33235             tpls.cell = new Roo.Template(
33236                 '<td class="x-grid-col x-grid-td-{id} {cellId} {css}" tabIndex="0">',
33237                 '<div class="x-grid-col-{id} x-grid-cell-inner"><div class="x-grid-cell-text ' +
33238                     this.unselectableCls +  '" ' + this.unselectable +'" {attr}>{value}</div></div>',
33239                 "</td>"
33240             );
33241             tpls.cell.disableFormats = true;
33242         }
33243         tpls.cell.compile();
33244
33245         this.templates = tpls;
33246     },
33247
33248     // remap these for backwards compat
33249     onColWidthChange : function(){
33250         this.updateColumns.apply(this, arguments);
33251     },
33252     onHeaderChange : function(){
33253         this.updateHeaders.apply(this, arguments);
33254     }, 
33255     onHiddenChange : function(){
33256         this.handleHiddenChange.apply(this, arguments);
33257     },
33258     onColumnMove : function(){
33259         this.handleColumnMove.apply(this, arguments);
33260     },
33261     onColumnLock : function(){
33262         this.handleLockChange.apply(this, arguments);
33263     },
33264
33265     onDataChange : function(){
33266         this.refresh();
33267         this.updateHeaderSortState();
33268     },
33269
33270     onClear : function(){
33271         this.refresh();
33272     },
33273
33274     onUpdate : function(ds, record){
33275         this.refreshRow(record);
33276     },
33277
33278     refreshRow : function(record){
33279         var ds = this.ds, index;
33280         if(typeof record == 'number'){
33281             index = record;
33282             record = ds.getAt(index);
33283         }else{
33284             index = ds.indexOf(record);
33285         }
33286         this.insertRows(ds, index, index, true);
33287         this.onRemove(ds, record, index+1, true);
33288         this.syncRowHeights(index, index);
33289         this.layout();
33290         this.fireEvent("rowupdated", this, index, record);
33291     },
33292
33293     onAdd : function(ds, records, index){
33294         this.insertRows(ds, index, index + (records.length-1));
33295     },
33296
33297     onRemove : function(ds, record, index, isUpdate){
33298         if(isUpdate !== true){
33299             this.fireEvent("beforerowremoved", this, index, record);
33300         }
33301         var bt = this.getBodyTable(), lt = this.getLockedTable();
33302         if(bt.rows[index]){
33303             bt.firstChild.removeChild(bt.rows[index]);
33304         }
33305         if(lt.rows[index]){
33306             lt.firstChild.removeChild(lt.rows[index]);
33307         }
33308         if(isUpdate !== true){
33309             this.stripeRows(index);
33310             this.syncRowHeights(index, index);
33311             this.layout();
33312             this.fireEvent("rowremoved", this, index, record);
33313         }
33314     },
33315
33316     onLoad : function(){
33317         this.scrollToTop();
33318     },
33319
33320     /**
33321      * Scrolls the grid to the top
33322      */
33323     scrollToTop : function(){
33324         if(this.scroller){
33325             this.scroller.dom.scrollTop = 0;
33326             this.syncScroll();
33327         }
33328     },
33329
33330     /**
33331      * Gets a panel in the header of the grid that can be used for toolbars etc.
33332      * After modifying the contents of this panel a call to grid.autoSize() may be
33333      * required to register any changes in size.
33334      * @param {Boolean} doShow By default the header is hidden. Pass true to show the panel
33335      * @return Roo.Element
33336      */
33337     getHeaderPanel : function(doShow){
33338         if(doShow){
33339             this.headerPanel.show();
33340         }
33341         return this.headerPanel;
33342     },
33343
33344     /**
33345      * Gets a panel in the footer of the grid that can be used for toolbars etc.
33346      * After modifying the contents of this panel a call to grid.autoSize() may be
33347      * required to register any changes in size.
33348      * @param {Boolean} doShow By default the footer is hidden. Pass true to show the panel
33349      * @return Roo.Element
33350      */
33351     getFooterPanel : function(doShow){
33352         if(doShow){
33353             this.footerPanel.show();
33354         }
33355         return this.footerPanel;
33356     },
33357
33358     initElements : function(){
33359         var E = Roo.Element;
33360         var el = this.grid.getGridEl().dom.firstChild;
33361         var cs = el.childNodes;
33362
33363         this.el = new E(el);
33364         
33365          this.focusEl = new E(el.firstChild);
33366         this.focusEl.swallowEvent("click", true);
33367         
33368         this.headerPanel = new E(cs[1]);
33369         this.headerPanel.enableDisplayMode("block");
33370
33371         this.scroller = new E(cs[2]);
33372         this.scrollSizer = new E(this.scroller.dom.firstChild);
33373
33374         this.lockedWrap = new E(cs[3]);
33375         this.lockedHd = new E(this.lockedWrap.dom.firstChild);
33376         this.lockedBody = new E(this.lockedWrap.dom.childNodes[1]);
33377
33378         this.mainWrap = new E(cs[4]);
33379         this.mainHd = new E(this.mainWrap.dom.firstChild);
33380         this.mainBody = new E(this.mainWrap.dom.childNodes[1]);
33381
33382         this.footerPanel = new E(cs[5]);
33383         this.footerPanel.enableDisplayMode("block");
33384
33385         this.resizeProxy = new E(cs[6]);
33386
33387         this.headerSelector = String.format(
33388            '#{0} td.x-grid-hd, #{1} td.x-grid-hd',
33389            this.lockedHd.id, this.mainHd.id
33390         );
33391
33392         this.splitterSelector = String.format(
33393            '#{0} div.x-grid-split, #{1} div.x-grid-split',
33394            this.idToCssName(this.lockedHd.id), this.idToCssName(this.mainHd.id)
33395         );
33396     },
33397     idToCssName : function(s)
33398     {
33399         return s.replace(/[^a-z0-9]+/ig, '-');
33400     },
33401
33402     getHeaderCell : function(index){
33403         return Roo.DomQuery.select(this.headerSelector)[index];
33404     },
33405
33406     getHeaderCellMeasure : function(index){
33407         return this.getHeaderCell(index).firstChild;
33408     },
33409
33410     getHeaderCellText : function(index){
33411         return this.getHeaderCell(index).firstChild.firstChild;
33412     },
33413
33414     getLockedTable : function(){
33415         return this.lockedBody.dom.firstChild;
33416     },
33417
33418     getBodyTable : function(){
33419         return this.mainBody.dom.firstChild;
33420     },
33421
33422     getLockedRow : function(index){
33423         return this.getLockedTable().rows[index];
33424     },
33425
33426     getRow : function(index){
33427         return this.getBodyTable().rows[index];
33428     },
33429
33430     getRowComposite : function(index){
33431         if(!this.rowEl){
33432             this.rowEl = new Roo.CompositeElementLite();
33433         }
33434         var els = [], lrow, mrow;
33435         if(lrow = this.getLockedRow(index)){
33436             els.push(lrow);
33437         }
33438         if(mrow = this.getRow(index)){
33439             els.push(mrow);
33440         }
33441         this.rowEl.elements = els;
33442         return this.rowEl;
33443     },
33444     /**
33445      * Gets the 'td' of the cell
33446      * 
33447      * @param {Integer} rowIndex row to select
33448      * @param {Integer} colIndex column to select
33449      * 
33450      * @return {Object} 
33451      */
33452     getCell : function(rowIndex, colIndex){
33453         var locked = this.cm.getLockedCount();
33454         var source;
33455         if(colIndex < locked){
33456             source = this.lockedBody.dom.firstChild;
33457         }else{
33458             source = this.mainBody.dom.firstChild;
33459             colIndex -= locked;
33460         }
33461         return source.rows[rowIndex].childNodes[colIndex];
33462     },
33463
33464     getCellText : function(rowIndex, colIndex){
33465         return this.getCell(rowIndex, colIndex).firstChild.firstChild;
33466     },
33467
33468     getCellBox : function(cell){
33469         var b = this.fly(cell).getBox();
33470         if(Roo.isOpera){ // opera fails to report the Y
33471             b.y = cell.offsetTop + this.mainBody.getY();
33472         }
33473         return b;
33474     },
33475
33476     getCellIndex : function(cell){
33477         var id = String(cell.className).match(this.cellRE);
33478         if(id){
33479             return parseInt(id[1], 10);
33480         }
33481         return 0;
33482     },
33483
33484     findHeaderIndex : function(n){
33485         var r = Roo.fly(n).findParent("td." + this.hdClass, 6);
33486         return r ? this.getCellIndex(r) : false;
33487     },
33488
33489     findHeaderCell : function(n){
33490         var r = Roo.fly(n).findParent("td." + this.hdClass, 6);
33491         return r ? r : false;
33492     },
33493
33494     findRowIndex : function(n){
33495         if(!n){
33496             return false;
33497         }
33498         var r = Roo.fly(n).findParent("tr." + this.rowClass, 6);
33499         return r ? r.rowIndex : false;
33500     },
33501
33502     findCellIndex : function(node){
33503         var stop = this.el.dom;
33504         while(node && node != stop){
33505             if(this.findRE.test(node.className)){
33506                 return this.getCellIndex(node);
33507             }
33508             node = node.parentNode;
33509         }
33510         return false;
33511     },
33512
33513     getColumnId : function(index){
33514         return this.cm.getColumnId(index);
33515     },
33516
33517     getSplitters : function()
33518     {
33519         if(this.splitterSelector){
33520            return Roo.DomQuery.select(this.splitterSelector);
33521         }else{
33522             return null;
33523       }
33524     },
33525
33526     getSplitter : function(index){
33527         return this.getSplitters()[index];
33528     },
33529
33530     onRowOver : function(e, t){
33531         var row;
33532         if((row = this.findRowIndex(t)) !== false){
33533             this.getRowComposite(row).addClass("x-grid-row-over");
33534         }
33535     },
33536
33537     onRowOut : function(e, t){
33538         var row;
33539         if((row = this.findRowIndex(t)) !== false && row !== this.findRowIndex(e.getRelatedTarget())){
33540             this.getRowComposite(row).removeClass("x-grid-row-over");
33541         }
33542     },
33543
33544     renderHeaders : function(){
33545         var cm = this.cm;
33546         var ct = this.templates.hcell, ht = this.templates.header, st = this.templates.hsplit;
33547         var cb = [], lb = [], sb = [], lsb = [], p = {};
33548         for(var i = 0, len = cm.getColumnCount(); i < len; i++){
33549             p.cellId = "x-grid-hd-0-" + i;
33550             p.splitId = "x-grid-csplit-0-" + i;
33551             p.id = cm.getColumnId(i);
33552             p.value = cm.getColumnHeader(i) || "";
33553             p.title = cm.getColumnTooltip(i) || (''+p.value).match(/\</)  ? '' :  p.value  || "";
33554             p.style = (this.grid.enableColumnResize === false || !cm.isResizable(i) || cm.isFixed(i)) ? 'cursor:default' : '';
33555             if(!cm.isLocked(i)){
33556                 cb[cb.length] = ct.apply(p);
33557                 sb[sb.length] = st.apply(p);
33558             }else{
33559                 lb[lb.length] = ct.apply(p);
33560                 lsb[lsb.length] = st.apply(p);
33561             }
33562         }
33563         return [ht.apply({cells: lb.join(""), splits:lsb.join("")}),
33564                 ht.apply({cells: cb.join(""), splits:sb.join("")})];
33565     },
33566
33567     updateHeaders : function(){
33568         var html = this.renderHeaders();
33569         this.lockedHd.update(html[0]);
33570         this.mainHd.update(html[1]);
33571     },
33572
33573     /**
33574      * Focuses the specified row.
33575      * @param {Number} row The row index
33576      */
33577     focusRow : function(row)
33578     {
33579         //Roo.log('GridView.focusRow');
33580         var x = this.scroller.dom.scrollLeft;
33581         this.focusCell(row, 0, false);
33582         this.scroller.dom.scrollLeft = x;
33583     },
33584
33585     /**
33586      * Focuses the specified cell.
33587      * @param {Number} row The row index
33588      * @param {Number} col The column index
33589      * @param {Boolean} hscroll false to disable horizontal scrolling
33590      */
33591     focusCell : function(row, col, hscroll)
33592     {
33593         //Roo.log('GridView.focusCell');
33594         var el = this.ensureVisible(row, col, hscroll);
33595         this.focusEl.alignTo(el, "tl-tl");
33596         if(Roo.isGecko){
33597             this.focusEl.focus();
33598         }else{
33599             this.focusEl.focus.defer(1, this.focusEl);
33600         }
33601     },
33602
33603     /**
33604      * Scrolls the specified cell into view
33605      * @param {Number} row The row index
33606      * @param {Number} col The column index
33607      * @param {Boolean} hscroll false to disable horizontal scrolling
33608      */
33609     ensureVisible : function(row, col, hscroll)
33610     {
33611         //Roo.log('GridView.ensureVisible,' + row + ',' + col);
33612         //return null; //disable for testing.
33613         if(typeof row != "number"){
33614             row = row.rowIndex;
33615         }
33616         if(row < 0 && row >= this.ds.getCount()){
33617             return  null;
33618         }
33619         col = (col !== undefined ? col : 0);
33620         var cm = this.grid.colModel;
33621         while(cm.isHidden(col)){
33622             col++;
33623         }
33624
33625         var el = this.getCell(row, col);
33626         if(!el){
33627             return null;
33628         }
33629         var c = this.scroller.dom;
33630
33631         var ctop = parseInt(el.offsetTop, 10);
33632         var cleft = parseInt(el.offsetLeft, 10);
33633         var cbot = ctop + el.offsetHeight;
33634         var cright = cleft + el.offsetWidth;
33635         
33636         var ch = c.clientHeight - this.mainHd.dom.offsetHeight;
33637         var stop = parseInt(c.scrollTop, 10);
33638         var sleft = parseInt(c.scrollLeft, 10);
33639         var sbot = stop + ch;
33640         var sright = sleft + c.clientWidth;
33641         /*
33642         Roo.log('GridView.ensureVisible:' +
33643                 ' ctop:' + ctop +
33644                 ' c.clientHeight:' + c.clientHeight +
33645                 ' this.mainHd.dom.offsetHeight:' + this.mainHd.dom.offsetHeight +
33646                 ' stop:' + stop +
33647                 ' cbot:' + cbot +
33648                 ' sbot:' + sbot +
33649                 ' ch:' + ch  
33650                 );
33651         */
33652         if(ctop < stop){
33653              c.scrollTop = ctop;
33654             //Roo.log("set scrolltop to ctop DISABLE?");
33655         }else if(cbot > sbot){
33656             //Roo.log("set scrolltop to cbot-ch");
33657             c.scrollTop = cbot-ch;
33658         }
33659         
33660         if(hscroll !== false){
33661             if(cleft < sleft){
33662                 c.scrollLeft = cleft;
33663             }else if(cright > sright){
33664                 c.scrollLeft = cright-c.clientWidth;
33665             }
33666         }
33667          
33668         return el;
33669     },
33670
33671     updateColumns : function(){
33672         this.grid.stopEditing();
33673         var cm = this.grid.colModel, colIds = this.getColumnIds();
33674         //var totalWidth = cm.getTotalWidth();
33675         var pos = 0;
33676         for(var i = 0, len = cm.getColumnCount(); i < len; i++){
33677             //if(cm.isHidden(i)) continue;
33678             var w = cm.getColumnWidth(i);
33679             this.css.updateRule(this.colSelector+this.idToCssName(colIds[i]), "width", (w - this.borderWidth) + "px");
33680             this.css.updateRule(this.hdSelector+this.idToCssName(colIds[i]), "width", (w - this.borderWidth) + "px");
33681         }
33682         this.updateSplitters();
33683     },
33684
33685     generateRules : function(cm){
33686         var ruleBuf = [], rulesId = this.idToCssName(this.grid.id)+ '-cssrules';
33687         Roo.util.CSS.removeStyleSheet(rulesId);
33688         for(var i = 0, len = cm.getColumnCount(); i < len; i++){
33689             var cid = cm.getColumnId(i);
33690             var align = '';
33691             if(cm.config[i].align){
33692                 align = 'text-align:'+cm.config[i].align+';';
33693             }
33694             var hidden = '';
33695             if(cm.isHidden(i)){
33696                 hidden = 'display:none;';
33697             }
33698             var width = "width:" + (cm.getColumnWidth(i) - this.borderWidth) + "px;";
33699             ruleBuf.push(
33700                     this.colSelector, cid, " {\n", cm.config[i].css, align, width, "\n}\n",
33701                     this.hdSelector, cid, " {\n", align, width, "}\n",
33702                     this.tdSelector, cid, " {\n",hidden,"\n}\n",
33703                     this.splitSelector, cid, " {\n", hidden , "\n}\n");
33704         }
33705         return Roo.util.CSS.createStyleSheet(ruleBuf.join(""), rulesId);
33706     },
33707
33708     updateSplitters : function(){
33709         var cm = this.cm, s = this.getSplitters();
33710         if(s){ // splitters not created yet
33711             var pos = 0, locked = true;
33712             for(var i = 0, len = cm.getColumnCount(); i < len; i++){
33713                 if(cm.isHidden(i)) {
33714                     continue;
33715                 }
33716                 var w = cm.getColumnWidth(i); // make sure it's a number
33717                 if(!cm.isLocked(i) && locked){
33718                     pos = 0;
33719                     locked = false;
33720                 }
33721                 pos += w;
33722                 s[i].style.left = (pos-this.splitOffset) + "px";
33723             }
33724         }
33725     },
33726
33727     handleHiddenChange : function(colModel, colIndex, hidden){
33728         if(hidden){
33729             this.hideColumn(colIndex);
33730         }else{
33731             this.unhideColumn(colIndex);
33732         }
33733     },
33734
33735     hideColumn : function(colIndex){
33736         var cid = this.getColumnId(colIndex);
33737         this.css.updateRule(this.tdSelector+this.idToCssName(cid), "display", "none");
33738         this.css.updateRule(this.splitSelector+this.idToCssName(cid), "display", "none");
33739         if(Roo.isSafari){
33740             this.updateHeaders();
33741         }
33742         this.updateSplitters();
33743         this.layout();
33744     },
33745
33746     unhideColumn : function(colIndex){
33747         var cid = this.getColumnId(colIndex);
33748         this.css.updateRule(this.tdSelector+this.idToCssName(cid), "display", "");
33749         this.css.updateRule(this.splitSelector+this.idToCssName(cid), "display", "");
33750
33751         if(Roo.isSafari){
33752             this.updateHeaders();
33753         }
33754         this.updateSplitters();
33755         this.layout();
33756     },
33757
33758     insertRows : function(dm, firstRow, lastRow, isUpdate){
33759         if(firstRow == 0 && lastRow == dm.getCount()-1){
33760             this.refresh();
33761         }else{
33762             if(!isUpdate){
33763                 this.fireEvent("beforerowsinserted", this, firstRow, lastRow);
33764             }
33765             var s = this.getScrollState();
33766             var markup = this.renderRows(firstRow, lastRow);
33767             this.bufferRows(markup[0], this.getLockedTable(), firstRow);
33768             this.bufferRows(markup[1], this.getBodyTable(), firstRow);
33769             this.restoreScroll(s);
33770             if(!isUpdate){
33771                 this.fireEvent("rowsinserted", this, firstRow, lastRow);
33772                 this.syncRowHeights(firstRow, lastRow);
33773                 this.stripeRows(firstRow);
33774                 this.layout();
33775             }
33776         }
33777     },
33778
33779     bufferRows : function(markup, target, index){
33780         var before = null, trows = target.rows, tbody = target.tBodies[0];
33781         if(index < trows.length){
33782             before = trows[index];
33783         }
33784         var b = document.createElement("div");
33785         b.innerHTML = "<table><tbody>"+markup+"</tbody></table>";
33786         var rows = b.firstChild.rows;
33787         for(var i = 0, len = rows.length; i < len; i++){
33788             if(before){
33789                 tbody.insertBefore(rows[0], before);
33790             }else{
33791                 tbody.appendChild(rows[0]);
33792             }
33793         }
33794         b.innerHTML = "";
33795         b = null;
33796     },
33797
33798     deleteRows : function(dm, firstRow, lastRow){
33799         if(dm.getRowCount()<1){
33800             this.fireEvent("beforerefresh", this);
33801             this.mainBody.update("");
33802             this.lockedBody.update("");
33803             this.fireEvent("refresh", this);
33804         }else{
33805             this.fireEvent("beforerowsdeleted", this, firstRow, lastRow);
33806             var bt = this.getBodyTable();
33807             var tbody = bt.firstChild;
33808             var rows = bt.rows;
33809             for(var rowIndex = firstRow; rowIndex <= lastRow; rowIndex++){
33810                 tbody.removeChild(rows[firstRow]);
33811             }
33812             this.stripeRows(firstRow);
33813             this.fireEvent("rowsdeleted", this, firstRow, lastRow);
33814         }
33815     },
33816
33817     updateRows : function(dataSource, firstRow, lastRow){
33818         var s = this.getScrollState();
33819         this.refresh();
33820         this.restoreScroll(s);
33821     },
33822
33823     handleSort : function(dataSource, sortColumnIndex, sortDir, noRefresh){
33824         if(!noRefresh){
33825            this.refresh();
33826         }
33827         this.updateHeaderSortState();
33828     },
33829
33830     getScrollState : function(){
33831         
33832         var sb = this.scroller.dom;
33833         return {left: sb.scrollLeft, top: sb.scrollTop};
33834     },
33835
33836     stripeRows : function(startRow){
33837         if(!this.grid.stripeRows || this.ds.getCount() < 1){
33838             return;
33839         }
33840         startRow = startRow || 0;
33841         var rows = this.getBodyTable().rows;
33842         var lrows = this.getLockedTable().rows;
33843         var cls = ' x-grid-row-alt ';
33844         for(var i = startRow, len = rows.length; i < len; i++){
33845             var row = rows[i], lrow = lrows[i];
33846             var isAlt = ((i+1) % 2 == 0);
33847             var hasAlt = (' '+row.className + ' ').indexOf(cls) != -1;
33848             if(isAlt == hasAlt){
33849                 continue;
33850             }
33851             if(isAlt){
33852                 row.className += " x-grid-row-alt";
33853             }else{
33854                 row.className = row.className.replace("x-grid-row-alt", "");
33855             }
33856             if(lrow){
33857                 lrow.className = row.className;
33858             }
33859         }
33860     },
33861
33862     restoreScroll : function(state){
33863         //Roo.log('GridView.restoreScroll');
33864         var sb = this.scroller.dom;
33865         sb.scrollLeft = state.left;
33866         sb.scrollTop = state.top;
33867         this.syncScroll();
33868     },
33869
33870     syncScroll : function(){
33871         //Roo.log('GridView.syncScroll');
33872         var sb = this.scroller.dom;
33873         var sh = this.mainHd.dom;
33874         var bs = this.mainBody.dom;
33875         var lv = this.lockedBody.dom;
33876         sh.scrollLeft = bs.scrollLeft = sb.scrollLeft;
33877         lv.scrollTop = bs.scrollTop = sb.scrollTop;
33878     },
33879
33880     handleScroll : function(e){
33881         this.syncScroll();
33882         var sb = this.scroller.dom;
33883         this.grid.fireEvent("bodyscroll", sb.scrollLeft, sb.scrollTop);
33884         e.stopEvent();
33885     },
33886
33887     handleWheel : function(e){
33888         var d = e.getWheelDelta();
33889         this.scroller.dom.scrollTop -= d*22;
33890         // set this here to prevent jumpy scrolling on large tables
33891         this.lockedBody.dom.scrollTop = this.mainBody.dom.scrollTop = this.scroller.dom.scrollTop;
33892         e.stopEvent();
33893     },
33894
33895     renderRows : function(startRow, endRow){
33896         // pull in all the crap needed to render rows
33897         var g = this.grid, cm = g.colModel, ds = g.dataSource, stripe = g.stripeRows;
33898         var colCount = cm.getColumnCount();
33899
33900         if(ds.getCount() < 1){
33901             return ["", ""];
33902         }
33903
33904         // build a map for all the columns
33905         var cs = [];
33906         for(var i = 0; i < colCount; i++){
33907             var name = cm.getDataIndex(i);
33908             cs[i] = {
33909                 name : typeof name == 'undefined' ? ds.fields.get(i).name : name,
33910                 renderer : cm.getRenderer(i),
33911                 id : cm.getColumnId(i),
33912                 locked : cm.isLocked(i),
33913                 has_editor : cm.isCellEditable(i)
33914             };
33915         }
33916
33917         startRow = startRow || 0;
33918         endRow = typeof endRow == "undefined"? ds.getCount()-1 : endRow;
33919
33920         // records to render
33921         var rs = ds.getRange(startRow, endRow);
33922
33923         return this.doRender(cs, rs, ds, startRow, colCount, stripe);
33924     },
33925
33926     // As much as I hate to duplicate code, this was branched because FireFox really hates
33927     // [].join("") on strings. The performance difference was substantial enough to
33928     // branch this function
33929     doRender : Roo.isGecko ?
33930             function(cs, rs, ds, startRow, colCount, stripe){
33931                 var ts = this.templates, ct = ts.cell, rt = ts.row;
33932                 // buffers
33933                 var buf = "", lbuf = "", cb, lcb, c, p = {}, rp = {}, r, rowIndex;
33934                 
33935                 var hasListener = this.grid.hasListener('rowclass');
33936                 var rowcfg = {};
33937                 for(var j = 0, len = rs.length; j < len; j++){
33938                     r = rs[j]; cb = ""; lcb = ""; rowIndex = (j+startRow);
33939                     for(var i = 0; i < colCount; i++){
33940                         c = cs[i];
33941                         p.cellId = "x-grid-cell-" + rowIndex + "-" + i;
33942                         p.id = c.id;
33943                         p.css = p.attr = "";
33944                         p.value = c.renderer(r.data[c.name], p, r, rowIndex, i, ds);
33945                         if(p.value == undefined || p.value === "") {
33946                             p.value = "&#160;";
33947                         }
33948                         if(c.has_editor){
33949                             p.css += ' x-grid-editable-cell';
33950                         }
33951                         if(c.dirty && typeof r.modified[c.name] !== 'undefined'){
33952                             p.css +=  ' x-grid-dirty-cell';
33953                         }
33954                         var markup = ct.apply(p);
33955                         if(!c.locked){
33956                             cb+= markup;
33957                         }else{
33958                             lcb+= markup;
33959                         }
33960                     }
33961                     var alt = [];
33962                     if(stripe && ((rowIndex+1) % 2 == 0)){
33963                         alt.push("x-grid-row-alt")
33964                     }
33965                     if(r.dirty){
33966                         alt.push(  " x-grid-dirty-row");
33967                     }
33968                     rp.cells = lcb;
33969                     if(this.getRowClass){
33970                         alt.push(this.getRowClass(r, rowIndex));
33971                     }
33972                     if (hasListener) {
33973                         rowcfg = {
33974                              
33975                             record: r,
33976                             rowIndex : rowIndex,
33977                             rowClass : ''
33978                         };
33979                         this.grid.fireEvent('rowclass', this, rowcfg);
33980                         alt.push(rowcfg.rowClass);
33981                     }
33982                     rp.alt = alt.join(" ");
33983                     lbuf+= rt.apply(rp);
33984                     rp.cells = cb;
33985                     buf+=  rt.apply(rp);
33986                 }
33987                 return [lbuf, buf];
33988             } :
33989             function(cs, rs, ds, startRow, colCount, stripe){
33990                 var ts = this.templates, ct = ts.cell, rt = ts.row;
33991                 // buffers
33992                 var buf = [], lbuf = [], cb, lcb, c, p = {}, rp = {}, r, rowIndex;
33993                 var hasListener = this.grid.hasListener('rowclass');
33994  
33995                 var rowcfg = {};
33996                 for(var j = 0, len = rs.length; j < len; j++){
33997                     r = rs[j]; cb = []; lcb = []; rowIndex = (j+startRow);
33998                     for(var i = 0; i < colCount; i++){
33999                         c = cs[i];
34000                         p.cellId = "x-grid-cell-" + rowIndex + "-" + i;
34001                         p.id = c.id;
34002                         p.css = p.attr = "";
34003                         p.value = c.renderer(r.data[c.name], p, r, rowIndex, i, ds);
34004                         if(p.value == undefined || p.value === "") {
34005                             p.value = "&#160;";
34006                         }
34007                         //Roo.log(c);
34008                          if(c.has_editor){
34009                             p.css += ' x-grid-editable-cell';
34010                         }
34011                         if(r.dirty && typeof r.modified[c.name] !== 'undefined'){
34012                             p.css += ' x-grid-dirty-cell' 
34013                         }
34014                         
34015                         var markup = ct.apply(p);
34016                         if(!c.locked){
34017                             cb[cb.length] = markup;
34018                         }else{
34019                             lcb[lcb.length] = markup;
34020                         }
34021                     }
34022                     var alt = [];
34023                     if(stripe && ((rowIndex+1) % 2 == 0)){
34024                         alt.push( "x-grid-row-alt");
34025                     }
34026                     if(r.dirty){
34027                         alt.push(" x-grid-dirty-row");
34028                     }
34029                     rp.cells = lcb;
34030                     if(this.getRowClass){
34031                         alt.push( this.getRowClass(r, rowIndex));
34032                     }
34033                     if (hasListener) {
34034                         rowcfg = {
34035                              
34036                             record: r,
34037                             rowIndex : rowIndex,
34038                             rowClass : ''
34039                         };
34040                         this.grid.fireEvent('rowclass', this, rowcfg);
34041                         alt.push(rowcfg.rowClass);
34042                     }
34043                     
34044                     rp.alt = alt.join(" ");
34045                     rp.cells = lcb.join("");
34046                     lbuf[lbuf.length] = rt.apply(rp);
34047                     rp.cells = cb.join("");
34048                     buf[buf.length] =  rt.apply(rp);
34049                 }
34050                 return [lbuf.join(""), buf.join("")];
34051             },
34052
34053     renderBody : function(){
34054         var markup = this.renderRows();
34055         var bt = this.templates.body;
34056         return [bt.apply({rows: markup[0]}), bt.apply({rows: markup[1]})];
34057     },
34058
34059     /**
34060      * Refreshes the grid
34061      * @param {Boolean} headersToo
34062      */
34063     refresh : function(headersToo){
34064         this.fireEvent("beforerefresh", this);
34065         this.grid.stopEditing();
34066         var result = this.renderBody();
34067         this.lockedBody.update(result[0]);
34068         this.mainBody.update(result[1]);
34069         if(headersToo === true){
34070             this.updateHeaders();
34071             this.updateColumns();
34072             this.updateSplitters();
34073             this.updateHeaderSortState();
34074         }
34075         this.syncRowHeights();
34076         this.layout();
34077         this.fireEvent("refresh", this);
34078     },
34079
34080     handleColumnMove : function(cm, oldIndex, newIndex){
34081         this.indexMap = null;
34082         var s = this.getScrollState();
34083         this.refresh(true);
34084         this.restoreScroll(s);
34085         this.afterMove(newIndex);
34086     },
34087
34088     afterMove : function(colIndex){
34089         if(this.enableMoveAnim && Roo.enableFx){
34090             this.fly(this.getHeaderCell(colIndex).firstChild).highlight(this.hlColor);
34091         }
34092         // if multisort - fix sortOrder, and reload..
34093         if (this.grid.dataSource.multiSort) {
34094             // the we can call sort again..
34095             var dm = this.grid.dataSource;
34096             var cm = this.grid.colModel;
34097             var so = [];
34098             for(var i = 0; i < cm.config.length; i++ ) {
34099                 
34100                 if ((typeof(dm.sortToggle[cm.config[i].dataIndex]) == 'undefined')) {
34101                     continue; // dont' bother, it's not in sort list or being set.
34102                 }
34103                 
34104                 so.push(cm.config[i].dataIndex);
34105             };
34106             dm.sortOrder = so;
34107             dm.load(dm.lastOptions);
34108             
34109             
34110         }
34111         
34112     },
34113
34114     updateCell : function(dm, rowIndex, dataIndex){
34115         var colIndex = this.getColumnIndexByDataIndex(dataIndex);
34116         if(typeof colIndex == "undefined"){ // not present in grid
34117             return;
34118         }
34119         var cm = this.grid.colModel;
34120         var cell = this.getCell(rowIndex, colIndex);
34121         var cellText = this.getCellText(rowIndex, colIndex);
34122
34123         var p = {
34124             cellId : "x-grid-cell-" + rowIndex + "-" + colIndex,
34125             id : cm.getColumnId(colIndex),
34126             css: colIndex == cm.getColumnCount()-1 ? "x-grid-col-last" : ""
34127         };
34128         var renderer = cm.getRenderer(colIndex);
34129         var val = renderer(dm.getValueAt(rowIndex, dataIndex), p, rowIndex, colIndex, dm);
34130         if(typeof val == "undefined" || val === "") {
34131             val = "&#160;";
34132         }
34133         cellText.innerHTML = val;
34134         cell.className = this.cellClass + " " + this.idToCssName(p.cellId) + " " + p.css;
34135         this.syncRowHeights(rowIndex, rowIndex);
34136     },
34137
34138     calcColumnWidth : function(colIndex, maxRowsToMeasure){
34139         var maxWidth = 0;
34140         if(this.grid.autoSizeHeaders){
34141             var h = this.getHeaderCellMeasure(colIndex);
34142             maxWidth = Math.max(maxWidth, h.scrollWidth);
34143         }
34144         var tb, index;
34145         if(this.cm.isLocked(colIndex)){
34146             tb = this.getLockedTable();
34147             index = colIndex;
34148         }else{
34149             tb = this.getBodyTable();
34150             index = colIndex - this.cm.getLockedCount();
34151         }
34152         if(tb && tb.rows){
34153             var rows = tb.rows;
34154             var stopIndex = Math.min(maxRowsToMeasure || rows.length, rows.length);
34155             for(var i = 0; i < stopIndex; i++){
34156                 var cell = rows[i].childNodes[index].firstChild;
34157                 maxWidth = Math.max(maxWidth, cell.scrollWidth);
34158             }
34159         }
34160         return maxWidth + /*margin for error in IE*/ 5;
34161     },
34162     /**
34163      * Autofit a column to its content.
34164      * @param {Number} colIndex
34165      * @param {Boolean} forceMinSize true to force the column to go smaller if possible
34166      */
34167      autoSizeColumn : function(colIndex, forceMinSize, suppressEvent){
34168          if(this.cm.isHidden(colIndex)){
34169              return; // can't calc a hidden column
34170          }
34171         if(forceMinSize){
34172             var cid = this.cm.getColumnId(colIndex);
34173             this.css.updateRule(this.colSelector +this.idToCssName( cid), "width", this.grid.minColumnWidth + "px");
34174            if(this.grid.autoSizeHeaders){
34175                this.css.updateRule(this.hdSelector + this.idToCssName(cid), "width", this.grid.minColumnWidth + "px");
34176            }
34177         }
34178         var newWidth = this.calcColumnWidth(colIndex);
34179         this.cm.setColumnWidth(colIndex,
34180             Math.max(this.grid.minColumnWidth, newWidth), suppressEvent);
34181         if(!suppressEvent){
34182             this.grid.fireEvent("columnresize", colIndex, newWidth);
34183         }
34184     },
34185
34186     /**
34187      * Autofits all columns to their content and then expands to fit any extra space in the grid
34188      */
34189      autoSizeColumns : function(){
34190         var cm = this.grid.colModel;
34191         var colCount = cm.getColumnCount();
34192         for(var i = 0; i < colCount; i++){
34193             this.autoSizeColumn(i, true, true);
34194         }
34195         if(cm.getTotalWidth() < this.scroller.dom.clientWidth){
34196             this.fitColumns();
34197         }else{
34198             this.updateColumns();
34199             this.layout();
34200         }
34201     },
34202
34203     /**
34204      * Autofits all columns to the grid's width proportionate with their current size
34205      * @param {Boolean} reserveScrollSpace Reserve space for a scrollbar
34206      */
34207     fitColumns : function(reserveScrollSpace){
34208         var cm = this.grid.colModel;
34209         var colCount = cm.getColumnCount();
34210         var cols = [];
34211         var width = 0;
34212         var i, w;
34213         for (i = 0; i < colCount; i++){
34214             if(!cm.isHidden(i) && !cm.isFixed(i)){
34215                 w = cm.getColumnWidth(i);
34216                 cols.push(i);
34217                 cols.push(w);
34218                 width += w;
34219             }
34220         }
34221         var avail = Math.min(this.scroller.dom.clientWidth, this.el.getWidth());
34222         if(reserveScrollSpace){
34223             avail -= 17;
34224         }
34225         var frac = (avail - cm.getTotalWidth())/width;
34226         while (cols.length){
34227             w = cols.pop();
34228             i = cols.pop();
34229             cm.setColumnWidth(i, Math.floor(w + w*frac), true);
34230         }
34231         this.updateColumns();
34232         this.layout();
34233     },
34234
34235     onRowSelect : function(rowIndex){
34236         var row = this.getRowComposite(rowIndex);
34237         row.addClass("x-grid-row-selected");
34238     },
34239
34240     onRowDeselect : function(rowIndex){
34241         var row = this.getRowComposite(rowIndex);
34242         row.removeClass("x-grid-row-selected");
34243     },
34244
34245     onCellSelect : function(row, col){
34246         var cell = this.getCell(row, col);
34247         if(cell){
34248             Roo.fly(cell).addClass("x-grid-cell-selected");
34249         }
34250     },
34251
34252     onCellDeselect : function(row, col){
34253         var cell = this.getCell(row, col);
34254         if(cell){
34255             Roo.fly(cell).removeClass("x-grid-cell-selected");
34256         }
34257     },
34258
34259     updateHeaderSortState : function(){
34260         
34261         // sort state can be single { field: xxx, direction : yyy}
34262         // or   { xxx=>ASC , yyy : DESC ..... }
34263         
34264         var mstate = {};
34265         if (!this.ds.multiSort) { 
34266             var state = this.ds.getSortState();
34267             if(!state){
34268                 return;
34269             }
34270             mstate[state.field] = state.direction;
34271             // FIXME... - this is not used here.. but might be elsewhere..
34272             this.sortState = state;
34273             
34274         } else {
34275             mstate = this.ds.sortToggle;
34276         }
34277         //remove existing sort classes..
34278         
34279         var sc = this.sortClasses;
34280         var hds = this.el.select(this.headerSelector).removeClass(sc);
34281         
34282         for(var f in mstate) {
34283         
34284             var sortColumn = this.cm.findColumnIndex(f);
34285             
34286             if(sortColumn != -1){
34287                 var sortDir = mstate[f];        
34288                 hds.item(sortColumn).addClass(sc[sortDir == "DESC" ? 1 : 0]);
34289             }
34290         }
34291         
34292          
34293         
34294     },
34295
34296
34297     handleHeaderClick : function(g, index,e){
34298         
34299         Roo.log("header click");
34300         
34301         if (Roo.isTouch) {
34302             // touch events on header are handled by context
34303             this.handleHdCtx(g,index,e);
34304             return;
34305         }
34306         
34307         
34308         if(this.headersDisabled){
34309             return;
34310         }
34311         var dm = g.dataSource, cm = g.colModel;
34312         if(!cm.isSortable(index)){
34313             return;
34314         }
34315         g.stopEditing();
34316         
34317         if (dm.multiSort) {
34318             // update the sortOrder
34319             var so = [];
34320             for(var i = 0; i < cm.config.length; i++ ) {
34321                 
34322                 if ((typeof(dm.sortToggle[cm.config[i].dataIndex]) == 'undefined') && (index != i)) {
34323                     continue; // dont' bother, it's not in sort list or being set.
34324                 }
34325                 
34326                 so.push(cm.config[i].dataIndex);
34327             };
34328             dm.sortOrder = so;
34329         }
34330         
34331         
34332         dm.sort(cm.getDataIndex(index));
34333     },
34334
34335
34336     destroy : function(){
34337         if(this.colMenu){
34338             this.colMenu.removeAll();
34339             Roo.menu.MenuMgr.unregister(this.colMenu);
34340             this.colMenu.getEl().remove();
34341             delete this.colMenu;
34342         }
34343         if(this.hmenu){
34344             this.hmenu.removeAll();
34345             Roo.menu.MenuMgr.unregister(this.hmenu);
34346             this.hmenu.getEl().remove();
34347             delete this.hmenu;
34348         }
34349         if(this.grid.enableColumnMove){
34350             var dds = Roo.dd.DDM.ids['gridHeader' + this.grid.getGridEl().id];
34351             if(dds){
34352                 for(var dd in dds){
34353                     if(!dds[dd].config.isTarget && dds[dd].dragElId){
34354                         var elid = dds[dd].dragElId;
34355                         dds[dd].unreg();
34356                         Roo.get(elid).remove();
34357                     } else if(dds[dd].config.isTarget){
34358                         dds[dd].proxyTop.remove();
34359                         dds[dd].proxyBottom.remove();
34360                         dds[dd].unreg();
34361                     }
34362                     if(Roo.dd.DDM.locationCache[dd]){
34363                         delete Roo.dd.DDM.locationCache[dd];
34364                     }
34365                 }
34366                 delete Roo.dd.DDM.ids['gridHeader' + this.grid.getGridEl().id];
34367             }
34368         }
34369         Roo.util.CSS.removeStyleSheet(this.idToCssName(this.grid.id) + '-cssrules');
34370         this.bind(null, null);
34371         Roo.EventManager.removeResizeListener(this.onWindowResize, this);
34372     },
34373
34374     handleLockChange : function(){
34375         this.refresh(true);
34376     },
34377
34378     onDenyColumnLock : function(){
34379
34380     },
34381
34382     onDenyColumnHide : function(){
34383
34384     },
34385
34386     handleHdMenuClick : function(item){
34387         var index = this.hdCtxIndex;
34388         var cm = this.cm, ds = this.ds;
34389         switch(item.id){
34390             case "asc":
34391                 ds.sort(cm.getDataIndex(index), "ASC");
34392                 break;
34393             case "desc":
34394                 ds.sort(cm.getDataIndex(index), "DESC");
34395                 break;
34396             case "lock":
34397                 var lc = cm.getLockedCount();
34398                 if(cm.getColumnCount(true) <= lc+1){
34399                     this.onDenyColumnLock();
34400                     return;
34401                 }
34402                 if(lc != index){
34403                     cm.setLocked(index, true, true);
34404                     cm.moveColumn(index, lc);
34405                     this.grid.fireEvent("columnmove", index, lc);
34406                 }else{
34407                     cm.setLocked(index, true);
34408                 }
34409             break;
34410             case "unlock":
34411                 var lc = cm.getLockedCount();
34412                 if((lc-1) != index){
34413                     cm.setLocked(index, false, true);
34414                     cm.moveColumn(index, lc-1);
34415                     this.grid.fireEvent("columnmove", index, lc-1);
34416                 }else{
34417                     cm.setLocked(index, false);
34418                 }
34419             break;
34420             case 'wider': // used to expand cols on touch..
34421             case 'narrow':
34422                 var cw = cm.getColumnWidth(index);
34423                 cw += (item.id == 'wider' ? 1 : -1) * 50;
34424                 cw = Math.max(0, cw);
34425                 cw = Math.min(cw,4000);
34426                 cm.setColumnWidth(index, cw);
34427                 break;
34428                 
34429             default:
34430                 index = cm.getIndexById(item.id.substr(4));
34431                 if(index != -1){
34432                     if(item.checked && cm.getColumnCount(true) <= 1){
34433                         this.onDenyColumnHide();
34434                         return false;
34435                     }
34436                     cm.setHidden(index, item.checked);
34437                 }
34438         }
34439         return true;
34440     },
34441
34442     beforeColMenuShow : function(){
34443         var cm = this.cm,  colCount = cm.getColumnCount();
34444         this.colMenu.removeAll();
34445         for(var i = 0; i < colCount; i++){
34446             this.colMenu.add(new Roo.menu.CheckItem({
34447                 id: "col-"+cm.getColumnId(i),
34448                 text: cm.getColumnHeader(i),
34449                 checked: !cm.isHidden(i),
34450                 hideOnClick:false
34451             }));
34452         }
34453     },
34454
34455     handleHdCtx : function(g, index, e){
34456         e.stopEvent();
34457         var hd = this.getHeaderCell(index);
34458         this.hdCtxIndex = index;
34459         var ms = this.hmenu.items, cm = this.cm;
34460         ms.get("asc").setDisabled(!cm.isSortable(index));
34461         ms.get("desc").setDisabled(!cm.isSortable(index));
34462         if(this.grid.enableColLock !== false){
34463             ms.get("lock").setDisabled(cm.isLocked(index));
34464             ms.get("unlock").setDisabled(!cm.isLocked(index));
34465         }
34466         this.hmenu.show(hd, "tl-bl");
34467     },
34468
34469     handleHdOver : function(e){
34470         var hd = this.findHeaderCell(e.getTarget());
34471         if(hd && !this.headersDisabled){
34472             if(this.grid.colModel.isSortable(this.getCellIndex(hd))){
34473                this.fly(hd).addClass("x-grid-hd-over");
34474             }
34475         }
34476     },
34477
34478     handleHdOut : function(e){
34479         var hd = this.findHeaderCell(e.getTarget());
34480         if(hd){
34481             this.fly(hd).removeClass("x-grid-hd-over");
34482         }
34483     },
34484
34485     handleSplitDblClick : function(e, t){
34486         var i = this.getCellIndex(t);
34487         if(this.grid.enableColumnResize !== false && this.cm.isResizable(i) && !this.cm.isFixed(i)){
34488             this.autoSizeColumn(i, true);
34489             this.layout();
34490         }
34491     },
34492
34493     render : function(){
34494
34495         var cm = this.cm;
34496         var colCount = cm.getColumnCount();
34497
34498         if(this.grid.monitorWindowResize === true){
34499             Roo.EventManager.onWindowResize(this.onWindowResize, this, true);
34500         }
34501         var header = this.renderHeaders();
34502         var body = this.templates.body.apply({rows:""});
34503         var html = this.templates.master.apply({
34504             lockedBody: body,
34505             body: body,
34506             lockedHeader: header[0],
34507             header: header[1]
34508         });
34509
34510         //this.updateColumns();
34511
34512         this.grid.getGridEl().dom.innerHTML = html;
34513
34514         this.initElements();
34515         
34516         // a kludge to fix the random scolling effect in webkit
34517         this.el.on("scroll", function() {
34518             this.el.dom.scrollTop=0; // hopefully not recursive..
34519         },this);
34520
34521         this.scroller.on("scroll", this.handleScroll, this);
34522         this.lockedBody.on("mousewheel", this.handleWheel, this);
34523         this.mainBody.on("mousewheel", this.handleWheel, this);
34524
34525         this.mainHd.on("mouseover", this.handleHdOver, this);
34526         this.mainHd.on("mouseout", this.handleHdOut, this);
34527         this.mainHd.on("dblclick", this.handleSplitDblClick, this,
34528                 {delegate: "."+this.splitClass});
34529
34530         this.lockedHd.on("mouseover", this.handleHdOver, this);
34531         this.lockedHd.on("mouseout", this.handleHdOut, this);
34532         this.lockedHd.on("dblclick", this.handleSplitDblClick, this,
34533                 {delegate: "."+this.splitClass});
34534
34535         if(this.grid.enableColumnResize !== false && Roo.grid.SplitDragZone){
34536             new Roo.grid.SplitDragZone(this.grid, this.lockedHd.dom, this.mainHd.dom);
34537         }
34538
34539         this.updateSplitters();
34540
34541         if(this.grid.enableColumnMove && Roo.grid.HeaderDragZone){
34542             new Roo.grid.HeaderDragZone(this.grid, this.lockedHd.dom, this.mainHd.dom);
34543             new Roo.grid.HeaderDropZone(this.grid, this.lockedHd.dom, this.mainHd.dom);
34544         }
34545
34546         if(this.grid.enableCtxMenu !== false && Roo.menu.Menu){
34547             this.hmenu = new Roo.menu.Menu({id: this.grid.id + "-hctx"});
34548             this.hmenu.add(
34549                 {id:"asc", text: this.sortAscText, cls: "xg-hmenu-sort-asc"},
34550                 {id:"desc", text: this.sortDescText, cls: "xg-hmenu-sort-desc"}
34551             );
34552             if(this.grid.enableColLock !== false){
34553                 this.hmenu.add('-',
34554                     {id:"lock", text: this.lockText, cls: "xg-hmenu-lock"},
34555                     {id:"unlock", text: this.unlockText, cls: "xg-hmenu-unlock"}
34556                 );
34557             }
34558             if (Roo.isTouch) {
34559                  this.hmenu.add('-',
34560                     {id:"wider", text: this.columnsWiderText},
34561                     {id:"narrow", text: this.columnsNarrowText }
34562                 );
34563                 
34564                  
34565             }
34566             
34567             if(this.grid.enableColumnHide !== false){
34568
34569                 this.colMenu = new Roo.menu.Menu({id:this.grid.id + "-hcols-menu"});
34570                 this.colMenu.on("beforeshow", this.beforeColMenuShow, this);
34571                 this.colMenu.on("itemclick", this.handleHdMenuClick, this);
34572
34573                 this.hmenu.add('-',
34574                     {id:"columns", text: this.columnsText, menu: this.colMenu}
34575                 );
34576             }
34577             this.hmenu.on("itemclick", this.handleHdMenuClick, this);
34578
34579             this.grid.on("headercontextmenu", this.handleHdCtx, this);
34580         }
34581
34582         if((this.grid.enableDragDrop || this.grid.enableDrag) && Roo.grid.GridDragZone){
34583             this.dd = new Roo.grid.GridDragZone(this.grid, {
34584                 ddGroup : this.grid.ddGroup || 'GridDD'
34585             });
34586             
34587         }
34588
34589         /*
34590         for(var i = 0; i < colCount; i++){
34591             if(cm.isHidden(i)){
34592                 this.hideColumn(i);
34593             }
34594             if(cm.config[i].align){
34595                 this.css.updateRule(this.colSelector + i, "textAlign", cm.config[i].align);
34596                 this.css.updateRule(this.hdSelector + i, "textAlign", cm.config[i].align);
34597             }
34598         }*/
34599         
34600         this.updateHeaderSortState();
34601
34602         this.beforeInitialResize();
34603         this.layout(true);
34604
34605         // two part rendering gives faster view to the user
34606         this.renderPhase2.defer(1, this);
34607     },
34608
34609     renderPhase2 : function(){
34610         // render the rows now
34611         this.refresh();
34612         if(this.grid.autoSizeColumns){
34613             this.autoSizeColumns();
34614         }
34615     },
34616
34617     beforeInitialResize : function(){
34618
34619     },
34620
34621     onColumnSplitterMoved : function(i, w){
34622         this.userResized = true;
34623         var cm = this.grid.colModel;
34624         cm.setColumnWidth(i, w, true);
34625         var cid = cm.getColumnId(i);
34626         this.css.updateRule(this.colSelector + this.idToCssName(cid), "width", (w-this.borderWidth) + "px");
34627         this.css.updateRule(this.hdSelector + this.idToCssName(cid), "width", (w-this.borderWidth) + "px");
34628         this.updateSplitters();
34629         this.layout();
34630         this.grid.fireEvent("columnresize", i, w);
34631     },
34632
34633     syncRowHeights : function(startIndex, endIndex){
34634         if(this.grid.enableRowHeightSync === true && this.cm.getLockedCount() > 0){
34635             startIndex = startIndex || 0;
34636             var mrows = this.getBodyTable().rows;
34637             var lrows = this.getLockedTable().rows;
34638             var len = mrows.length-1;
34639             endIndex = Math.min(endIndex || len, len);
34640             for(var i = startIndex; i <= endIndex; i++){
34641                 var m = mrows[i], l = lrows[i];
34642                 var h = Math.max(m.offsetHeight, l.offsetHeight);
34643                 m.style.height = l.style.height = h + "px";
34644             }
34645         }
34646     },
34647
34648     layout : function(initialRender, is2ndPass){
34649         var g = this.grid;
34650         var auto = g.autoHeight;
34651         var scrollOffset = 16;
34652         var c = g.getGridEl(), cm = this.cm,
34653                 expandCol = g.autoExpandColumn,
34654                 gv = this;
34655         //c.beginMeasure();
34656
34657         if(!c.dom.offsetWidth){ // display:none?
34658             if(initialRender){
34659                 this.lockedWrap.show();
34660                 this.mainWrap.show();
34661             }
34662             return;
34663         }
34664
34665         var hasLock = this.cm.isLocked(0);
34666
34667         var tbh = this.headerPanel.getHeight();
34668         var bbh = this.footerPanel.getHeight();
34669
34670         if(auto){
34671             var ch = this.getBodyTable().offsetHeight + tbh + bbh + this.mainHd.getHeight();
34672             var newHeight = ch + c.getBorderWidth("tb");
34673             if(g.maxHeight){
34674                 newHeight = Math.min(g.maxHeight, newHeight);
34675             }
34676             c.setHeight(newHeight);
34677         }
34678
34679         if(g.autoWidth){
34680             c.setWidth(cm.getTotalWidth()+c.getBorderWidth('lr'));
34681         }
34682
34683         var s = this.scroller;
34684
34685         var csize = c.getSize(true);
34686
34687         this.el.setSize(csize.width, csize.height);
34688
34689         this.headerPanel.setWidth(csize.width);
34690         this.footerPanel.setWidth(csize.width);
34691
34692         var hdHeight = this.mainHd.getHeight();
34693         var vw = csize.width;
34694         var vh = csize.height - (tbh + bbh);
34695
34696         s.setSize(vw, vh);
34697
34698         var bt = this.getBodyTable();
34699         
34700         if(cm.getLockedCount() == cm.config.length){
34701             bt = this.getLockedTable();
34702         }
34703         
34704         var ltWidth = hasLock ?
34705                       Math.max(this.getLockedTable().offsetWidth, this.lockedHd.dom.firstChild.offsetWidth) : 0;
34706
34707         var scrollHeight = bt.offsetHeight;
34708         var scrollWidth = ltWidth + bt.offsetWidth;
34709         var vscroll = false, hscroll = false;
34710
34711         this.scrollSizer.setSize(scrollWidth, scrollHeight+hdHeight);
34712
34713         var lw = this.lockedWrap, mw = this.mainWrap;
34714         var lb = this.lockedBody, mb = this.mainBody;
34715
34716         setTimeout(function(){
34717             var t = s.dom.offsetTop;
34718             var w = s.dom.clientWidth,
34719                 h = s.dom.clientHeight;
34720
34721             lw.setTop(t);
34722             lw.setSize(ltWidth, h);
34723
34724             mw.setLeftTop(ltWidth, t);
34725             mw.setSize(w-ltWidth, h);
34726
34727             lb.setHeight(h-hdHeight);
34728             mb.setHeight(h-hdHeight);
34729
34730             if(is2ndPass !== true && !gv.userResized && expandCol){
34731                 // high speed resize without full column calculation
34732                 
34733                 var ci = cm.getIndexById(expandCol);
34734                 if (ci < 0) {
34735                     ci = cm.findColumnIndex(expandCol);
34736                 }
34737                 ci = Math.max(0, ci); // make sure it's got at least the first col.
34738                 var expandId = cm.getColumnId(ci);
34739                 var  tw = cm.getTotalWidth(false);
34740                 var currentWidth = cm.getColumnWidth(ci);
34741                 var cw = Math.min(Math.max(((w-tw)+currentWidth-2)-/*scrollbar*/(w <= s.dom.offsetWidth ? 0 : 18), g.autoExpandMin), g.autoExpandMax);
34742                 if(currentWidth != cw){
34743                     cm.setColumnWidth(ci, cw, true);
34744                     gv.css.updateRule(gv.colSelector+gv.idToCssName(expandId), "width", (cw - gv.borderWidth) + "px");
34745                     gv.css.updateRule(gv.hdSelector+gv.idToCssName(expandId), "width", (cw - gv.borderWidth) + "px");
34746                     gv.updateSplitters();
34747                     gv.layout(false, true);
34748                 }
34749             }
34750
34751             if(initialRender){
34752                 lw.show();
34753                 mw.show();
34754             }
34755             //c.endMeasure();
34756         }, 10);
34757     },
34758
34759     onWindowResize : function(){
34760         if(!this.grid.monitorWindowResize || this.grid.autoHeight){
34761             return;
34762         }
34763         this.layout();
34764     },
34765
34766     appendFooter : function(parentEl){
34767         return null;
34768     },
34769
34770     sortAscText : "Sort Ascending",
34771     sortDescText : "Sort Descending",
34772     lockText : "Lock Column",
34773     unlockText : "Unlock Column",
34774     columnsText : "Columns",
34775  
34776     columnsWiderText : "Wider",
34777     columnsNarrowText : "Thinner"
34778 });
34779
34780
34781 Roo.grid.GridView.ColumnDragZone = function(grid, hd){
34782     Roo.grid.GridView.ColumnDragZone.superclass.constructor.call(this, grid, hd, null);
34783     this.proxy.el.addClass('x-grid3-col-dd');
34784 };
34785
34786 Roo.extend(Roo.grid.GridView.ColumnDragZone, Roo.grid.HeaderDragZone, {
34787     handleMouseDown : function(e){
34788
34789     },
34790
34791     callHandleMouseDown : function(e){
34792         Roo.grid.GridView.ColumnDragZone.superclass.handleMouseDown.call(this, e);
34793     }
34794 });
34795 /*
34796  * Based on:
34797  * Ext JS Library 1.1.1
34798  * Copyright(c) 2006-2007, Ext JS, LLC.
34799  *
34800  * Originally Released Under LGPL - original licence link has changed is not relivant.
34801  *
34802  * Fork - LGPL
34803  * <script type="text/javascript">
34804  */
34805  
34806 // private
34807 // This is a support class used internally by the Grid components
34808 Roo.grid.SplitDragZone = function(grid, hd, hd2){
34809     this.grid = grid;
34810     this.view = grid.getView();
34811     this.proxy = this.view.resizeProxy;
34812     Roo.grid.SplitDragZone.superclass.constructor.call(this, hd,
34813         "gridSplitters" + this.grid.getGridEl().id, {
34814         dragElId : Roo.id(this.proxy.dom), resizeFrame:false
34815     });
34816     this.setHandleElId(Roo.id(hd));
34817     this.setOuterHandleElId(Roo.id(hd2));
34818     this.scroll = false;
34819 };
34820 Roo.extend(Roo.grid.SplitDragZone, Roo.dd.DDProxy, {
34821     fly: Roo.Element.fly,
34822
34823     b4StartDrag : function(x, y){
34824         this.view.headersDisabled = true;
34825         this.proxy.setHeight(this.view.mainWrap.getHeight());
34826         var w = this.cm.getColumnWidth(this.cellIndex);
34827         var minw = Math.max(w-this.grid.minColumnWidth, 0);
34828         this.resetConstraints();
34829         this.setXConstraint(minw, 1000);
34830         this.setYConstraint(0, 0);
34831         this.minX = x - minw;
34832         this.maxX = x + 1000;
34833         this.startPos = x;
34834         Roo.dd.DDProxy.prototype.b4StartDrag.call(this, x, y);
34835     },
34836
34837
34838     handleMouseDown : function(e){
34839         ev = Roo.EventObject.setEvent(e);
34840         var t = this.fly(ev.getTarget());
34841         if(t.hasClass("x-grid-split")){
34842             this.cellIndex = this.view.getCellIndex(t.dom);
34843             this.split = t.dom;
34844             this.cm = this.grid.colModel;
34845             if(this.cm.isResizable(this.cellIndex) && !this.cm.isFixed(this.cellIndex)){
34846                 Roo.grid.SplitDragZone.superclass.handleMouseDown.apply(this, arguments);
34847             }
34848         }
34849     },
34850
34851     endDrag : function(e){
34852         this.view.headersDisabled = false;
34853         var endX = Math.max(this.minX, Roo.lib.Event.getPageX(e));
34854         var diff = endX - this.startPos;
34855         this.view.onColumnSplitterMoved(this.cellIndex, this.cm.getColumnWidth(this.cellIndex)+diff);
34856     },
34857
34858     autoOffset : function(){
34859         this.setDelta(0,0);
34860     }
34861 });/*
34862  * Based on:
34863  * Ext JS Library 1.1.1
34864  * Copyright(c) 2006-2007, Ext JS, LLC.
34865  *
34866  * Originally Released Under LGPL - original licence link has changed is not relivant.
34867  *
34868  * Fork - LGPL
34869  * <script type="text/javascript">
34870  */
34871  
34872 // private
34873 // This is a support class used internally by the Grid components
34874 Roo.grid.GridDragZone = function(grid, config){
34875     this.view = grid.getView();
34876     Roo.grid.GridDragZone.superclass.constructor.call(this, this.view.mainBody.dom, config);
34877     if(this.view.lockedBody){
34878         this.setHandleElId(Roo.id(this.view.mainBody.dom));
34879         this.setOuterHandleElId(Roo.id(this.view.lockedBody.dom));
34880     }
34881     this.scroll = false;
34882     this.grid = grid;
34883     this.ddel = document.createElement('div');
34884     this.ddel.className = 'x-grid-dd-wrap';
34885 };
34886
34887 Roo.extend(Roo.grid.GridDragZone, Roo.dd.DragZone, {
34888     ddGroup : "GridDD",
34889
34890     getDragData : function(e){
34891         var t = Roo.lib.Event.getTarget(e);
34892         var rowIndex = this.view.findRowIndex(t);
34893         var sm = this.grid.selModel;
34894             
34895         //Roo.log(rowIndex);
34896         
34897         if (sm.getSelectedCell) {
34898             // cell selection..
34899             if (!sm.getSelectedCell()) {
34900                 return false;
34901             }
34902             if (rowIndex != sm.getSelectedCell()[0]) {
34903                 return false;
34904             }
34905         
34906         }
34907         
34908         if(rowIndex !== false){
34909             
34910             // if editorgrid.. 
34911             
34912             
34913             //Roo.log([ sm.getSelectedCell() ? sm.getSelectedCell()[0] : 'NO' , rowIndex ]);
34914                
34915             //if(!sm.isSelected(rowIndex) || e.hasModifier()){
34916               //  
34917             //}
34918             if (e.hasModifier()){
34919                 sm.handleMouseDown(e, t); // non modifier buttons are handled by row select.
34920             }
34921             
34922             Roo.log("getDragData");
34923             
34924             return {
34925                 grid: this.grid,
34926                 ddel: this.ddel,
34927                 rowIndex: rowIndex,
34928                 selections:sm.getSelections ? sm.getSelections() : (
34929                     sm.getSelectedCell() ? [ this.grid.ds.getAt(sm.getSelectedCell()[0]) ] : []
34930                 )
34931             };
34932         }
34933         return false;
34934     },
34935
34936     onInitDrag : function(e){
34937         var data = this.dragData;
34938         this.ddel.innerHTML = this.grid.getDragDropText();
34939         this.proxy.update(this.ddel);
34940         // fire start drag?
34941     },
34942
34943     afterRepair : function(){
34944         this.dragging = false;
34945     },
34946
34947     getRepairXY : function(e, data){
34948         return false;
34949     },
34950
34951     onEndDrag : function(data, e){
34952         // fire end drag?
34953     },
34954
34955     onValidDrop : function(dd, e, id){
34956         // fire drag drop?
34957         this.hideProxy();
34958     },
34959
34960     beforeInvalidDrop : function(e, id){
34961
34962     }
34963 });/*
34964  * Based on:
34965  * Ext JS Library 1.1.1
34966  * Copyright(c) 2006-2007, Ext JS, LLC.
34967  *
34968  * Originally Released Under LGPL - original licence link has changed is not relivant.
34969  *
34970  * Fork - LGPL
34971  * <script type="text/javascript">
34972  */
34973  
34974
34975 /**
34976  * @class Roo.grid.ColumnModel
34977  * @extends Roo.util.Observable
34978  * This is the default implementation of a ColumnModel used by the Grid. It defines
34979  * the columns in the grid.
34980  * <br>Usage:<br>
34981  <pre><code>
34982  var colModel = new Roo.grid.ColumnModel([
34983         {header: "Ticker", width: 60, sortable: true, locked: true},
34984         {header: "Company Name", width: 150, sortable: true},
34985         {header: "Market Cap.", width: 100, sortable: true},
34986         {header: "$ Sales", width: 100, sortable: true, renderer: money},
34987         {header: "Employees", width: 100, sortable: true, resizable: false}
34988  ]);
34989  </code></pre>
34990  * <p>
34991  
34992  * The config options listed for this class are options which may appear in each
34993  * individual column definition.
34994  * <br/>RooJS Fix - column id's are not sequential but use Roo.id() - fixes bugs with layouts.
34995  * @constructor
34996  * @param {Object} config An Array of column config objects. See this class's
34997  * config objects for details.
34998 */
34999 Roo.grid.ColumnModel = function(config){
35000         /**
35001      * The config passed into the constructor
35002      */
35003     this.config = config;
35004     this.lookup = {};
35005
35006     // if no id, create one
35007     // if the column does not have a dataIndex mapping,
35008     // map it to the order it is in the config
35009     for(var i = 0, len = config.length; i < len; i++){
35010         var c = config[i];
35011         if(typeof c.dataIndex == "undefined"){
35012             c.dataIndex = i;
35013         }
35014         if(typeof c.renderer == "string"){
35015             c.renderer = Roo.util.Format[c.renderer];
35016         }
35017         if(typeof c.id == "undefined"){
35018             c.id = Roo.id();
35019         }
35020         if(c.editor && c.editor.xtype){
35021             c.editor  = Roo.factory(c.editor, Roo.grid);
35022         }
35023         if(c.editor && c.editor.isFormField){
35024             c.editor = new Roo.grid.GridEditor(c.editor);
35025         }
35026         this.lookup[c.id] = c;
35027     }
35028
35029     /**
35030      * The width of columns which have no width specified (defaults to 100)
35031      * @type Number
35032      */
35033     this.defaultWidth = 100;
35034
35035     /**
35036      * Default sortable of columns which have no sortable specified (defaults to false)
35037      * @type Boolean
35038      */
35039     this.defaultSortable = false;
35040
35041     this.addEvents({
35042         /**
35043              * @event widthchange
35044              * Fires when the width of a column changes.
35045              * @param {ColumnModel} this
35046              * @param {Number} columnIndex The column index
35047              * @param {Number} newWidth The new width
35048              */
35049             "widthchange": true,
35050         /**
35051              * @event headerchange
35052              * Fires when the text of a header changes.
35053              * @param {ColumnModel} this
35054              * @param {Number} columnIndex The column index
35055              * @param {Number} newText The new header text
35056              */
35057             "headerchange": true,
35058         /**
35059              * @event hiddenchange
35060              * Fires when a column is hidden or "unhidden".
35061              * @param {ColumnModel} this
35062              * @param {Number} columnIndex The column index
35063              * @param {Boolean} hidden true if hidden, false otherwise
35064              */
35065             "hiddenchange": true,
35066             /**
35067          * @event columnmoved
35068          * Fires when a column is moved.
35069          * @param {ColumnModel} this
35070          * @param {Number} oldIndex
35071          * @param {Number} newIndex
35072          */
35073         "columnmoved" : true,
35074         /**
35075          * @event columlockchange
35076          * Fires when a column's locked state is changed
35077          * @param {ColumnModel} this
35078          * @param {Number} colIndex
35079          * @param {Boolean} locked true if locked
35080          */
35081         "columnlockchange" : true
35082     });
35083     Roo.grid.ColumnModel.superclass.constructor.call(this);
35084 };
35085 Roo.extend(Roo.grid.ColumnModel, Roo.util.Observable, {
35086     /**
35087      * @cfg {String} header The header text to display in the Grid view.
35088      */
35089     /**
35090      * @cfg {String} dataIndex (Optional) The name of the field in the grid's {@link Roo.data.Store}'s
35091      * {@link Roo.data.Record} definition from which to draw the column's value. If not
35092      * specified, the column's index is used as an index into the Record's data Array.
35093      */
35094     /**
35095      * @cfg {Number} width (Optional) The initial width in pixels of the column. Using this
35096      * instead of {@link Roo.grid.Grid#autoSizeColumns} is more efficient.
35097      */
35098     /**
35099      * @cfg {Boolean} sortable (Optional) True if sorting is to be allowed on this column.
35100      * Defaults to the value of the {@link #defaultSortable} property.
35101      * Whether local/remote sorting is used is specified in {@link Roo.data.Store#remoteSort}.
35102      */
35103     /**
35104      * @cfg {Boolean} locked (Optional) True to lock the column in place while scrolling the Grid.  Defaults to false.
35105      */
35106     /**
35107      * @cfg {Boolean} fixed (Optional) True if the column width cannot be changed.  Defaults to false.
35108      */
35109     /**
35110      * @cfg {Boolean} resizable (Optional) False to disable column resizing. Defaults to true.
35111      */
35112     /**
35113      * @cfg {Boolean} hidden (Optional) True to hide the column. Defaults to false.
35114      */
35115     /**
35116      * @cfg {Function} renderer (Optional) A function used to generate HTML markup for a cell
35117      * given the cell's data value. See {@link #setRenderer}. If not specified, the
35118      * default renderer returns the escaped data value. If an object is returned (bootstrap only)
35119      * then it is treated as a Roo Component object instance, and it is rendered after the initial row is rendered
35120      */
35121        /**
35122      * @cfg {Roo.grid.GridEditor} editor (Optional) For grid editors - returns the grid editor 
35123      */
35124     /**
35125      * @cfg {String} align (Optional) Set the CSS text-align property of the column.  Defaults to undefined.
35126      */
35127     /**
35128      * @cfg {String} valign (Optional) Set the CSS vertical-align property of the column (eg. middle, top, bottom etc).  Defaults to undefined.
35129      */
35130     /**
35131      * @cfg {String} cursor (Optional)
35132      */
35133     /**
35134      * @cfg {String} tooltip (Optional)
35135      */
35136     /**
35137      * @cfg {Number} xs (Optional)
35138      */
35139     /**
35140      * @cfg {Number} sm (Optional)
35141      */
35142     /**
35143      * @cfg {Number} md (Optional)
35144      */
35145     /**
35146      * @cfg {Number} lg (Optional)
35147      */
35148     /**
35149      * Returns the id of the column at the specified index.
35150      * @param {Number} index The column index
35151      * @return {String} the id
35152      */
35153     getColumnId : function(index){
35154         return this.config[index].id;
35155     },
35156
35157     /**
35158      * Returns the column for a specified id.
35159      * @param {String} id The column id
35160      * @return {Object} the column
35161      */
35162     getColumnById : function(id){
35163         return this.lookup[id];
35164     },
35165
35166     
35167     /**
35168      * Returns the column for a specified dataIndex.
35169      * @param {String} dataIndex The column dataIndex
35170      * @return {Object|Boolean} the column or false if not found
35171      */
35172     getColumnByDataIndex: function(dataIndex){
35173         var index = this.findColumnIndex(dataIndex);
35174         return index > -1 ? this.config[index] : false;
35175     },
35176     
35177     /**
35178      * Returns the index for a specified column id.
35179      * @param {String} id The column id
35180      * @return {Number} the index, or -1 if not found
35181      */
35182     getIndexById : function(id){
35183         for(var i = 0, len = this.config.length; i < len; i++){
35184             if(this.config[i].id == id){
35185                 return i;
35186             }
35187         }
35188         return -1;
35189     },
35190     
35191     /**
35192      * Returns the index for a specified column dataIndex.
35193      * @param {String} dataIndex The column dataIndex
35194      * @return {Number} the index, or -1 if not found
35195      */
35196     
35197     findColumnIndex : function(dataIndex){
35198         for(var i = 0, len = this.config.length; i < len; i++){
35199             if(this.config[i].dataIndex == dataIndex){
35200                 return i;
35201             }
35202         }
35203         return -1;
35204     },
35205     
35206     
35207     moveColumn : function(oldIndex, newIndex){
35208         var c = this.config[oldIndex];
35209         this.config.splice(oldIndex, 1);
35210         this.config.splice(newIndex, 0, c);
35211         this.dataMap = null;
35212         this.fireEvent("columnmoved", this, oldIndex, newIndex);
35213     },
35214
35215     isLocked : function(colIndex){
35216         return this.config[colIndex].locked === true;
35217     },
35218
35219     setLocked : function(colIndex, value, suppressEvent){
35220         if(this.isLocked(colIndex) == value){
35221             return;
35222         }
35223         this.config[colIndex].locked = value;
35224         if(!suppressEvent){
35225             this.fireEvent("columnlockchange", this, colIndex, value);
35226         }
35227     },
35228
35229     getTotalLockedWidth : function(){
35230         var totalWidth = 0;
35231         for(var i = 0; i < this.config.length; i++){
35232             if(this.isLocked(i) && !this.isHidden(i)){
35233                 this.totalWidth += this.getColumnWidth(i);
35234             }
35235         }
35236         return totalWidth;
35237     },
35238
35239     getLockedCount : function(){
35240         for(var i = 0, len = this.config.length; i < len; i++){
35241             if(!this.isLocked(i)){
35242                 return i;
35243             }
35244         }
35245         
35246         return this.config.length;
35247     },
35248
35249     /**
35250      * Returns the number of columns.
35251      * @return {Number}
35252      */
35253     getColumnCount : function(visibleOnly){
35254         if(visibleOnly === true){
35255             var c = 0;
35256             for(var i = 0, len = this.config.length; i < len; i++){
35257                 if(!this.isHidden(i)){
35258                     c++;
35259                 }
35260             }
35261             return c;
35262         }
35263         return this.config.length;
35264     },
35265
35266     /**
35267      * Returns the column configs that return true by the passed function that is called with (columnConfig, index)
35268      * @param {Function} fn
35269      * @param {Object} scope (optional)
35270      * @return {Array} result
35271      */
35272     getColumnsBy : function(fn, scope){
35273         var r = [];
35274         for(var i = 0, len = this.config.length; i < len; i++){
35275             var c = this.config[i];
35276             if(fn.call(scope||this, c, i) === true){
35277                 r[r.length] = c;
35278             }
35279         }
35280         return r;
35281     },
35282
35283     /**
35284      * Returns true if the specified column is sortable.
35285      * @param {Number} col The column index
35286      * @return {Boolean}
35287      */
35288     isSortable : function(col){
35289         if(typeof this.config[col].sortable == "undefined"){
35290             return this.defaultSortable;
35291         }
35292         return this.config[col].sortable;
35293     },
35294
35295     /**
35296      * Returns the rendering (formatting) function defined for the column.
35297      * @param {Number} col The column index.
35298      * @return {Function} The function used to render the cell. See {@link #setRenderer}.
35299      */
35300     getRenderer : function(col){
35301         if(!this.config[col].renderer){
35302             return Roo.grid.ColumnModel.defaultRenderer;
35303         }
35304         return this.config[col].renderer;
35305     },
35306
35307     /**
35308      * Sets the rendering (formatting) function for a column.
35309      * @param {Number} col The column index
35310      * @param {Function} fn The function to use to process the cell's raw data
35311      * to return HTML markup for the grid view. The render function is called with
35312      * the following parameters:<ul>
35313      * <li>Data value.</li>
35314      * <li>Cell metadata. An object in which you may set the following attributes:<ul>
35315      * <li>css A CSS style string to apply to the table cell.</li>
35316      * <li>attr An HTML attribute definition string to apply to the data container element <i>within</i> the table cell.</li></ul>
35317      * <li>The {@link Roo.data.Record} from which the data was extracted.</li>
35318      * <li>Row index</li>
35319      * <li>Column index</li>
35320      * <li>The {@link Roo.data.Store} object from which the Record was extracted</li></ul>
35321      */
35322     setRenderer : function(col, fn){
35323         this.config[col].renderer = fn;
35324     },
35325
35326     /**
35327      * Returns the width for the specified column.
35328      * @param {Number} col The column index
35329      * @return {Number}
35330      */
35331     getColumnWidth : function(col){
35332         return this.config[col].width * 1 || this.defaultWidth;
35333     },
35334
35335     /**
35336      * Sets the width for a column.
35337      * @param {Number} col The column index
35338      * @param {Number} width The new width
35339      */
35340     setColumnWidth : function(col, width, suppressEvent){
35341         this.config[col].width = width;
35342         this.totalWidth = null;
35343         if(!suppressEvent){
35344              this.fireEvent("widthchange", this, col, width);
35345         }
35346     },
35347
35348     /**
35349      * Returns the total width of all columns.
35350      * @param {Boolean} includeHidden True to include hidden column widths
35351      * @return {Number}
35352      */
35353     getTotalWidth : function(includeHidden){
35354         if(!this.totalWidth){
35355             this.totalWidth = 0;
35356             for(var i = 0, len = this.config.length; i < len; i++){
35357                 if(includeHidden || !this.isHidden(i)){
35358                     this.totalWidth += this.getColumnWidth(i);
35359                 }
35360             }
35361         }
35362         return this.totalWidth;
35363     },
35364
35365     /**
35366      * Returns the header for the specified column.
35367      * @param {Number} col The column index
35368      * @return {String}
35369      */
35370     getColumnHeader : function(col){
35371         return this.config[col].header;
35372     },
35373
35374     /**
35375      * Sets the header for a column.
35376      * @param {Number} col The column index
35377      * @param {String} header The new header
35378      */
35379     setColumnHeader : function(col, header){
35380         this.config[col].header = header;
35381         this.fireEvent("headerchange", this, col, header);
35382     },
35383
35384     /**
35385      * Returns the tooltip for the specified column.
35386      * @param {Number} col The column index
35387      * @return {String}
35388      */
35389     getColumnTooltip : function(col){
35390             return this.config[col].tooltip;
35391     },
35392     /**
35393      * Sets the tooltip for a column.
35394      * @param {Number} col The column index
35395      * @param {String} tooltip The new tooltip
35396      */
35397     setColumnTooltip : function(col, tooltip){
35398             this.config[col].tooltip = tooltip;
35399     },
35400
35401     /**
35402      * Returns the dataIndex for the specified column.
35403      * @param {Number} col The column index
35404      * @return {Number}
35405      */
35406     getDataIndex : function(col){
35407         return this.config[col].dataIndex;
35408     },
35409
35410     /**
35411      * Sets the dataIndex for a column.
35412      * @param {Number} col The column index
35413      * @param {Number} dataIndex The new dataIndex
35414      */
35415     setDataIndex : function(col, dataIndex){
35416         this.config[col].dataIndex = dataIndex;
35417     },
35418
35419     
35420     
35421     /**
35422      * Returns true if the cell is editable.
35423      * @param {Number} colIndex The column index
35424      * @param {Number} rowIndex The row index - this is nto actually used..?
35425      * @return {Boolean}
35426      */
35427     isCellEditable : function(colIndex, rowIndex){
35428         return (this.config[colIndex].editable || (typeof this.config[colIndex].editable == "undefined" && this.config[colIndex].editor)) ? true : false;
35429     },
35430
35431     /**
35432      * Returns the editor defined for the cell/column.
35433      * return false or null to disable editing.
35434      * @param {Number} colIndex The column index
35435      * @param {Number} rowIndex The row index
35436      * @return {Object}
35437      */
35438     getCellEditor : function(colIndex, rowIndex){
35439         return this.config[colIndex].editor;
35440     },
35441
35442     /**
35443      * Sets if a column is editable.
35444      * @param {Number} col The column index
35445      * @param {Boolean} editable True if the column is editable
35446      */
35447     setEditable : function(col, editable){
35448         this.config[col].editable = editable;
35449     },
35450
35451
35452     /**
35453      * Returns true if the column is hidden.
35454      * @param {Number} colIndex The column index
35455      * @return {Boolean}
35456      */
35457     isHidden : function(colIndex){
35458         return this.config[colIndex].hidden;
35459     },
35460
35461
35462     /**
35463      * Returns true if the column width cannot be changed
35464      */
35465     isFixed : function(colIndex){
35466         return this.config[colIndex].fixed;
35467     },
35468
35469     /**
35470      * Returns true if the column can be resized
35471      * @return {Boolean}
35472      */
35473     isResizable : function(colIndex){
35474         return colIndex >= 0 && this.config[colIndex].resizable !== false && this.config[colIndex].fixed !== true;
35475     },
35476     /**
35477      * Sets if a column is hidden.
35478      * @param {Number} colIndex The column index
35479      * @param {Boolean} hidden True if the column is hidden
35480      */
35481     setHidden : function(colIndex, hidden){
35482         this.config[colIndex].hidden = hidden;
35483         this.totalWidth = null;
35484         this.fireEvent("hiddenchange", this, colIndex, hidden);
35485     },
35486
35487     /**
35488      * Sets the editor for a column.
35489      * @param {Number} col The column index
35490      * @param {Object} editor The editor object
35491      */
35492     setEditor : function(col, editor){
35493         this.config[col].editor = editor;
35494     }
35495 });
35496
35497 Roo.grid.ColumnModel.defaultRenderer = function(value)
35498 {
35499     if(typeof value == "object") {
35500         return value;
35501     }
35502         if(typeof value == "string" && value.length < 1){
35503             return "&#160;";
35504         }
35505     
35506         return String.format("{0}", value);
35507 };
35508
35509 // Alias for backwards compatibility
35510 Roo.grid.DefaultColumnModel = Roo.grid.ColumnModel;
35511 /*
35512  * Based on:
35513  * Ext JS Library 1.1.1
35514  * Copyright(c) 2006-2007, Ext JS, LLC.
35515  *
35516  * Originally Released Under LGPL - original licence link has changed is not relivant.
35517  *
35518  * Fork - LGPL
35519  * <script type="text/javascript">
35520  */
35521
35522 /**
35523  * @class Roo.grid.AbstractSelectionModel
35524  * @extends Roo.util.Observable
35525  * Abstract base class for grid SelectionModels.  It provides the interface that should be
35526  * implemented by descendant classes.  This class should not be directly instantiated.
35527  * @constructor
35528  */
35529 Roo.grid.AbstractSelectionModel = function(){
35530     this.locked = false;
35531     Roo.grid.AbstractSelectionModel.superclass.constructor.call(this);
35532 };
35533
35534 Roo.extend(Roo.grid.AbstractSelectionModel, Roo.util.Observable,  {
35535     /** @ignore Called by the grid automatically. Do not call directly. */
35536     init : function(grid){
35537         this.grid = grid;
35538         this.initEvents();
35539     },
35540
35541     /**
35542      * Locks the selections.
35543      */
35544     lock : function(){
35545         this.locked = true;
35546     },
35547
35548     /**
35549      * Unlocks the selections.
35550      */
35551     unlock : function(){
35552         this.locked = false;
35553     },
35554
35555     /**
35556      * Returns true if the selections are locked.
35557      * @return {Boolean}
35558      */
35559     isLocked : function(){
35560         return this.locked;
35561     }
35562 });/*
35563  * Based on:
35564  * Ext JS Library 1.1.1
35565  * Copyright(c) 2006-2007, Ext JS, LLC.
35566  *
35567  * Originally Released Under LGPL - original licence link has changed is not relivant.
35568  *
35569  * Fork - LGPL
35570  * <script type="text/javascript">
35571  */
35572 /**
35573  * @extends Roo.grid.AbstractSelectionModel
35574  * @class Roo.grid.RowSelectionModel
35575  * The default SelectionModel used by {@link Roo.grid.Grid}.
35576  * It supports multiple selections and keyboard selection/navigation. 
35577  * @constructor
35578  * @param {Object} config
35579  */
35580 Roo.grid.RowSelectionModel = function(config){
35581     Roo.apply(this, config);
35582     this.selections = new Roo.util.MixedCollection(false, function(o){
35583         return o.id;
35584     });
35585
35586     this.last = false;
35587     this.lastActive = false;
35588
35589     this.addEvents({
35590         /**
35591              * @event selectionchange
35592              * Fires when the selection changes
35593              * @param {SelectionModel} this
35594              */
35595             "selectionchange" : true,
35596         /**
35597              * @event afterselectionchange
35598              * Fires after the selection changes (eg. by key press or clicking)
35599              * @param {SelectionModel} this
35600              */
35601             "afterselectionchange" : true,
35602         /**
35603              * @event beforerowselect
35604              * Fires when a row is selected being selected, return false to cancel.
35605              * @param {SelectionModel} this
35606              * @param {Number} rowIndex The selected index
35607              * @param {Boolean} keepExisting False if other selections will be cleared
35608              */
35609             "beforerowselect" : true,
35610         /**
35611              * @event rowselect
35612              * Fires when a row is selected.
35613              * @param {SelectionModel} this
35614              * @param {Number} rowIndex The selected index
35615              * @param {Roo.data.Record} r The record
35616              */
35617             "rowselect" : true,
35618         /**
35619              * @event rowdeselect
35620              * Fires when a row is deselected.
35621              * @param {SelectionModel} this
35622              * @param {Number} rowIndex The selected index
35623              */
35624         "rowdeselect" : true
35625     });
35626     Roo.grid.RowSelectionModel.superclass.constructor.call(this);
35627     this.locked = false;
35628 };
35629
35630 Roo.extend(Roo.grid.RowSelectionModel, Roo.grid.AbstractSelectionModel,  {
35631     /**
35632      * @cfg {Boolean} singleSelect
35633      * True to allow selection of only one row at a time (defaults to false)
35634      */
35635     singleSelect : false,
35636
35637     // private
35638     initEvents : function(){
35639
35640         if(!this.grid.enableDragDrop && !this.grid.enableDrag){
35641             this.grid.on("mousedown", this.handleMouseDown, this);
35642         }else{ // allow click to work like normal
35643             this.grid.on("rowclick", this.handleDragableRowClick, this);
35644         }
35645
35646         this.rowNav = new Roo.KeyNav(this.grid.getGridEl(), {
35647             "up" : function(e){
35648                 if(!e.shiftKey){
35649                     this.selectPrevious(e.shiftKey);
35650                 }else if(this.last !== false && this.lastActive !== false){
35651                     var last = this.last;
35652                     this.selectRange(this.last,  this.lastActive-1);
35653                     this.grid.getView().focusRow(this.lastActive);
35654                     if(last !== false){
35655                         this.last = last;
35656                     }
35657                 }else{
35658                     this.selectFirstRow();
35659                 }
35660                 this.fireEvent("afterselectionchange", this);
35661             },
35662             "down" : function(e){
35663                 if(!e.shiftKey){
35664                     this.selectNext(e.shiftKey);
35665                 }else if(this.last !== false && this.lastActive !== false){
35666                     var last = this.last;
35667                     this.selectRange(this.last,  this.lastActive+1);
35668                     this.grid.getView().focusRow(this.lastActive);
35669                     if(last !== false){
35670                         this.last = last;
35671                     }
35672                 }else{
35673                     this.selectFirstRow();
35674                 }
35675                 this.fireEvent("afterselectionchange", this);
35676             },
35677             scope: this
35678         });
35679
35680         var view = this.grid.view;
35681         view.on("refresh", this.onRefresh, this);
35682         view.on("rowupdated", this.onRowUpdated, this);
35683         view.on("rowremoved", this.onRemove, this);
35684     },
35685
35686     // private
35687     onRefresh : function(){
35688         var ds = this.grid.dataSource, i, v = this.grid.view;
35689         var s = this.selections;
35690         s.each(function(r){
35691             if((i = ds.indexOfId(r.id)) != -1){
35692                 v.onRowSelect(i);
35693                 s.add(ds.getAt(i)); // updating the selection relate data
35694             }else{
35695                 s.remove(r);
35696             }
35697         });
35698     },
35699
35700     // private
35701     onRemove : function(v, index, r){
35702         this.selections.remove(r);
35703     },
35704
35705     // private
35706     onRowUpdated : function(v, index, r){
35707         if(this.isSelected(r)){
35708             v.onRowSelect(index);
35709         }
35710     },
35711
35712     /**
35713      * Select records.
35714      * @param {Array} records The records to select
35715      * @param {Boolean} keepExisting (optional) True to keep existing selections
35716      */
35717     selectRecords : function(records, keepExisting){
35718         if(!keepExisting){
35719             this.clearSelections();
35720         }
35721         var ds = this.grid.dataSource;
35722         for(var i = 0, len = records.length; i < len; i++){
35723             this.selectRow(ds.indexOf(records[i]), true);
35724         }
35725     },
35726
35727     /**
35728      * Gets the number of selected rows.
35729      * @return {Number}
35730      */
35731     getCount : function(){
35732         return this.selections.length;
35733     },
35734
35735     /**
35736      * Selects the first row in the grid.
35737      */
35738     selectFirstRow : function(){
35739         this.selectRow(0);
35740     },
35741
35742     /**
35743      * Select the last row.
35744      * @param {Boolean} keepExisting (optional) True to keep existing selections
35745      */
35746     selectLastRow : function(keepExisting){
35747         this.selectRow(this.grid.dataSource.getCount() - 1, keepExisting);
35748     },
35749
35750     /**
35751      * Selects the row immediately following the last selected row.
35752      * @param {Boolean} keepExisting (optional) True to keep existing selections
35753      */
35754     selectNext : function(keepExisting){
35755         if(this.last !== false && (this.last+1) < this.grid.dataSource.getCount()){
35756             this.selectRow(this.last+1, keepExisting);
35757             this.grid.getView().focusRow(this.last);
35758         }
35759     },
35760
35761     /**
35762      * Selects the row that precedes the last selected row.
35763      * @param {Boolean} keepExisting (optional) True to keep existing selections
35764      */
35765     selectPrevious : function(keepExisting){
35766         if(this.last){
35767             this.selectRow(this.last-1, keepExisting);
35768             this.grid.getView().focusRow(this.last);
35769         }
35770     },
35771
35772     /**
35773      * Returns the selected records
35774      * @return {Array} Array of selected records
35775      */
35776     getSelections : function(){
35777         return [].concat(this.selections.items);
35778     },
35779
35780     /**
35781      * Returns the first selected record.
35782      * @return {Record}
35783      */
35784     getSelected : function(){
35785         return this.selections.itemAt(0);
35786     },
35787
35788
35789     /**
35790      * Clears all selections.
35791      */
35792     clearSelections : function(fast){
35793         if(this.locked) {
35794             return;
35795         }
35796         if(fast !== true){
35797             var ds = this.grid.dataSource;
35798             var s = this.selections;
35799             s.each(function(r){
35800                 this.deselectRow(ds.indexOfId(r.id));
35801             }, this);
35802             s.clear();
35803         }else{
35804             this.selections.clear();
35805         }
35806         this.last = false;
35807     },
35808
35809
35810     /**
35811      * Selects all rows.
35812      */
35813     selectAll : function(){
35814         if(this.locked) {
35815             return;
35816         }
35817         this.selections.clear();
35818         for(var i = 0, len = this.grid.dataSource.getCount(); i < len; i++){
35819             this.selectRow(i, true);
35820         }
35821     },
35822
35823     /**
35824      * Returns True if there is a selection.
35825      * @return {Boolean}
35826      */
35827     hasSelection : function(){
35828         return this.selections.length > 0;
35829     },
35830
35831     /**
35832      * Returns True if the specified row is selected.
35833      * @param {Number/Record} record The record or index of the record to check
35834      * @return {Boolean}
35835      */
35836     isSelected : function(index){
35837         var r = typeof index == "number" ? this.grid.dataSource.getAt(index) : index;
35838         return (r && this.selections.key(r.id) ? true : false);
35839     },
35840
35841     /**
35842      * Returns True if the specified record id is selected.
35843      * @param {String} id The id of record to check
35844      * @return {Boolean}
35845      */
35846     isIdSelected : function(id){
35847         return (this.selections.key(id) ? true : false);
35848     },
35849
35850     // private
35851     handleMouseDown : function(e, t){
35852         var view = this.grid.getView(), rowIndex;
35853         if(this.isLocked() || (rowIndex = view.findRowIndex(t)) === false){
35854             return;
35855         };
35856         if(e.shiftKey && this.last !== false){
35857             var last = this.last;
35858             this.selectRange(last, rowIndex, e.ctrlKey);
35859             this.last = last; // reset the last
35860             view.focusRow(rowIndex);
35861         }else{
35862             var isSelected = this.isSelected(rowIndex);
35863             if(e.button !== 0 && isSelected){
35864                 view.focusRow(rowIndex);
35865             }else if(e.ctrlKey && isSelected){
35866                 this.deselectRow(rowIndex);
35867             }else if(!isSelected){
35868                 this.selectRow(rowIndex, e.button === 0 && (e.ctrlKey || e.shiftKey));
35869                 view.focusRow(rowIndex);
35870             }
35871         }
35872         this.fireEvent("afterselectionchange", this);
35873     },
35874     // private
35875     handleDragableRowClick :  function(grid, rowIndex, e) 
35876     {
35877         if(e.button === 0 && !e.shiftKey && !e.ctrlKey) {
35878             this.selectRow(rowIndex, false);
35879             grid.view.focusRow(rowIndex);
35880              this.fireEvent("afterselectionchange", this);
35881         }
35882     },
35883     
35884     /**
35885      * Selects multiple rows.
35886      * @param {Array} rows Array of the indexes of the row to select
35887      * @param {Boolean} keepExisting (optional) True to keep existing selections
35888      */
35889     selectRows : function(rows, keepExisting){
35890         if(!keepExisting){
35891             this.clearSelections();
35892         }
35893         for(var i = 0, len = rows.length; i < len; i++){
35894             this.selectRow(rows[i], true);
35895         }
35896     },
35897
35898     /**
35899      * Selects a range of rows. All rows in between startRow and endRow are also selected.
35900      * @param {Number} startRow The index of the first row in the range
35901      * @param {Number} endRow The index of the last row in the range
35902      * @param {Boolean} keepExisting (optional) True to retain existing selections
35903      */
35904     selectRange : function(startRow, endRow, keepExisting){
35905         if(this.locked) {
35906             return;
35907         }
35908         if(!keepExisting){
35909             this.clearSelections();
35910         }
35911         if(startRow <= endRow){
35912             for(var i = startRow; i <= endRow; i++){
35913                 this.selectRow(i, true);
35914             }
35915         }else{
35916             for(var i = startRow; i >= endRow; i--){
35917                 this.selectRow(i, true);
35918             }
35919         }
35920     },
35921
35922     /**
35923      * Deselects a range of rows. All rows in between startRow and endRow are also deselected.
35924      * @param {Number} startRow The index of the first row in the range
35925      * @param {Number} endRow The index of the last row in the range
35926      */
35927     deselectRange : function(startRow, endRow, preventViewNotify){
35928         if(this.locked) {
35929             return;
35930         }
35931         for(var i = startRow; i <= endRow; i++){
35932             this.deselectRow(i, preventViewNotify);
35933         }
35934     },
35935
35936     /**
35937      * Selects a row.
35938      * @param {Number} row The index of the row to select
35939      * @param {Boolean} keepExisting (optional) True to keep existing selections
35940      */
35941     selectRow : function(index, keepExisting, preventViewNotify){
35942         if(this.locked || (index < 0 || index >= this.grid.dataSource.getCount())) {
35943             return;
35944         }
35945         if(this.fireEvent("beforerowselect", this, index, keepExisting) !== false){
35946             if(!keepExisting || this.singleSelect){
35947                 this.clearSelections();
35948             }
35949             var r = this.grid.dataSource.getAt(index);
35950             this.selections.add(r);
35951             this.last = this.lastActive = index;
35952             if(!preventViewNotify){
35953                 this.grid.getView().onRowSelect(index);
35954             }
35955             this.fireEvent("rowselect", this, index, r);
35956             this.fireEvent("selectionchange", this);
35957         }
35958     },
35959
35960     /**
35961      * Deselects a row.
35962      * @param {Number} row The index of the row to deselect
35963      */
35964     deselectRow : function(index, preventViewNotify){
35965         if(this.locked) {
35966             return;
35967         }
35968         if(this.last == index){
35969             this.last = false;
35970         }
35971         if(this.lastActive == index){
35972             this.lastActive = false;
35973         }
35974         var r = this.grid.dataSource.getAt(index);
35975         this.selections.remove(r);
35976         if(!preventViewNotify){
35977             this.grid.getView().onRowDeselect(index);
35978         }
35979         this.fireEvent("rowdeselect", this, index);
35980         this.fireEvent("selectionchange", this);
35981     },
35982
35983     // private
35984     restoreLast : function(){
35985         if(this._last){
35986             this.last = this._last;
35987         }
35988     },
35989
35990     // private
35991     acceptsNav : function(row, col, cm){
35992         return !cm.isHidden(col) && cm.isCellEditable(col, row);
35993     },
35994
35995     // private
35996     onEditorKey : function(field, e){
35997         var k = e.getKey(), newCell, g = this.grid, ed = g.activeEditor;
35998         if(k == e.TAB){
35999             e.stopEvent();
36000             ed.completeEdit();
36001             if(e.shiftKey){
36002                 newCell = g.walkCells(ed.row, ed.col-1, -1, this.acceptsNav, this);
36003             }else{
36004                 newCell = g.walkCells(ed.row, ed.col+1, 1, this.acceptsNav, this);
36005             }
36006         }else if(k == e.ENTER && !e.ctrlKey){
36007             e.stopEvent();
36008             ed.completeEdit();
36009             if(e.shiftKey){
36010                 newCell = g.walkCells(ed.row-1, ed.col, -1, this.acceptsNav, this);
36011             }else{
36012                 newCell = g.walkCells(ed.row+1, ed.col, 1, this.acceptsNav, this);
36013             }
36014         }else if(k == e.ESC){
36015             ed.cancelEdit();
36016         }
36017         if(newCell){
36018             g.startEditing(newCell[0], newCell[1]);
36019         }
36020     }
36021 });/*
36022  * Based on:
36023  * Ext JS Library 1.1.1
36024  * Copyright(c) 2006-2007, Ext JS, LLC.
36025  *
36026  * Originally Released Under LGPL - original licence link has changed is not relivant.
36027  *
36028  * Fork - LGPL
36029  * <script type="text/javascript">
36030  */
36031 /**
36032  * @class Roo.grid.CellSelectionModel
36033  * @extends Roo.grid.AbstractSelectionModel
36034  * This class provides the basic implementation for cell selection in a grid.
36035  * @constructor
36036  * @param {Object} config The object containing the configuration of this model.
36037  * @cfg {Boolean} enter_is_tab Enter behaves the same as tab. (eg. goes to next cell) default: false
36038  */
36039 Roo.grid.CellSelectionModel = function(config){
36040     Roo.apply(this, config);
36041
36042     this.selection = null;
36043
36044     this.addEvents({
36045         /**
36046              * @event beforerowselect
36047              * Fires before a cell is selected.
36048              * @param {SelectionModel} this
36049              * @param {Number} rowIndex The selected row index
36050              * @param {Number} colIndex The selected cell index
36051              */
36052             "beforecellselect" : true,
36053         /**
36054              * @event cellselect
36055              * Fires when a cell is selected.
36056              * @param {SelectionModel} this
36057              * @param {Number} rowIndex The selected row index
36058              * @param {Number} colIndex The selected cell index
36059              */
36060             "cellselect" : true,
36061         /**
36062              * @event selectionchange
36063              * Fires when the active selection changes.
36064              * @param {SelectionModel} this
36065              * @param {Object} selection null for no selection or an object (o) with two properties
36066                 <ul>
36067                 <li>o.record: the record object for the row the selection is in</li>
36068                 <li>o.cell: An array of [rowIndex, columnIndex]</li>
36069                 </ul>
36070              */
36071             "selectionchange" : true,
36072         /**
36073              * @event tabend
36074              * Fires when the tab (or enter) was pressed on the last editable cell
36075              * You can use this to trigger add new row.
36076              * @param {SelectionModel} this
36077              */
36078             "tabend" : true,
36079          /**
36080              * @event beforeeditnext
36081              * Fires before the next editable sell is made active
36082              * You can use this to skip to another cell or fire the tabend
36083              *    if you set cell to false
36084              * @param {Object} eventdata object : { cell : [ row, col ] } 
36085              */
36086             "beforeeditnext" : true
36087     });
36088     Roo.grid.CellSelectionModel.superclass.constructor.call(this);
36089 };
36090
36091 Roo.extend(Roo.grid.CellSelectionModel, Roo.grid.AbstractSelectionModel,  {
36092     
36093     enter_is_tab: false,
36094
36095     /** @ignore */
36096     initEvents : function(){
36097         this.grid.on("mousedown", this.handleMouseDown, this);
36098         this.grid.getGridEl().on(Roo.isIE ? "keydown" : "keypress", this.handleKeyDown, this);
36099         var view = this.grid.view;
36100         view.on("refresh", this.onViewChange, this);
36101         view.on("rowupdated", this.onRowUpdated, this);
36102         view.on("beforerowremoved", this.clearSelections, this);
36103         view.on("beforerowsinserted", this.clearSelections, this);
36104         if(this.grid.isEditor){
36105             this.grid.on("beforeedit", this.beforeEdit,  this);
36106         }
36107     },
36108
36109         //private
36110     beforeEdit : function(e){
36111         this.select(e.row, e.column, false, true, e.record);
36112     },
36113
36114         //private
36115     onRowUpdated : function(v, index, r){
36116         if(this.selection && this.selection.record == r){
36117             v.onCellSelect(index, this.selection.cell[1]);
36118         }
36119     },
36120
36121         //private
36122     onViewChange : function(){
36123         this.clearSelections(true);
36124     },
36125
36126         /**
36127          * Returns the currently selected cell,.
36128          * @return {Array} The selected cell (row, column) or null if none selected.
36129          */
36130     getSelectedCell : function(){
36131         return this.selection ? this.selection.cell : null;
36132     },
36133
36134     /**
36135      * Clears all selections.
36136      * @param {Boolean} true to prevent the gridview from being notified about the change.
36137      */
36138     clearSelections : function(preventNotify){
36139         var s = this.selection;
36140         if(s){
36141             if(preventNotify !== true){
36142                 this.grid.view.onCellDeselect(s.cell[0], s.cell[1]);
36143             }
36144             this.selection = null;
36145             this.fireEvent("selectionchange", this, null);
36146         }
36147     },
36148
36149     /**
36150      * Returns true if there is a selection.
36151      * @return {Boolean}
36152      */
36153     hasSelection : function(){
36154         return this.selection ? true : false;
36155     },
36156
36157     /** @ignore */
36158     handleMouseDown : function(e, t){
36159         var v = this.grid.getView();
36160         if(this.isLocked()){
36161             return;
36162         };
36163         var row = v.findRowIndex(t);
36164         var cell = v.findCellIndex(t);
36165         if(row !== false && cell !== false){
36166             this.select(row, cell);
36167         }
36168     },
36169
36170     /**
36171      * Selects a cell.
36172      * @param {Number} rowIndex
36173      * @param {Number} collIndex
36174      */
36175     select : function(rowIndex, colIndex, preventViewNotify, preventFocus, /*internal*/ r){
36176         if(this.fireEvent("beforecellselect", this, rowIndex, colIndex) !== false){
36177             this.clearSelections();
36178             r = r || this.grid.dataSource.getAt(rowIndex);
36179             this.selection = {
36180                 record : r,
36181                 cell : [rowIndex, colIndex]
36182             };
36183             if(!preventViewNotify){
36184                 var v = this.grid.getView();
36185                 v.onCellSelect(rowIndex, colIndex);
36186                 if(preventFocus !== true){
36187                     v.focusCell(rowIndex, colIndex);
36188                 }
36189             }
36190             this.fireEvent("cellselect", this, rowIndex, colIndex);
36191             this.fireEvent("selectionchange", this, this.selection);
36192         }
36193     },
36194
36195         //private
36196     isSelectable : function(rowIndex, colIndex, cm){
36197         return !cm.isHidden(colIndex);
36198     },
36199
36200     /** @ignore */
36201     handleKeyDown : function(e){
36202         //Roo.log('Cell Sel Model handleKeyDown');
36203         if(!e.isNavKeyPress()){
36204             return;
36205         }
36206         var g = this.grid, s = this.selection;
36207         if(!s){
36208             e.stopEvent();
36209             var cell = g.walkCells(0, 0, 1, this.isSelectable,  this);
36210             if(cell){
36211                 this.select(cell[0], cell[1]);
36212             }
36213             return;
36214         }
36215         var sm = this;
36216         var walk = function(row, col, step){
36217             return g.walkCells(row, col, step, sm.isSelectable,  sm);
36218         };
36219         var k = e.getKey(), r = s.cell[0], c = s.cell[1];
36220         var newCell;
36221
36222       
36223
36224         switch(k){
36225             case e.TAB:
36226                 // handled by onEditorKey
36227                 if (g.isEditor && g.editing) {
36228                     return;
36229                 }
36230                 if(e.shiftKey) {
36231                     newCell = walk(r, c-1, -1);
36232                 } else {
36233                     newCell = walk(r, c+1, 1);
36234                 }
36235                 break;
36236             
36237             case e.DOWN:
36238                newCell = walk(r+1, c, 1);
36239                 break;
36240             
36241             case e.UP:
36242                 newCell = walk(r-1, c, -1);
36243                 break;
36244             
36245             case e.RIGHT:
36246                 newCell = walk(r, c+1, 1);
36247                 break;
36248             
36249             case e.LEFT:
36250                 newCell = walk(r, c-1, -1);
36251                 break;
36252             
36253             case e.ENTER:
36254                 
36255                 if(g.isEditor && !g.editing){
36256                    g.startEditing(r, c);
36257                    e.stopEvent();
36258                    return;
36259                 }
36260                 
36261                 
36262              break;
36263         };
36264         if(newCell){
36265             this.select(newCell[0], newCell[1]);
36266             e.stopEvent();
36267             
36268         }
36269     },
36270
36271     acceptsNav : function(row, col, cm){
36272         return !cm.isHidden(col) && cm.isCellEditable(col, row);
36273     },
36274     /**
36275      * Selects a cell.
36276      * @param {Number} field (not used) - as it's normally used as a listener
36277      * @param {Number} e - event - fake it by using
36278      *
36279      * var e = Roo.EventObjectImpl.prototype;
36280      * e.keyCode = e.TAB
36281      *
36282      * 
36283      */
36284     onEditorKey : function(field, e){
36285         
36286         var k = e.getKey(),
36287             newCell,
36288             g = this.grid,
36289             ed = g.activeEditor,
36290             forward = false;
36291         ///Roo.log('onEditorKey' + k);
36292         
36293         
36294         if (this.enter_is_tab && k == e.ENTER) {
36295             k = e.TAB;
36296         }
36297         
36298         if(k == e.TAB){
36299             if(e.shiftKey){
36300                 newCell = g.walkCells(ed.row, ed.col-1, -1, this.acceptsNav, this);
36301             }else{
36302                 newCell = g.walkCells(ed.row, ed.col+1, 1, this.acceptsNav, this);
36303                 forward = true;
36304             }
36305             
36306             e.stopEvent();
36307             
36308         } else if(k == e.ENTER &&  !e.ctrlKey){
36309             ed.completeEdit();
36310             e.stopEvent();
36311             newCell = g.walkCells(ed.row, ed.col+1, 1, this.acceptsNav, this);
36312         
36313                 } else if(k == e.ESC){
36314             ed.cancelEdit();
36315         }
36316                 
36317         if (newCell) {
36318             var ecall = { cell : newCell, forward : forward };
36319             this.fireEvent('beforeeditnext', ecall );
36320             newCell = ecall.cell;
36321                         forward = ecall.forward;
36322         }
36323                 
36324         if(newCell){
36325             //Roo.log('next cell after edit');
36326             g.startEditing.defer(100, g, [newCell[0], newCell[1]]);
36327         } else if (forward) {
36328             // tabbed past last
36329             this.fireEvent.defer(100, this, ['tabend',this]);
36330         }
36331     }
36332 });/*
36333  * Based on:
36334  * Ext JS Library 1.1.1
36335  * Copyright(c) 2006-2007, Ext JS, LLC.
36336  *
36337  * Originally Released Under LGPL - original licence link has changed is not relivant.
36338  *
36339  * Fork - LGPL
36340  * <script type="text/javascript">
36341  */
36342  
36343 /**
36344  * @class Roo.grid.EditorGrid
36345  * @extends Roo.grid.Grid
36346  * Class for creating and editable grid.
36347  * @param {String/HTMLElement/Roo.Element} container The element into which this grid will be rendered - 
36348  * The container MUST have some type of size defined for the grid to fill. The container will be 
36349  * automatically set to position relative if it isn't already.
36350  * @param {Object} dataSource The data model to bind to
36351  * @param {Object} colModel The column model with info about this grid's columns
36352  */
36353 Roo.grid.EditorGrid = function(container, config){
36354     Roo.grid.EditorGrid.superclass.constructor.call(this, container, config);
36355     this.getGridEl().addClass("xedit-grid");
36356
36357     if(!this.selModel){
36358         this.selModel = new Roo.grid.CellSelectionModel();
36359     }
36360
36361     this.activeEditor = null;
36362
36363         this.addEvents({
36364             /**
36365              * @event beforeedit
36366              * Fires before cell editing is triggered. The edit event object has the following properties <br />
36367              * <ul style="padding:5px;padding-left:16px;">
36368              * <li>grid - This grid</li>
36369              * <li>record - The record being edited</li>
36370              * <li>field - The field name being edited</li>
36371              * <li>value - The value for the field being edited.</li>
36372              * <li>row - The grid row index</li>
36373              * <li>column - The grid column index</li>
36374              * <li>cancel - Set this to true to cancel the edit or return false from your handler.</li>
36375              * </ul>
36376              * @param {Object} e An edit event (see above for description)
36377              */
36378             "beforeedit" : true,
36379             /**
36380              * @event afteredit
36381              * Fires after a cell is edited. <br />
36382              * <ul style="padding:5px;padding-left:16px;">
36383              * <li>grid - This grid</li>
36384              * <li>record - The record being edited</li>
36385              * <li>field - The field name being edited</li>
36386              * <li>value - The value being set</li>
36387              * <li>originalValue - The original value for the field, before the edit.</li>
36388              * <li>row - The grid row index</li>
36389              * <li>column - The grid column index</li>
36390              * </ul>
36391              * @param {Object} e An edit event (see above for description)
36392              */
36393             "afteredit" : true,
36394             /**
36395              * @event validateedit
36396              * Fires after a cell is edited, but before the value is set in the record. 
36397          * You can use this to modify the value being set in the field, Return false
36398              * to cancel the change. The edit event object has the following properties <br />
36399              * <ul style="padding:5px;padding-left:16px;">
36400          * <li>editor - This editor</li>
36401              * <li>grid - This grid</li>
36402              * <li>record - The record being edited</li>
36403              * <li>field - The field name being edited</li>
36404              * <li>value - The value being set</li>
36405              * <li>originalValue - The original value for the field, before the edit.</li>
36406              * <li>row - The grid row index</li>
36407              * <li>column - The grid column index</li>
36408              * <li>cancel - Set this to true to cancel the edit or return false from your handler.</li>
36409              * </ul>
36410              * @param {Object} e An edit event (see above for description)
36411              */
36412             "validateedit" : true
36413         });
36414     this.on("bodyscroll", this.stopEditing,  this);
36415     this.on(this.clicksToEdit == 1 ? "cellclick" : "celldblclick", this.onCellDblClick,  this);
36416 };
36417
36418 Roo.extend(Roo.grid.EditorGrid, Roo.grid.Grid, {
36419     /**
36420      * @cfg {Number} clicksToEdit
36421      * The number of clicks on a cell required to display the cell's editor (defaults to 2)
36422      */
36423     clicksToEdit: 2,
36424
36425     // private
36426     isEditor : true,
36427     // private
36428     trackMouseOver: false, // causes very odd FF errors
36429
36430     onCellDblClick : function(g, row, col){
36431         this.startEditing(row, col);
36432     },
36433
36434     onEditComplete : function(ed, value, startValue){
36435         this.editing = false;
36436         this.activeEditor = null;
36437         ed.un("specialkey", this.selModel.onEditorKey, this.selModel);
36438         var r = ed.record;
36439         var field = this.colModel.getDataIndex(ed.col);
36440         var e = {
36441             grid: this,
36442             record: r,
36443             field: field,
36444             originalValue: startValue,
36445             value: value,
36446             row: ed.row,
36447             column: ed.col,
36448             cancel:false,
36449             editor: ed
36450         };
36451         var cell = Roo.get(this.view.getCell(ed.row,ed.col));
36452         cell.show();
36453           
36454         if(String(value) !== String(startValue)){
36455             
36456             if(this.fireEvent("validateedit", e) !== false && !e.cancel){
36457                 r.set(field, e.value);
36458                 // if we are dealing with a combo box..
36459                 // then we also set the 'name' colum to be the displayField
36460                 if (ed.field.displayField && ed.field.name) {
36461                     r.set(ed.field.name, ed.field.el.dom.value);
36462                 }
36463                 
36464                 delete e.cancel; //?? why!!!
36465                 this.fireEvent("afteredit", e);
36466             }
36467         } else {
36468             this.fireEvent("afteredit", e); // always fire it!
36469         }
36470         this.view.focusCell(ed.row, ed.col);
36471     },
36472
36473     /**
36474      * Starts editing the specified for the specified row/column
36475      * @param {Number} rowIndex
36476      * @param {Number} colIndex
36477      */
36478     startEditing : function(row, col){
36479         this.stopEditing();
36480         if(this.colModel.isCellEditable(col, row)){
36481             this.view.ensureVisible(row, col, true);
36482           
36483             var r = this.dataSource.getAt(row);
36484             var field = this.colModel.getDataIndex(col);
36485             var cell = Roo.get(this.view.getCell(row,col));
36486             var e = {
36487                 grid: this,
36488                 record: r,
36489                 field: field,
36490                 value: r.data[field],
36491                 row: row,
36492                 column: col,
36493                 cancel:false 
36494             };
36495             if(this.fireEvent("beforeedit", e) !== false && !e.cancel){
36496                 this.editing = true;
36497                 var ed = this.colModel.getCellEditor(col, row);
36498                 
36499                 if (!ed) {
36500                     return;
36501                 }
36502                 if(!ed.rendered){
36503                     ed.render(ed.parentEl || document.body);
36504                 }
36505                 ed.field.reset();
36506                
36507                 cell.hide();
36508                 
36509                 (function(){ // complex but required for focus issues in safari, ie and opera
36510                     ed.row = row;
36511                     ed.col = col;
36512                     ed.record = r;
36513                     ed.on("complete",   this.onEditComplete,        this,       {single: true});
36514                     ed.on("specialkey", this.selModel.onEditorKey,  this.selModel);
36515                     this.activeEditor = ed;
36516                     var v = r.data[field];
36517                     ed.startEdit(this.view.getCell(row, col), v);
36518                     // combo's with 'displayField and name set
36519                     if (ed.field.displayField && ed.field.name) {
36520                         ed.field.el.dom.value = r.data[ed.field.name];
36521                     }
36522                     
36523                     
36524                 }).defer(50, this);
36525             }
36526         }
36527     },
36528         
36529     /**
36530      * Stops any active editing
36531      */
36532     stopEditing : function(){
36533         if(this.activeEditor){
36534             this.activeEditor.completeEdit();
36535         }
36536         this.activeEditor = null;
36537     },
36538         
36539          /**
36540      * Called to get grid's drag proxy text, by default returns this.ddText.
36541      * @return {String}
36542      */
36543     getDragDropText : function(){
36544         var count = this.selModel.getSelectedCell() ? 1 : 0;
36545         return String.format(this.ddText, count, count == 1 ? '' : 's');
36546     }
36547         
36548 });/*
36549  * Based on:
36550  * Ext JS Library 1.1.1
36551  * Copyright(c) 2006-2007, Ext JS, LLC.
36552  *
36553  * Originally Released Under LGPL - original licence link has changed is not relivant.
36554  *
36555  * Fork - LGPL
36556  * <script type="text/javascript">
36557  */
36558
36559 // private - not really -- you end up using it !
36560 // This is a support class used internally by the Grid components
36561
36562 /**
36563  * @class Roo.grid.GridEditor
36564  * @extends Roo.Editor
36565  * Class for creating and editable grid elements.
36566  * @param {Object} config any settings (must include field)
36567  */
36568 Roo.grid.GridEditor = function(field, config){
36569     if (!config && field.field) {
36570         config = field;
36571         field = Roo.factory(config.field, Roo.form);
36572     }
36573     Roo.grid.GridEditor.superclass.constructor.call(this, field, config);
36574     field.monitorTab = false;
36575 };
36576
36577 Roo.extend(Roo.grid.GridEditor, Roo.Editor, {
36578     
36579     /**
36580      * @cfg {Roo.form.Field} field Field to wrap (or xtyped)
36581      */
36582     
36583     alignment: "tl-tl",
36584     autoSize: "width",
36585     hideEl : false,
36586     cls: "x-small-editor x-grid-editor",
36587     shim:false,
36588     shadow:"frame"
36589 });/*
36590  * Based on:
36591  * Ext JS Library 1.1.1
36592  * Copyright(c) 2006-2007, Ext JS, LLC.
36593  *
36594  * Originally Released Under LGPL - original licence link has changed is not relivant.
36595  *
36596  * Fork - LGPL
36597  * <script type="text/javascript">
36598  */
36599   
36600
36601   
36602 Roo.grid.PropertyRecord = Roo.data.Record.create([
36603     {name:'name',type:'string'},  'value'
36604 ]);
36605
36606
36607 Roo.grid.PropertyStore = function(grid, source){
36608     this.grid = grid;
36609     this.store = new Roo.data.Store({
36610         recordType : Roo.grid.PropertyRecord
36611     });
36612     this.store.on('update', this.onUpdate,  this);
36613     if(source){
36614         this.setSource(source);
36615     }
36616     Roo.grid.PropertyStore.superclass.constructor.call(this);
36617 };
36618
36619
36620
36621 Roo.extend(Roo.grid.PropertyStore, Roo.util.Observable, {
36622     setSource : function(o){
36623         this.source = o;
36624         this.store.removeAll();
36625         var data = [];
36626         for(var k in o){
36627             if(this.isEditableValue(o[k])){
36628                 data.push(new Roo.grid.PropertyRecord({name: k, value: o[k]}, k));
36629             }
36630         }
36631         this.store.loadRecords({records: data}, {}, true);
36632     },
36633
36634     onUpdate : function(ds, record, type){
36635         if(type == Roo.data.Record.EDIT){
36636             var v = record.data['value'];
36637             var oldValue = record.modified['value'];
36638             if(this.grid.fireEvent('beforepropertychange', this.source, record.id, v, oldValue) !== false){
36639                 this.source[record.id] = v;
36640                 record.commit();
36641                 this.grid.fireEvent('propertychange', this.source, record.id, v, oldValue);
36642             }else{
36643                 record.reject();
36644             }
36645         }
36646     },
36647
36648     getProperty : function(row){
36649        return this.store.getAt(row);
36650     },
36651
36652     isEditableValue: function(val){
36653         if(val && val instanceof Date){
36654             return true;
36655         }else if(typeof val == 'object' || typeof val == 'function'){
36656             return false;
36657         }
36658         return true;
36659     },
36660
36661     setValue : function(prop, value){
36662         this.source[prop] = value;
36663         this.store.getById(prop).set('value', value);
36664     },
36665
36666     getSource : function(){
36667         return this.source;
36668     }
36669 });
36670
36671 Roo.grid.PropertyColumnModel = function(grid, store){
36672     this.grid = grid;
36673     var g = Roo.grid;
36674     g.PropertyColumnModel.superclass.constructor.call(this, [
36675         {header: this.nameText, sortable: true, dataIndex:'name', id: 'name'},
36676         {header: this.valueText, resizable:false, dataIndex: 'value', id: 'value'}
36677     ]);
36678     this.store = store;
36679     this.bselect = Roo.DomHelper.append(document.body, {
36680         tag: 'select', style:'display:none', cls: 'x-grid-editor', children: [
36681             {tag: 'option', value: 'true', html: 'true'},
36682             {tag: 'option', value: 'false', html: 'false'}
36683         ]
36684     });
36685     Roo.id(this.bselect);
36686     var f = Roo.form;
36687     this.editors = {
36688         'date' : new g.GridEditor(new f.DateField({selectOnFocus:true})),
36689         'string' : new g.GridEditor(new f.TextField({selectOnFocus:true})),
36690         'number' : new g.GridEditor(new f.NumberField({selectOnFocus:true, style:'text-align:left;'})),
36691         'int' : new g.GridEditor(new f.NumberField({selectOnFocus:true, allowDecimals:false, style:'text-align:left;'})),
36692         'boolean' : new g.GridEditor(new f.Field({el:this.bselect,selectOnFocus:true}))
36693     };
36694     this.renderCellDelegate = this.renderCell.createDelegate(this);
36695     this.renderPropDelegate = this.renderProp.createDelegate(this);
36696 };
36697
36698 Roo.extend(Roo.grid.PropertyColumnModel, Roo.grid.ColumnModel, {
36699     
36700     
36701     nameText : 'Name',
36702     valueText : 'Value',
36703     
36704     dateFormat : 'm/j/Y',
36705     
36706     
36707     renderDate : function(dateVal){
36708         return dateVal.dateFormat(this.dateFormat);
36709     },
36710
36711     renderBool : function(bVal){
36712         return bVal ? 'true' : 'false';
36713     },
36714
36715     isCellEditable : function(colIndex, rowIndex){
36716         return colIndex == 1;
36717     },
36718
36719     getRenderer : function(col){
36720         return col == 1 ?
36721             this.renderCellDelegate : this.renderPropDelegate;
36722     },
36723
36724     renderProp : function(v){
36725         return this.getPropertyName(v);
36726     },
36727
36728     renderCell : function(val){
36729         var rv = val;
36730         if(val instanceof Date){
36731             rv = this.renderDate(val);
36732         }else if(typeof val == 'boolean'){
36733             rv = this.renderBool(val);
36734         }
36735         return Roo.util.Format.htmlEncode(rv);
36736     },
36737
36738     getPropertyName : function(name){
36739         var pn = this.grid.propertyNames;
36740         return pn && pn[name] ? pn[name] : name;
36741     },
36742
36743     getCellEditor : function(colIndex, rowIndex){
36744         var p = this.store.getProperty(rowIndex);
36745         var n = p.data['name'], val = p.data['value'];
36746         
36747         if(typeof(this.grid.customEditors[n]) == 'string'){
36748             return this.editors[this.grid.customEditors[n]];
36749         }
36750         if(typeof(this.grid.customEditors[n]) != 'undefined'){
36751             return this.grid.customEditors[n];
36752         }
36753         if(val instanceof Date){
36754             return this.editors['date'];
36755         }else if(typeof val == 'number'){
36756             return this.editors['number'];
36757         }else if(typeof val == 'boolean'){
36758             return this.editors['boolean'];
36759         }else{
36760             return this.editors['string'];
36761         }
36762     }
36763 });
36764
36765 /**
36766  * @class Roo.grid.PropertyGrid
36767  * @extends Roo.grid.EditorGrid
36768  * This class represents the  interface of a component based property grid control.
36769  * <br><br>Usage:<pre><code>
36770  var grid = new Roo.grid.PropertyGrid("my-container-id", {
36771       
36772  });
36773  // set any options
36774  grid.render();
36775  * </code></pre>
36776   
36777  * @constructor
36778  * @param {String/HTMLElement/Roo.Element} container The element into which this grid will be rendered -
36779  * The container MUST have some type of size defined for the grid to fill. The container will be
36780  * automatically set to position relative if it isn't already.
36781  * @param {Object} config A config object that sets properties on this grid.
36782  */
36783 Roo.grid.PropertyGrid = function(container, config){
36784     config = config || {};
36785     var store = new Roo.grid.PropertyStore(this);
36786     this.store = store;
36787     var cm = new Roo.grid.PropertyColumnModel(this, store);
36788     store.store.sort('name', 'ASC');
36789     Roo.grid.PropertyGrid.superclass.constructor.call(this, container, Roo.apply({
36790         ds: store.store,
36791         cm: cm,
36792         enableColLock:false,
36793         enableColumnMove:false,
36794         stripeRows:false,
36795         trackMouseOver: false,
36796         clicksToEdit:1
36797     }, config));
36798     this.getGridEl().addClass('x-props-grid');
36799     this.lastEditRow = null;
36800     this.on('columnresize', this.onColumnResize, this);
36801     this.addEvents({
36802          /**
36803              * @event beforepropertychange
36804              * Fires before a property changes (return false to stop?)
36805              * @param {Roo.grid.PropertyGrid} grid property grid? (check could be store)
36806              * @param {String} id Record Id
36807              * @param {String} newval New Value
36808          * @param {String} oldval Old Value
36809              */
36810         "beforepropertychange": true,
36811         /**
36812              * @event propertychange
36813              * Fires after a property changes
36814              * @param {Roo.grid.PropertyGrid} grid property grid? (check could be store)
36815              * @param {String} id Record Id
36816              * @param {String} newval New Value
36817          * @param {String} oldval Old Value
36818              */
36819         "propertychange": true
36820     });
36821     this.customEditors = this.customEditors || {};
36822 };
36823 Roo.extend(Roo.grid.PropertyGrid, Roo.grid.EditorGrid, {
36824     
36825      /**
36826      * @cfg {Object} customEditors map of colnames=> custom editors.
36827      * the custom editor can be one of the standard ones (date|string|number|int|boolean), or a
36828      * grid editor eg. Roo.grid.GridEditor(new Roo.form.TextArea({selectOnFocus:true})),
36829      * false disables editing of the field.
36830          */
36831     
36832       /**
36833      * @cfg {Object} propertyNames map of property Names to their displayed value
36834          */
36835     
36836     render : function(){
36837         Roo.grid.PropertyGrid.superclass.render.call(this);
36838         this.autoSize.defer(100, this);
36839     },
36840
36841     autoSize : function(){
36842         Roo.grid.PropertyGrid.superclass.autoSize.call(this);
36843         if(this.view){
36844             this.view.fitColumns();
36845         }
36846     },
36847
36848     onColumnResize : function(){
36849         this.colModel.setColumnWidth(1, this.container.getWidth(true)-this.colModel.getColumnWidth(0));
36850         this.autoSize();
36851     },
36852     /**
36853      * Sets the data for the Grid
36854      * accepts a Key => Value object of all the elements avaiable.
36855      * @param {Object} data  to appear in grid.
36856      */
36857     setSource : function(source){
36858         this.store.setSource(source);
36859         //this.autoSize();
36860     },
36861     /**
36862      * Gets all the data from the grid.
36863      * @return {Object} data  data stored in grid
36864      */
36865     getSource : function(){
36866         return this.store.getSource();
36867     }
36868 });/*
36869   
36870  * Licence LGPL
36871  
36872  */
36873  
36874 /**
36875  * @class Roo.grid.Calendar
36876  * @extends Roo.util.Grid
36877  * This class extends the Grid to provide a calendar widget
36878  * <br><br>Usage:<pre><code>
36879  var grid = new Roo.grid.Calendar("my-container-id", {
36880      ds: myDataStore,
36881      cm: myColModel,
36882      selModel: mySelectionModel,
36883      autoSizeColumns: true,
36884      monitorWindowResize: false,
36885      trackMouseOver: true
36886      eventstore : real data store..
36887  });
36888  // set any options
36889  grid.render();
36890   
36891   * @constructor
36892  * @param {String/HTMLElement/Roo.Element} container The element into which this grid will be rendered -
36893  * The container MUST have some type of size defined for the grid to fill. The container will be
36894  * automatically set to position relative if it isn't already.
36895  * @param {Object} config A config object that sets properties on this grid.
36896  */
36897 Roo.grid.Calendar = function(container, config){
36898         // initialize the container
36899         this.container = Roo.get(container);
36900         this.container.update("");
36901         this.container.setStyle("overflow", "hidden");
36902     this.container.addClass('x-grid-container');
36903
36904     this.id = this.container.id;
36905
36906     Roo.apply(this, config);
36907     // check and correct shorthanded configs
36908     
36909     var rows = [];
36910     var d =1;
36911     for (var r = 0;r < 6;r++) {
36912         
36913         rows[r]=[];
36914         for (var c =0;c < 7;c++) {
36915             rows[r][c]= '';
36916         }
36917     }
36918     if (this.eventStore) {
36919         this.eventStore= Roo.factory(this.eventStore, Roo.data);
36920         this.eventStore.on('load',this.onLoad, this);
36921         this.eventStore.on('beforeload',this.clearEvents, this);
36922          
36923     }
36924     
36925     this.dataSource = new Roo.data.Store({
36926             proxy: new Roo.data.MemoryProxy(rows),
36927             reader: new Roo.data.ArrayReader({}, [
36928                    'weekday0', 'weekday1', 'weekday2', 'weekday3', 'weekday4', 'weekday5', 'weekday6' ])
36929     });
36930
36931     this.dataSource.load();
36932     this.ds = this.dataSource;
36933     this.ds.xmodule = this.xmodule || false;
36934     
36935     
36936     var cellRender = function(v,x,r)
36937     {
36938         return String.format(
36939             '<div class="fc-day  fc-widget-content"><div>' +
36940                 '<div class="fc-event-container"></div>' +
36941                 '<div class="fc-day-number">{0}</div>'+
36942                 
36943                 '<div class="fc-day-content"><div style="position:relative"></div></div>' +
36944             '</div></div>', v);
36945     
36946     }
36947     
36948     
36949     this.colModel = new Roo.grid.ColumnModel( [
36950         {
36951             xtype: 'ColumnModel',
36952             xns: Roo.grid,
36953             dataIndex : 'weekday0',
36954             header : 'Sunday',
36955             renderer : cellRender
36956         },
36957         {
36958             xtype: 'ColumnModel',
36959             xns: Roo.grid,
36960             dataIndex : 'weekday1',
36961             header : 'Monday',
36962             renderer : cellRender
36963         },
36964         {
36965             xtype: 'ColumnModel',
36966             xns: Roo.grid,
36967             dataIndex : 'weekday2',
36968             header : 'Tuesday',
36969             renderer : cellRender
36970         },
36971         {
36972             xtype: 'ColumnModel',
36973             xns: Roo.grid,
36974             dataIndex : 'weekday3',
36975             header : 'Wednesday',
36976             renderer : cellRender
36977         },
36978         {
36979             xtype: 'ColumnModel',
36980             xns: Roo.grid,
36981             dataIndex : 'weekday4',
36982             header : 'Thursday',
36983             renderer : cellRender
36984         },
36985         {
36986             xtype: 'ColumnModel',
36987             xns: Roo.grid,
36988             dataIndex : 'weekday5',
36989             header : 'Friday',
36990             renderer : cellRender
36991         },
36992         {
36993             xtype: 'ColumnModel',
36994             xns: Roo.grid,
36995             dataIndex : 'weekday6',
36996             header : 'Saturday',
36997             renderer : cellRender
36998         }
36999     ]);
37000     this.cm = this.colModel;
37001     this.cm.xmodule = this.xmodule || false;
37002  
37003         
37004           
37005     //this.selModel = new Roo.grid.CellSelectionModel();
37006     //this.sm = this.selModel;
37007     //this.selModel.init(this);
37008     
37009     
37010     if(this.width){
37011         this.container.setWidth(this.width);
37012     }
37013
37014     if(this.height){
37015         this.container.setHeight(this.height);
37016     }
37017     /** @private */
37018         this.addEvents({
37019         // raw events
37020         /**
37021          * @event click
37022          * The raw click event for the entire grid.
37023          * @param {Roo.EventObject} e
37024          */
37025         "click" : true,
37026         /**
37027          * @event dblclick
37028          * The raw dblclick event for the entire grid.
37029          * @param {Roo.EventObject} e
37030          */
37031         "dblclick" : true,
37032         /**
37033          * @event contextmenu
37034          * The raw contextmenu event for the entire grid.
37035          * @param {Roo.EventObject} e
37036          */
37037         "contextmenu" : true,
37038         /**
37039          * @event mousedown
37040          * The raw mousedown event for the entire grid.
37041          * @param {Roo.EventObject} e
37042          */
37043         "mousedown" : true,
37044         /**
37045          * @event mouseup
37046          * The raw mouseup event for the entire grid.
37047          * @param {Roo.EventObject} e
37048          */
37049         "mouseup" : true,
37050         /**
37051          * @event mouseover
37052          * The raw mouseover event for the entire grid.
37053          * @param {Roo.EventObject} e
37054          */
37055         "mouseover" : true,
37056         /**
37057          * @event mouseout
37058          * The raw mouseout event for the entire grid.
37059          * @param {Roo.EventObject} e
37060          */
37061         "mouseout" : true,
37062         /**
37063          * @event keypress
37064          * The raw keypress event for the entire grid.
37065          * @param {Roo.EventObject} e
37066          */
37067         "keypress" : true,
37068         /**
37069          * @event keydown
37070          * The raw keydown event for the entire grid.
37071          * @param {Roo.EventObject} e
37072          */
37073         "keydown" : true,
37074
37075         // custom events
37076
37077         /**
37078          * @event cellclick
37079          * Fires when a cell is clicked
37080          * @param {Grid} this
37081          * @param {Number} rowIndex
37082          * @param {Number} columnIndex
37083          * @param {Roo.EventObject} e
37084          */
37085         "cellclick" : true,
37086         /**
37087          * @event celldblclick
37088          * Fires when a cell is double clicked
37089          * @param {Grid} this
37090          * @param {Number} rowIndex
37091          * @param {Number} columnIndex
37092          * @param {Roo.EventObject} e
37093          */
37094         "celldblclick" : true,
37095         /**
37096          * @event rowclick
37097          * Fires when a row is clicked
37098          * @param {Grid} this
37099          * @param {Number} rowIndex
37100          * @param {Roo.EventObject} e
37101          */
37102         "rowclick" : true,
37103         /**
37104          * @event rowdblclick
37105          * Fires when a row is double clicked
37106          * @param {Grid} this
37107          * @param {Number} rowIndex
37108          * @param {Roo.EventObject} e
37109          */
37110         "rowdblclick" : true,
37111         /**
37112          * @event headerclick
37113          * Fires when a header is clicked
37114          * @param {Grid} this
37115          * @param {Number} columnIndex
37116          * @param {Roo.EventObject} e
37117          */
37118         "headerclick" : true,
37119         /**
37120          * @event headerdblclick
37121          * Fires when a header cell is double clicked
37122          * @param {Grid} this
37123          * @param {Number} columnIndex
37124          * @param {Roo.EventObject} e
37125          */
37126         "headerdblclick" : true,
37127         /**
37128          * @event rowcontextmenu
37129          * Fires when a row is right clicked
37130          * @param {Grid} this
37131          * @param {Number} rowIndex
37132          * @param {Roo.EventObject} e
37133          */
37134         "rowcontextmenu" : true,
37135         /**
37136          * @event cellcontextmenu
37137          * Fires when a cell is right clicked
37138          * @param {Grid} this
37139          * @param {Number} rowIndex
37140          * @param {Number} cellIndex
37141          * @param {Roo.EventObject} e
37142          */
37143          "cellcontextmenu" : true,
37144         /**
37145          * @event headercontextmenu
37146          * Fires when a header is right clicked
37147          * @param {Grid} this
37148          * @param {Number} columnIndex
37149          * @param {Roo.EventObject} e
37150          */
37151         "headercontextmenu" : true,
37152         /**
37153          * @event bodyscroll
37154          * Fires when the body element is scrolled
37155          * @param {Number} scrollLeft
37156          * @param {Number} scrollTop
37157          */
37158         "bodyscroll" : true,
37159         /**
37160          * @event columnresize
37161          * Fires when the user resizes a column
37162          * @param {Number} columnIndex
37163          * @param {Number} newSize
37164          */
37165         "columnresize" : true,
37166         /**
37167          * @event columnmove
37168          * Fires when the user moves a column
37169          * @param {Number} oldIndex
37170          * @param {Number} newIndex
37171          */
37172         "columnmove" : true,
37173         /**
37174          * @event startdrag
37175          * Fires when row(s) start being dragged
37176          * @param {Grid} this
37177          * @param {Roo.GridDD} dd The drag drop object
37178          * @param {event} e The raw browser event
37179          */
37180         "startdrag" : true,
37181         /**
37182          * @event enddrag
37183          * Fires when a drag operation is complete
37184          * @param {Grid} this
37185          * @param {Roo.GridDD} dd The drag drop object
37186          * @param {event} e The raw browser event
37187          */
37188         "enddrag" : true,
37189         /**
37190          * @event dragdrop
37191          * Fires when dragged row(s) are dropped on a valid DD target
37192          * @param {Grid} this
37193          * @param {Roo.GridDD} dd The drag drop object
37194          * @param {String} targetId The target drag drop object
37195          * @param {event} e The raw browser event
37196          */
37197         "dragdrop" : true,
37198         /**
37199          * @event dragover
37200          * Fires while row(s) are being dragged. "targetId" is the id of the Yahoo.util.DD object the selected rows are being dragged over.
37201          * @param {Grid} this
37202          * @param {Roo.GridDD} dd The drag drop object
37203          * @param {String} targetId The target drag drop object
37204          * @param {event} e The raw browser event
37205          */
37206         "dragover" : true,
37207         /**
37208          * @event dragenter
37209          *  Fires when the dragged row(s) first cross another DD target while being dragged
37210          * @param {Grid} this
37211          * @param {Roo.GridDD} dd The drag drop object
37212          * @param {String} targetId The target drag drop object
37213          * @param {event} e The raw browser event
37214          */
37215         "dragenter" : true,
37216         /**
37217          * @event dragout
37218          * Fires when the dragged row(s) leave another DD target while being dragged
37219          * @param {Grid} this
37220          * @param {Roo.GridDD} dd The drag drop object
37221          * @param {String} targetId The target drag drop object
37222          * @param {event} e The raw browser event
37223          */
37224         "dragout" : true,
37225         /**
37226          * @event rowclass
37227          * Fires when a row is rendered, so you can change add a style to it.
37228          * @param {GridView} gridview   The grid view
37229          * @param {Object} rowcfg   contains record  rowIndex and rowClass - set rowClass to add a style.
37230          */
37231         'rowclass' : true,
37232
37233         /**
37234          * @event render
37235          * Fires when the grid is rendered
37236          * @param {Grid} grid
37237          */
37238         'render' : true,
37239             /**
37240              * @event select
37241              * Fires when a date is selected
37242              * @param {DatePicker} this
37243              * @param {Date} date The selected date
37244              */
37245         'select': true,
37246         /**
37247              * @event monthchange
37248              * Fires when the displayed month changes 
37249              * @param {DatePicker} this
37250              * @param {Date} date The selected month
37251              */
37252         'monthchange': true,
37253         /**
37254              * @event evententer
37255              * Fires when mouse over an event
37256              * @param {Calendar} this
37257              * @param {event} Event
37258              */
37259         'evententer': true,
37260         /**
37261              * @event eventleave
37262              * Fires when the mouse leaves an
37263              * @param {Calendar} this
37264              * @param {event}
37265              */
37266         'eventleave': true,
37267         /**
37268              * @event eventclick
37269              * Fires when the mouse click an
37270              * @param {Calendar} this
37271              * @param {event}
37272              */
37273         'eventclick': true,
37274         /**
37275              * @event eventrender
37276              * Fires before each cell is rendered, so you can modify the contents, like cls / title / qtip
37277              * @param {Calendar} this
37278              * @param {data} data to be modified
37279              */
37280         'eventrender': true
37281         
37282     });
37283
37284     Roo.grid.Grid.superclass.constructor.call(this);
37285     this.on('render', function() {
37286         this.view.el.addClass('x-grid-cal'); 
37287         
37288         (function() { this.setDate(new Date()); }).defer(100,this); //default today..
37289
37290     },this);
37291     
37292     if (!Roo.grid.Calendar.style) {
37293         Roo.grid.Calendar.style = Roo.util.CSS.createStyleSheet({
37294             
37295             
37296             '.x-grid-cal .x-grid-col' :  {
37297                 height: 'auto !important',
37298                 'vertical-align': 'top'
37299             },
37300             '.x-grid-cal  .fc-event-hori' : {
37301                 height: '14px'
37302             }
37303              
37304             
37305         }, Roo.id());
37306     }
37307
37308     
37309     
37310 };
37311 Roo.extend(Roo.grid.Calendar, Roo.grid.Grid, {
37312     /**
37313      * @cfg {Store} eventStore The store that loads events.
37314      */
37315     eventStore : 25,
37316
37317      
37318     activeDate : false,
37319     startDay : 0,
37320     autoWidth : true,
37321     monitorWindowResize : false,
37322
37323     
37324     resizeColumns : function() {
37325         var col = (this.view.el.getWidth() / 7) - 3;
37326         // loop through cols, and setWidth
37327         for(var i =0 ; i < 7 ; i++){
37328             this.cm.setColumnWidth(i, col);
37329         }
37330     },
37331      setDate :function(date) {
37332         
37333         Roo.log('setDate?');
37334         
37335         this.resizeColumns();
37336         var vd = this.activeDate;
37337         this.activeDate = date;
37338 //        if(vd && this.el){
37339 //            var t = date.getTime();
37340 //            if(vd.getMonth() == date.getMonth() && vd.getFullYear() == date.getFullYear()){
37341 //                Roo.log('using add remove');
37342 //                
37343 //                this.fireEvent('monthchange', this, date);
37344 //                
37345 //                this.cells.removeClass("fc-state-highlight");
37346 //                this.cells.each(function(c){
37347 //                   if(c.dateValue == t){
37348 //                       c.addClass("fc-state-highlight");
37349 //                       setTimeout(function(){
37350 //                            try{c.dom.firstChild.focus();}catch(e){}
37351 //                       }, 50);
37352 //                       return false;
37353 //                   }
37354 //                   return true;
37355 //                });
37356 //                return;
37357 //            }
37358 //        }
37359         
37360         var days = date.getDaysInMonth();
37361         
37362         var firstOfMonth = date.getFirstDateOfMonth();
37363         var startingPos = firstOfMonth.getDay()-this.startDay;
37364         
37365         if(startingPos < this.startDay){
37366             startingPos += 7;
37367         }
37368         
37369         var pm = date.add(Date.MONTH, -1);
37370         var prevStart = pm.getDaysInMonth()-startingPos;
37371 //        
37372         
37373         
37374         this.cells = this.view.el.select('.x-grid-row .x-grid-col',true);
37375         
37376         this.textNodes = this.view.el.query('.x-grid-row .x-grid-col .x-grid-cell-text');
37377         //this.cells.addClassOnOver('fc-state-hover');
37378         
37379         var cells = this.cells.elements;
37380         var textEls = this.textNodes;
37381         
37382         //Roo.each(cells, function(cell){
37383         //    cell.removeClass([ 'fc-past', 'fc-other-month', 'fc-future', 'fc-state-highlight', 'fc-state-disabled']);
37384         //});
37385         
37386         days += startingPos;
37387
37388         // convert everything to numbers so it's fast
37389         var day = 86400000;
37390         var d = (new Date(pm.getFullYear(), pm.getMonth(), prevStart)).clearTime();
37391         //Roo.log(d);
37392         //Roo.log(pm);
37393         //Roo.log(prevStart);
37394         
37395         var today = new Date().clearTime().getTime();
37396         var sel = date.clearTime().getTime();
37397         var min = this.minDate ? this.minDate.clearTime() : Number.NEGATIVE_INFINITY;
37398         var max = this.maxDate ? this.maxDate.clearTime() : Number.POSITIVE_INFINITY;
37399         var ddMatch = this.disabledDatesRE;
37400         var ddText = this.disabledDatesText;
37401         var ddays = this.disabledDays ? this.disabledDays.join("") : false;
37402         var ddaysText = this.disabledDaysText;
37403         var format = this.format;
37404         
37405         var setCellClass = function(cal, cell){
37406             
37407             //Roo.log('set Cell Class');
37408             cell.title = "";
37409             var t = d.getTime();
37410             
37411             //Roo.log(d);
37412             
37413             
37414             cell.dateValue = t;
37415             if(t == today){
37416                 cell.className += " fc-today";
37417                 cell.className += " fc-state-highlight";
37418                 cell.title = cal.todayText;
37419             }
37420             if(t == sel){
37421                 // disable highlight in other month..
37422                 cell.className += " fc-state-highlight";
37423                 
37424             }
37425             // disabling
37426             if(t < min) {
37427                 //cell.className = " fc-state-disabled";
37428                 cell.title = cal.minText;
37429                 return;
37430             }
37431             if(t > max) {
37432                 //cell.className = " fc-state-disabled";
37433                 cell.title = cal.maxText;
37434                 return;
37435             }
37436             if(ddays){
37437                 if(ddays.indexOf(d.getDay()) != -1){
37438                     // cell.title = ddaysText;
37439                    // cell.className = " fc-state-disabled";
37440                 }
37441             }
37442             if(ddMatch && format){
37443                 var fvalue = d.dateFormat(format);
37444                 if(ddMatch.test(fvalue)){
37445                     cell.title = ddText.replace("%0", fvalue);
37446                    cell.className = " fc-state-disabled";
37447                 }
37448             }
37449             
37450             if (!cell.initialClassName) {
37451                 cell.initialClassName = cell.dom.className;
37452             }
37453             
37454             cell.dom.className = cell.initialClassName  + ' ' +  cell.className;
37455         };
37456
37457         var i = 0;
37458         
37459         for(; i < startingPos; i++) {
37460             cells[i].dayName =  (++prevStart);
37461             Roo.log(textEls[i]);
37462             d.setDate(d.getDate()+1);
37463             
37464             //cells[i].className = "fc-past fc-other-month";
37465             setCellClass(this, cells[i]);
37466         }
37467         
37468         var intDay = 0;
37469         
37470         for(; i < days; i++){
37471             intDay = i - startingPos + 1;
37472             cells[i].dayName =  (intDay);
37473             d.setDate(d.getDate()+1);
37474             
37475             cells[i].className = ''; // "x-date-active";
37476             setCellClass(this, cells[i]);
37477         }
37478         var extraDays = 0;
37479         
37480         for(; i < 42; i++) {
37481             //textEls[i].innerHTML = (++extraDays);
37482             
37483             d.setDate(d.getDate()+1);
37484             cells[i].dayName = (++extraDays);
37485             cells[i].className = "fc-future fc-other-month";
37486             setCellClass(this, cells[i]);
37487         }
37488         
37489         //this.el.select('.fc-header-title h2',true).update(Date.monthNames[date.getMonth()] + " " + date.getFullYear());
37490         
37491         var totalRows = Math.ceil((date.getDaysInMonth() + date.getFirstDateOfMonth().getDay()) / 7);
37492         
37493         // this will cause all the cells to mis
37494         var rows= [];
37495         var i =0;
37496         for (var r = 0;r < 6;r++) {
37497             for (var c =0;c < 7;c++) {
37498                 this.ds.getAt(r).set('weekday' + c ,cells[i++].dayName );
37499             }    
37500         }
37501         
37502         this.cells = this.view.el.select('.x-grid-row .x-grid-col',true);
37503         for(i=0;i<cells.length;i++) {
37504             
37505             this.cells.elements[i].dayName = cells[i].dayName ;
37506             this.cells.elements[i].className = cells[i].className;
37507             this.cells.elements[i].initialClassName = cells[i].initialClassName ;
37508             this.cells.elements[i].title = cells[i].title ;
37509             this.cells.elements[i].dateValue = cells[i].dateValue ;
37510         }
37511         
37512         
37513         
37514         
37515         //this.el.select('tr.fc-week.fc-prev-last',true).removeClass('fc-last');
37516         //this.el.select('tr.fc-week.fc-next-last',true).addClass('fc-last').show();
37517         
37518         ////if(totalRows != 6){
37519             //this.el.select('tr.fc-week.fc-last',true).removeClass('fc-last').addClass('fc-next-last').hide();
37520            // this.el.select('tr.fc-week.fc-prev-last',true).addClass('fc-last');
37521        // }
37522         
37523         this.fireEvent('monthchange', this, date);
37524         
37525         
37526     },
37527  /**
37528      * Returns the grid's SelectionModel.
37529      * @return {SelectionModel}
37530      */
37531     getSelectionModel : function(){
37532         if(!this.selModel){
37533             this.selModel = new Roo.grid.CellSelectionModel();
37534         }
37535         return this.selModel;
37536     },
37537
37538     load: function() {
37539         this.eventStore.load()
37540         
37541         
37542         
37543     },
37544     
37545     findCell : function(dt) {
37546         dt = dt.clearTime().getTime();
37547         var ret = false;
37548         this.cells.each(function(c){
37549             //Roo.log("check " +c.dateValue + '?=' + dt);
37550             if(c.dateValue == dt){
37551                 ret = c;
37552                 return false;
37553             }
37554             return true;
37555         });
37556         
37557         return ret;
37558     },
37559     
37560     findCells : function(rec) {
37561         var s = rec.data.start_dt.clone().clearTime().getTime();
37562        // Roo.log(s);
37563         var e= rec.data.end_dt.clone().clearTime().getTime();
37564        // Roo.log(e);
37565         var ret = [];
37566         this.cells.each(function(c){
37567              ////Roo.log("check " +c.dateValue + '<' + e + ' > ' + s);
37568             
37569             if(c.dateValue > e){
37570                 return ;
37571             }
37572             if(c.dateValue < s){
37573                 return ;
37574             }
37575             ret.push(c);
37576         });
37577         
37578         return ret;    
37579     },
37580     
37581     findBestRow: function(cells)
37582     {
37583         var ret = 0;
37584         
37585         for (var i =0 ; i < cells.length;i++) {
37586             ret  = Math.max(cells[i].rows || 0,ret);
37587         }
37588         return ret;
37589         
37590     },
37591     
37592     
37593     addItem : function(rec)
37594     {
37595         // look for vertical location slot in
37596         var cells = this.findCells(rec);
37597         
37598         rec.row = this.findBestRow(cells);
37599         
37600         // work out the location.
37601         
37602         var crow = false;
37603         var rows = [];
37604         for(var i =0; i < cells.length; i++) {
37605             if (!crow) {
37606                 crow = {
37607                     start : cells[i],
37608                     end :  cells[i]
37609                 };
37610                 continue;
37611             }
37612             if (crow.start.getY() == cells[i].getY()) {
37613                 // on same row.
37614                 crow.end = cells[i];
37615                 continue;
37616             }
37617             // different row.
37618             rows.push(crow);
37619             crow = {
37620                 start: cells[i],
37621                 end : cells[i]
37622             };
37623             
37624         }
37625         
37626         rows.push(crow);
37627         rec.els = [];
37628         rec.rows = rows;
37629         rec.cells = cells;
37630         for (var i = 0; i < cells.length;i++) {
37631             cells[i].rows = Math.max(cells[i].rows || 0 , rec.row + 1 );
37632             
37633         }
37634         
37635         
37636     },
37637     
37638     clearEvents: function() {
37639         
37640         if (!this.eventStore.getCount()) {
37641             return;
37642         }
37643         // reset number of rows in cells.
37644         Roo.each(this.cells.elements, function(c){
37645             c.rows = 0;
37646         });
37647         
37648         this.eventStore.each(function(e) {
37649             this.clearEvent(e);
37650         },this);
37651         
37652     },
37653     
37654     clearEvent : function(ev)
37655     {
37656         if (ev.els) {
37657             Roo.each(ev.els, function(el) {
37658                 el.un('mouseenter' ,this.onEventEnter, this);
37659                 el.un('mouseleave' ,this.onEventLeave, this);
37660                 el.remove();
37661             },this);
37662             ev.els = [];
37663         }
37664     },
37665     
37666     
37667     renderEvent : function(ev,ctr) {
37668         if (!ctr) {
37669              ctr = this.view.el.select('.fc-event-container',true).first();
37670         }
37671         
37672          
37673         this.clearEvent(ev);
37674             //code
37675        
37676         
37677         
37678         ev.els = [];
37679         var cells = ev.cells;
37680         var rows = ev.rows;
37681         this.fireEvent('eventrender', this, ev);
37682         
37683         for(var i =0; i < rows.length; i++) {
37684             
37685             cls = '';
37686             if (i == 0) {
37687                 cls += ' fc-event-start';
37688             }
37689             if ((i+1) == rows.length) {
37690                 cls += ' fc-event-end';
37691             }
37692             
37693             //Roo.log(ev.data);
37694             // how many rows should it span..
37695             var cg = this.eventTmpl.append(ctr,Roo.apply({
37696                 fccls : cls
37697                 
37698             }, ev.data) , true);
37699             
37700             
37701             cg.on('mouseenter' ,this.onEventEnter, this, ev);
37702             cg.on('mouseleave' ,this.onEventLeave, this, ev);
37703             cg.on('click', this.onEventClick, this, ev);
37704             
37705             ev.els.push(cg);
37706             
37707             var sbox = rows[i].start.select('.fc-day-content',true).first().getBox();
37708             var ebox = rows[i].end.select('.fc-day-content',true).first().getBox();
37709             //Roo.log(cg);
37710              
37711             cg.setXY([sbox.x +2, sbox.y +(ev.row * 20)]);    
37712             cg.setWidth(ebox.right - sbox.x -2);
37713         }
37714     },
37715     
37716     renderEvents: function()
37717     {   
37718         // first make sure there is enough space..
37719         
37720         if (!this.eventTmpl) {
37721             this.eventTmpl = new Roo.Template(
37722                 '<div class="roo-dynamic fc-event fc-event-hori fc-event-draggable ui-draggable {fccls} {cls}"  style="position: absolute" unselectable="on">' +
37723                     '<div class="fc-event-inner">' +
37724                         '<span class="fc-event-time">{time}</span>' +
37725                         '<span class="fc-event-title" qtip="{qtip}">{title}</span>' +
37726                     '</div>' +
37727                     '<div class="ui-resizable-heandle ui-resizable-e">&nbsp;&nbsp;&nbsp;</div>' +
37728                 '</div>'
37729             );
37730                 
37731         }
37732                
37733         
37734         
37735         this.cells.each(function(c) {
37736             //Roo.log(c.select('.fc-day-content div',true).first());
37737             c.select('.fc-day-content div',true).first().setHeight(Math.max(34, (c.rows || 1) * 20));
37738         });
37739         
37740         var ctr = this.view.el.select('.fc-event-container',true).first();
37741         
37742         var cls;
37743         this.eventStore.each(function(ev){
37744             
37745             this.renderEvent(ev);
37746              
37747              
37748         }, this);
37749         this.view.layout();
37750         
37751     },
37752     
37753     onEventEnter: function (e, el,event,d) {
37754         this.fireEvent('evententer', this, el, event);
37755     },
37756     
37757     onEventLeave: function (e, el,event,d) {
37758         this.fireEvent('eventleave', this, el, event);
37759     },
37760     
37761     onEventClick: function (e, el,event,d) {
37762         this.fireEvent('eventclick', this, el, event);
37763     },
37764     
37765     onMonthChange: function () {
37766         this.store.load();
37767     },
37768     
37769     onLoad: function () {
37770         
37771         //Roo.log('calendar onload');
37772 //         
37773         if(this.eventStore.getCount() > 0){
37774             
37775            
37776             
37777             this.eventStore.each(function(d){
37778                 
37779                 
37780                 // FIXME..
37781                 var add =   d.data;
37782                 if (typeof(add.end_dt) == 'undefined')  {
37783                     Roo.log("Missing End time in calendar data: ");
37784                     Roo.log(d);
37785                     return;
37786                 }
37787                 if (typeof(add.start_dt) == 'undefined')  {
37788                     Roo.log("Missing Start time in calendar data: ");
37789                     Roo.log(d);
37790                     return;
37791                 }
37792                 add.start_dt = typeof(add.start_dt) == 'string' ? Date.parseDate(add.start_dt,'Y-m-d H:i:s') : add.start_dt,
37793                 add.end_dt = typeof(add.end_dt) == 'string' ? Date.parseDate(add.end_dt,'Y-m-d H:i:s') : add.end_dt,
37794                 add.id = add.id || d.id;
37795                 add.title = add.title || '??';
37796                 
37797                 this.addItem(d);
37798                 
37799              
37800             },this);
37801         }
37802         
37803         this.renderEvents();
37804     }
37805     
37806
37807 });
37808 /*
37809  grid : {
37810                 xtype: 'Grid',
37811                 xns: Roo.grid,
37812                 listeners : {
37813                     render : function ()
37814                     {
37815                         _this.grid = this;
37816                         
37817                         if (!this.view.el.hasClass('course-timesheet')) {
37818                             this.view.el.addClass('course-timesheet');
37819                         }
37820                         if (this.tsStyle) {
37821                             this.ds.load({});
37822                             return; 
37823                         }
37824                         Roo.log('width');
37825                         Roo.log(_this.grid.view.el.getWidth());
37826                         
37827                         
37828                         this.tsStyle =  Roo.util.CSS.createStyleSheet({
37829                             '.course-timesheet .x-grid-row' : {
37830                                 height: '80px'
37831                             },
37832                             '.x-grid-row td' : {
37833                                 'vertical-align' : 0
37834                             },
37835                             '.course-edit-link' : {
37836                                 'color' : 'blue',
37837                                 'text-overflow' : 'ellipsis',
37838                                 'overflow' : 'hidden',
37839                                 'white-space' : 'nowrap',
37840                                 'cursor' : 'pointer'
37841                             },
37842                             '.sub-link' : {
37843                                 'color' : 'green'
37844                             },
37845                             '.de-act-sup-link' : {
37846                                 'color' : 'purple',
37847                                 'text-decoration' : 'line-through'
37848                             },
37849                             '.de-act-link' : {
37850                                 'color' : 'red',
37851                                 'text-decoration' : 'line-through'
37852                             },
37853                             '.course-timesheet .course-highlight' : {
37854                                 'border-top-style': 'dashed !important',
37855                                 'border-bottom-bottom': 'dashed !important'
37856                             },
37857                             '.course-timesheet .course-item' : {
37858                                 'font-family'   : 'tahoma, arial, helvetica',
37859                                 'font-size'     : '11px',
37860                                 'overflow'      : 'hidden',
37861                                 'padding-left'  : '10px',
37862                                 'padding-right' : '10px',
37863                                 'padding-top' : '10px' 
37864                             }
37865                             
37866                         }, Roo.id());
37867                                 this.ds.load({});
37868                     }
37869                 },
37870                 autoWidth : true,
37871                 monitorWindowResize : false,
37872                 cellrenderer : function(v,x,r)
37873                 {
37874                     return v;
37875                 },
37876                 sm : {
37877                     xtype: 'CellSelectionModel',
37878                     xns: Roo.grid
37879                 },
37880                 dataSource : {
37881                     xtype: 'Store',
37882                     xns: Roo.data,
37883                     listeners : {
37884                         beforeload : function (_self, options)
37885                         {
37886                             options.params = options.params || {};
37887                             options.params._month = _this.monthField.getValue();
37888                             options.params.limit = 9999;
37889                             options.params['sort'] = 'when_dt';    
37890                             options.params['dir'] = 'ASC';    
37891                             this.proxy.loadResponse = this.loadResponse;
37892                             Roo.log("load?");
37893                             //this.addColumns();
37894                         },
37895                         load : function (_self, records, options)
37896                         {
37897                             _this.grid.view.el.select('.course-edit-link', true).on('click', function() {
37898                                 // if you click on the translation.. you can edit it...
37899                                 var el = Roo.get(this);
37900                                 var id = el.dom.getAttribute('data-id');
37901                                 var d = el.dom.getAttribute('data-date');
37902                                 var t = el.dom.getAttribute('data-time');
37903                                 //var id = this.child('span').dom.textContent;
37904                                 
37905                                 //Roo.log(this);
37906                                 Pman.Dialog.CourseCalendar.show({
37907                                     id : id,
37908                                     when_d : d,
37909                                     when_t : t,
37910                                     productitem_active : id ? 1 : 0
37911                                 }, function() {
37912                                     _this.grid.ds.load({});
37913                                 });
37914                            
37915                            });
37916                            
37917                            _this.panel.fireEvent('resize', [ '', '' ]);
37918                         }
37919                     },
37920                     loadResponse : function(o, success, response){
37921                             // this is overridden on before load..
37922                             
37923                             Roo.log("our code?");       
37924                             //Roo.log(success);
37925                             //Roo.log(response)
37926                             delete this.activeRequest;
37927                             if(!success){
37928                                 this.fireEvent("loadexception", this, o, response);
37929                                 o.request.callback.call(o.request.scope, null, o.request.arg, false);
37930                                 return;
37931                             }
37932                             var result;
37933                             try {
37934                                 result = o.reader.read(response);
37935                             }catch(e){
37936                                 Roo.log("load exception?");
37937                                 this.fireEvent("loadexception", this, o, response, e);
37938                                 o.request.callback.call(o.request.scope, null, o.request.arg, false);
37939                                 return;
37940                             }
37941                             Roo.log("ready...");        
37942                             // loop through result.records;
37943                             // and set this.tdate[date] = [] << array of records..
37944                             _this.tdata  = {};
37945                             Roo.each(result.records, function(r){
37946                                 //Roo.log(r.data);
37947                                 if(typeof(_this.tdata[r.data.when_dt.format('j')]) == 'undefined'){
37948                                     _this.tdata[r.data.when_dt.format('j')] = [];
37949                                 }
37950                                 _this.tdata[r.data.when_dt.format('j')].push(r.data);
37951                             });
37952                             
37953                             //Roo.log(_this.tdata);
37954                             
37955                             result.records = [];
37956                             result.totalRecords = 6;
37957                     
37958                             // let's generate some duumy records for the rows.
37959                             //var st = _this.dateField.getValue();
37960                             
37961                             // work out monday..
37962                             //st = st.add(Date.DAY, -1 * st.format('w'));
37963                             
37964                             var date = Date.parseDate(_this.monthField.getValue(), "Y-m-d");
37965                             
37966                             var firstOfMonth = date.getFirstDayOfMonth();
37967                             var days = date.getDaysInMonth();
37968                             var d = 1;
37969                             var firstAdded = false;
37970                             for (var i = 0; i < result.totalRecords ; i++) {
37971                                 //var d= st.add(Date.DAY, i);
37972                                 var row = {};
37973                                 var added = 0;
37974                                 for(var w = 0 ; w < 7 ; w++){
37975                                     if(!firstAdded && firstOfMonth != w){
37976                                         continue;
37977                                     }
37978                                     if(d > days){
37979                                         continue;
37980                                     }
37981                                     firstAdded = true;
37982                                     var dd = (d > 0 && d < 10) ? "0"+d : d;
37983                                     row['weekday'+w] = String.format(
37984                                                     '<span style="font-size: 16px;"><b>{0}</b></span>'+
37985                                                     '<span class="course-edit-link" style="color:blue;" data-id="0" data-date="{1}"> Add New</span>',
37986                                                     d,
37987                                                     date.format('Y-m-')+dd
37988                                                 );
37989                                     added++;
37990                                     if(typeof(_this.tdata[d]) != 'undefined'){
37991                                         Roo.each(_this.tdata[d], function(r){
37992                                             var is_sub = '';
37993                                             var deactive = '';
37994                                             var id = r.id;
37995                                             var desc = (r.productitem_id_descrip) ? r.productitem_id_descrip : '';
37996                                             if(r.parent_id*1>0){
37997                                                 is_sub = (r.productitem_id_visible*1 < 1) ? 'de-act-sup-link' :'sub-link';
37998                                                 id = r.parent_id;
37999                                             }
38000                                             if(r.productitem_id_visible*1 < 1 && r.parent_id*1 < 1){
38001                                                 deactive = 'de-act-link';
38002                                             }
38003                                             
38004                                             row['weekday'+w] += String.format(
38005                                                     '<br /><span class="course-edit-link {3} {4}" qtip="{5}" data-id="{0}">{2} - {1}</span>',
38006                                                     id, //0
38007                                                     r.product_id_name, //1
38008                                                     r.when_dt.format('h:ia'), //2
38009                                                     is_sub, //3
38010                                                     deactive, //4
38011                                                     desc // 5
38012                                             );
38013                                         });
38014                                     }
38015                                     d++;
38016                                 }
38017                                 
38018                                 // only do this if something added..
38019                                 if(added > 0){ 
38020                                     result.records.push(_this.grid.dataSource.reader.newRow(row));
38021                                 }
38022                                 
38023                                 
38024                                 // push it twice. (second one with an hour..
38025                                 
38026                             }
38027                             //Roo.log(result);
38028                             this.fireEvent("load", this, o, o.request.arg);
38029                             o.request.callback.call(o.request.scope, result, o.request.arg, true);
38030                         },
38031                     sortInfo : {field: 'when_dt', direction : 'ASC' },
38032                     proxy : {
38033                         xtype: 'HttpProxy',
38034                         xns: Roo.data,
38035                         method : 'GET',
38036                         url : baseURL + '/Roo/Shop_course.php'
38037                     },
38038                     reader : {
38039                         xtype: 'JsonReader',
38040                         xns: Roo.data,
38041                         id : 'id',
38042                         fields : [
38043                             {
38044                                 'name': 'id',
38045                                 'type': 'int'
38046                             },
38047                             {
38048                                 'name': 'when_dt',
38049                                 'type': 'string'
38050                             },
38051                             {
38052                                 'name': 'end_dt',
38053                                 'type': 'string'
38054                             },
38055                             {
38056                                 'name': 'parent_id',
38057                                 'type': 'int'
38058                             },
38059                             {
38060                                 'name': 'product_id',
38061                                 'type': 'int'
38062                             },
38063                             {
38064                                 'name': 'productitem_id',
38065                                 'type': 'int'
38066                             },
38067                             {
38068                                 'name': 'guid',
38069                                 'type': 'int'
38070                             }
38071                         ]
38072                     }
38073                 },
38074                 toolbar : {
38075                     xtype: 'Toolbar',
38076                     xns: Roo,
38077                     items : [
38078                         {
38079                             xtype: 'Button',
38080                             xns: Roo.Toolbar,
38081                             listeners : {
38082                                 click : function (_self, e)
38083                                 {
38084                                     var sd = Date.parseDate(_this.monthField.getValue(), "Y-m-d");
38085                                     sd.setMonth(sd.getMonth()-1);
38086                                     _this.monthField.setValue(sd.format('Y-m-d'));
38087                                     _this.grid.ds.load({});
38088                                 }
38089                             },
38090                             text : "Back"
38091                         },
38092                         {
38093                             xtype: 'Separator',
38094                             xns: Roo.Toolbar
38095                         },
38096                         {
38097                             xtype: 'MonthField',
38098                             xns: Roo.form,
38099                             listeners : {
38100                                 render : function (_self)
38101                                 {
38102                                     _this.monthField = _self;
38103                                    // _this.monthField.set  today
38104                                 },
38105                                 select : function (combo, date)
38106                                 {
38107                                     _this.grid.ds.load({});
38108                                 }
38109                             },
38110                             value : (function() { return new Date(); })()
38111                         },
38112                         {
38113                             xtype: 'Separator',
38114                             xns: Roo.Toolbar
38115                         },
38116                         {
38117                             xtype: 'TextItem',
38118                             xns: Roo.Toolbar,
38119                             text : "Blue: in-active, green: in-active sup-event, red: de-active, purple: de-active sup-event"
38120                         },
38121                         {
38122                             xtype: 'Fill',
38123                             xns: Roo.Toolbar
38124                         },
38125                         {
38126                             xtype: 'Button',
38127                             xns: Roo.Toolbar,
38128                             listeners : {
38129                                 click : function (_self, e)
38130                                 {
38131                                     var sd = Date.parseDate(_this.monthField.getValue(), "Y-m-d");
38132                                     sd.setMonth(sd.getMonth()+1);
38133                                     _this.monthField.setValue(sd.format('Y-m-d'));
38134                                     _this.grid.ds.load({});
38135                                 }
38136                             },
38137                             text : "Next"
38138                         }
38139                     ]
38140                 },
38141                  
38142             }
38143         };
38144         
38145         *//*
38146  * Based on:
38147  * Ext JS Library 1.1.1
38148  * Copyright(c) 2006-2007, Ext JS, LLC.
38149  *
38150  * Originally Released Under LGPL - original licence link has changed is not relivant.
38151  *
38152  * Fork - LGPL
38153  * <script type="text/javascript">
38154  */
38155  
38156 /**
38157  * @class Roo.LoadMask
38158  * A simple utility class for generically masking elements while loading data.  If the element being masked has
38159  * an underlying {@link Roo.data.Store}, the masking will be automatically synchronized with the store's loading
38160  * process and the mask element will be cached for reuse.  For all other elements, this mask will replace the
38161  * element's UpdateManager load indicator and will be destroyed after the initial load.
38162  * @constructor
38163  * Create a new LoadMask
38164  * @param {String/HTMLElement/Roo.Element} el The element or DOM node, or its id
38165  * @param {Object} config The config object
38166  */
38167 Roo.LoadMask = function(el, config){
38168     this.el = Roo.get(el);
38169     Roo.apply(this, config);
38170     if(this.store){
38171         this.store.on('beforeload', this.onBeforeLoad, this);
38172         this.store.on('load', this.onLoad, this);
38173         this.store.on('loadexception', this.onLoadException, this);
38174         this.removeMask = false;
38175     }else{
38176         var um = this.el.getUpdateManager();
38177         um.showLoadIndicator = false; // disable the default indicator
38178         um.on('beforeupdate', this.onBeforeLoad, this);
38179         um.on('update', this.onLoad, this);
38180         um.on('failure', this.onLoad, this);
38181         this.removeMask = true;
38182     }
38183 };
38184
38185 Roo.LoadMask.prototype = {
38186     /**
38187      * @cfg {Boolean} removeMask
38188      * True to create a single-use mask that is automatically destroyed after loading (useful for page loads),
38189      * False to persist the mask element reference for multiple uses (e.g., for paged data widgets).  Defaults to false.
38190      */
38191     /**
38192      * @cfg {String} msg
38193      * The text to display in a centered loading message box (defaults to 'Loading...')
38194      */
38195     msg : 'Loading...',
38196     /**
38197      * @cfg {String} msgCls
38198      * The CSS class to apply to the loading message element (defaults to "x-mask-loading")
38199      */
38200     msgCls : 'x-mask-loading',
38201
38202     /**
38203      * Read-only. True if the mask is currently disabled so that it will not be displayed (defaults to false)
38204      * @type Boolean
38205      */
38206     disabled: false,
38207
38208     /**
38209      * Disables the mask to prevent it from being displayed
38210      */
38211     disable : function(){
38212        this.disabled = true;
38213     },
38214
38215     /**
38216      * Enables the mask so that it can be displayed
38217      */
38218     enable : function(){
38219         this.disabled = false;
38220     },
38221     
38222     onLoadException : function()
38223     {
38224         Roo.log(arguments);
38225         
38226         if (typeof(arguments[3]) != 'undefined') {
38227             Roo.MessageBox.alert("Error loading",arguments[3]);
38228         } 
38229         /*
38230         try {
38231             if (this.store && typeof(this.store.reader.jsonData.errorMsg) != 'undefined') {
38232                 Roo.MessageBox.alert("Error loading",this.store.reader.jsonData.errorMsg);
38233             }   
38234         } catch(e) {
38235             
38236         }
38237         */
38238     
38239         (function() { this.el.unmask(this.removeMask); }).defer(50, this);
38240     },
38241     // private
38242     onLoad : function()
38243     {
38244         (function() { this.el.unmask(this.removeMask); }).defer(50, this);
38245     },
38246
38247     // private
38248     onBeforeLoad : function(){
38249         if(!this.disabled){
38250             (function() { this.el.mask(this.msg, this.msgCls); }).defer(50, this);
38251         }
38252     },
38253
38254     // private
38255     destroy : function(){
38256         if(this.store){
38257             this.store.un('beforeload', this.onBeforeLoad, this);
38258             this.store.un('load', this.onLoad, this);
38259             this.store.un('loadexception', this.onLoadException, this);
38260         }else{
38261             var um = this.el.getUpdateManager();
38262             um.un('beforeupdate', this.onBeforeLoad, this);
38263             um.un('update', this.onLoad, this);
38264             um.un('failure', this.onLoad, this);
38265         }
38266     }
38267 };/*
38268  * Based on:
38269  * Ext JS Library 1.1.1
38270  * Copyright(c) 2006-2007, Ext JS, LLC.
38271  *
38272  * Originally Released Under LGPL - original licence link has changed is not relivant.
38273  *
38274  * Fork - LGPL
38275  * <script type="text/javascript">
38276  */
38277
38278
38279 /**
38280  * @class Roo.XTemplate
38281  * @extends Roo.Template
38282  * Provides a template that can have nested templates for loops or conditionals. The syntax is:
38283 <pre><code>
38284 var t = new Roo.XTemplate(
38285         '&lt;select name="{name}"&gt;',
38286                 '&lt;tpl for="options"&gt;&lt;option value="{value:trim}"&gt;{text:ellipsis(10)}&lt;/option&gt;&lt;/tpl&gt;',
38287         '&lt;/select&gt;'
38288 );
38289  
38290 // then append, applying the master template values
38291  </code></pre>
38292  *
38293  * Supported features:
38294  *
38295  *  Tags:
38296
38297 <pre><code>
38298       {a_variable} - output encoded.
38299       {a_variable.format:("Y-m-d")} - call a method on the variable
38300       {a_variable:raw} - unencoded output
38301       {a_variable:toFixed(1,2)} - Roo.util.Format."toFixed"
38302       {a_variable:this.method_on_template(...)} - call a method on the template object.
38303  
38304 </code></pre>
38305  *  The tpl tag:
38306 <pre><code>
38307         &lt;tpl for="a_variable or condition.."&gt;&lt;/tpl&gt;
38308         &lt;tpl if="a_variable or condition"&gt;&lt;/tpl&gt;
38309         &lt;tpl exec="some javascript"&gt;&lt;/tpl&gt;
38310         &lt;tpl name="named_template"&gt;&lt;/tpl&gt; (experimental)
38311   
38312         &lt;tpl for="."&gt;&lt;/tpl&gt; - just iterate the property..
38313         &lt;tpl for=".."&gt;&lt;/tpl&gt; - iterates with the parent (probably the template) 
38314 </code></pre>
38315  *      
38316  */
38317 Roo.XTemplate = function()
38318 {
38319     Roo.XTemplate.superclass.constructor.apply(this, arguments);
38320     if (this.html) {
38321         this.compile();
38322     }
38323 };
38324
38325
38326 Roo.extend(Roo.XTemplate, Roo.Template, {
38327
38328     /**
38329      * The various sub templates
38330      */
38331     tpls : false,
38332     /**
38333      *
38334      * basic tag replacing syntax
38335      * WORD:WORD()
38336      *
38337      * // you can fake an object call by doing this
38338      *  x.t:(test,tesT) 
38339      * 
38340      */
38341     re : /\{([\w-\.]+)(?:\:([\w\.]*)(?:\((.*?)?\))?)?\}/g,
38342
38343     /**
38344      * compile the template
38345      *
38346      * This is not recursive, so I'm not sure how nested templates are really going to be handled..
38347      *
38348      */
38349     compile: function()
38350     {
38351         var s = this.html;
38352      
38353         s = ['<tpl>', s, '</tpl>'].join('');
38354     
38355         var re     = /<tpl\b[^>]*>((?:(?=([^<]+))\2|<(?!tpl\b[^>]*>))*?)<\/tpl>/,
38356             nameRe = /^<tpl\b[^>]*?for="(.*?)"/,
38357             ifRe   = /^<tpl\b[^>]*?if="(.*?)"/,
38358             execRe = /^<tpl\b[^>]*?exec="(.*?)"/,
38359             namedRe = /^<tpl\b[^>]*?name="(\w+)"/,  // named templates..
38360             m,
38361             id     = 0,
38362             tpls   = [];
38363     
38364         while(true == !!(m = s.match(re))){
38365             var forMatch   = m[0].match(nameRe),
38366                 ifMatch   = m[0].match(ifRe),
38367                 execMatch   = m[0].match(execRe),
38368                 namedMatch   = m[0].match(namedRe),
38369                 
38370                 exp  = null, 
38371                 fn   = null,
38372                 exec = null,
38373                 name = forMatch && forMatch[1] ? forMatch[1] : '';
38374                 
38375             if (ifMatch) {
38376                 // if - puts fn into test..
38377                 exp = ifMatch && ifMatch[1] ? ifMatch[1] : null;
38378                 if(exp){
38379                    fn = new Function('values', 'parent', 'with(values){ return '+(Roo.util.Format.htmlDecode(exp))+'; }');
38380                 }
38381             }
38382             
38383             if (execMatch) {
38384                 // exec - calls a function... returns empty if true is  returned.
38385                 exp = execMatch && execMatch[1] ? execMatch[1] : null;
38386                 if(exp){
38387                    exec = new Function('values', 'parent', 'with(values){ '+(Roo.util.Format.htmlDecode(exp))+'; }');
38388                 }
38389             }
38390             
38391             
38392             if (name) {
38393                 // for = 
38394                 switch(name){
38395                     case '.':  name = new Function('values', 'parent', 'with(values){ return values; }'); break;
38396                     case '..': name = new Function('values', 'parent', 'with(values){ return parent; }'); break;
38397                     default:   name = new Function('values', 'parent', 'with(values){ return '+name+'; }');
38398                 }
38399             }
38400             var uid = namedMatch ? namedMatch[1] : id;
38401             
38402             
38403             tpls.push({
38404                 id:     namedMatch ? namedMatch[1] : id,
38405                 target: name,
38406                 exec:   exec,
38407                 test:   fn,
38408                 body:   m[1] || ''
38409             });
38410             if (namedMatch) {
38411                 s = s.replace(m[0], '');
38412             } else { 
38413                 s = s.replace(m[0], '{xtpl'+ id + '}');
38414             }
38415             ++id;
38416         }
38417         this.tpls = [];
38418         for(var i = tpls.length-1; i >= 0; --i){
38419             this.compileTpl(tpls[i]);
38420             this.tpls[tpls[i].id] = tpls[i];
38421         }
38422         this.master = tpls[tpls.length-1];
38423         return this;
38424     },
38425     /**
38426      * same as applyTemplate, except it's done to one of the subTemplates
38427      * when using named templates, you can do:
38428      *
38429      * var str = pl.applySubTemplate('your-name', values);
38430      *
38431      * 
38432      * @param {Number} id of the template
38433      * @param {Object} values to apply to template
38434      * @param {Object} parent (normaly the instance of this object)
38435      */
38436     applySubTemplate : function(id, values, parent)
38437     {
38438         
38439         
38440         var t = this.tpls[id];
38441         
38442         
38443         try { 
38444             if(t.test && !t.test.call(this, values, parent)){
38445                 return '';
38446             }
38447         } catch(e) {
38448             Roo.log("Xtemplate.applySubTemplate 'test': Exception thrown");
38449             Roo.log(e.toString());
38450             Roo.log(t.test);
38451             return ''
38452         }
38453         try { 
38454             
38455             if(t.exec && t.exec.call(this, values, parent)){
38456                 return '';
38457             }
38458         } catch(e) {
38459             Roo.log("Xtemplate.applySubTemplate 'exec': Exception thrown");
38460             Roo.log(e.toString());
38461             Roo.log(t.exec);
38462             return ''
38463         }
38464         try {
38465             var vs = t.target ? t.target.call(this, values, parent) : values;
38466             parent = t.target ? values : parent;
38467             if(t.target && vs instanceof Array){
38468                 var buf = [];
38469                 for(var i = 0, len = vs.length; i < len; i++){
38470                     buf[buf.length] = t.compiled.call(this, vs[i], parent);
38471                 }
38472                 return buf.join('');
38473             }
38474             return t.compiled.call(this, vs, parent);
38475         } catch (e) {
38476             Roo.log("Xtemplate.applySubTemplate : Exception thrown");
38477             Roo.log(e.toString());
38478             Roo.log(t.compiled);
38479             return '';
38480         }
38481     },
38482
38483     compileTpl : function(tpl)
38484     {
38485         var fm = Roo.util.Format;
38486         var useF = this.disableFormats !== true;
38487         var sep = Roo.isGecko ? "+" : ",";
38488         var undef = function(str) {
38489             Roo.log("Property not found :"  + str);
38490             return '';
38491         };
38492         
38493         var fn = function(m, name, format, args)
38494         {
38495             //Roo.log(arguments);
38496             args = args ? args.replace(/\\'/g,"'") : args;
38497             //["{TEST:(a,b,c)}", "TEST", "", "a,b,c", 0, "{TEST:(a,b,c)}"]
38498             if (typeof(format) == 'undefined') {
38499                 format= 'htmlEncode';
38500             }
38501             if (format == 'raw' ) {
38502                 format = false;
38503             }
38504             
38505             if(name.substr(0, 4) == 'xtpl'){
38506                 return "'"+ sep +'this.applySubTemplate('+name.substr(4)+', values, parent)'+sep+"'";
38507             }
38508             
38509             // build an array of options to determine if value is undefined..
38510             
38511             // basically get 'xxxx.yyyy' then do
38512             // (typeof(xxxx) == 'undefined' || typeof(xxx.yyyy) == 'undefined') ?
38513             //    (function () { Roo.log("Property not found"); return ''; })() :
38514             //    ......
38515             
38516             var udef_ar = [];
38517             var lookfor = '';
38518             Roo.each(name.split('.'), function(st) {
38519                 lookfor += (lookfor.length ? '.': '') + st;
38520                 udef_ar.push(  "(typeof(" + lookfor + ") == 'undefined')"  );
38521             });
38522             
38523             var udef_st = '((' + udef_ar.join(" || ") +") ? undef('" + name + "') : "; // .. needs )
38524             
38525             
38526             if(format && useF){
38527                 
38528                 args = args ? ',' + args : "";
38529                  
38530                 if(format.substr(0, 5) != "this."){
38531                     format = "fm." + format + '(';
38532                 }else{
38533                     format = 'this.call("'+ format.substr(5) + '", ';
38534                     args = ", values";
38535                 }
38536                 
38537                 return "'"+ sep +   udef_st   +    format + name + args + "))"+sep+"'";
38538             }
38539              
38540             if (args.length) {
38541                 // called with xxyx.yuu:(test,test)
38542                 // change to ()
38543                 return "'"+ sep + udef_st  + name + '(' +  args + "))"+sep+"'";
38544             }
38545             // raw.. - :raw modifier..
38546             return "'"+ sep + udef_st  + name + ")"+sep+"'";
38547             
38548         };
38549         var body;
38550         // branched to use + in gecko and [].join() in others
38551         if(Roo.isGecko){
38552             body = "tpl.compiled = function(values, parent){  with(values) { return '" +
38553                    tpl.body.replace(/(\r\n|\n)/g, '\\n').replace(/'/g, "\\'").replace(this.re, fn) +
38554                     "';};};";
38555         }else{
38556             body = ["tpl.compiled = function(values, parent){  with (values) { return ['"];
38557             body.push(tpl.body.replace(/(\r\n|\n)/g,
38558                             '\\n').replace(/'/g, "\\'").replace(this.re, fn));
38559             body.push("'].join('');};};");
38560             body = body.join('');
38561         }
38562         
38563         Roo.debug && Roo.log(body.replace(/\\n/,'\n'));
38564        
38565         /** eval:var:tpl eval:var:fm eval:var:useF eval:var:undef  */
38566         eval(body);
38567         
38568         return this;
38569     },
38570
38571     applyTemplate : function(values){
38572         return this.master.compiled.call(this, values, {});
38573         //var s = this.subs;
38574     },
38575
38576     apply : function(){
38577         return this.applyTemplate.apply(this, arguments);
38578     }
38579
38580  });
38581
38582 Roo.XTemplate.from = function(el){
38583     el = Roo.getDom(el);
38584     return new Roo.XTemplate(el.value || el.innerHTML);
38585 };