roojs-ui.js
[roojs1] / roojs-ui-debug.js
1 /*
2  * Based on:
3  * Ext JS Library 1.1.1
4  * Copyright(c) 2006-2007, Ext JS, LLC.
5  *
6  * Originally Released Under LGPL - original licence link has changed is not relivant.
7  *
8  * Fork - LGPL
9  * <script type="text/javascript">
10  */
11
12
13 /**
14  * @class Roo.data.SortTypes
15  * @static
16  * Defines the default sorting (casting?) comparison functions used when sorting data.
17  */
18 Roo.data.SortTypes = {
19     /**
20      * Default sort that does nothing
21      * @param {Mixed} s The value being converted
22      * @return {Mixed} The comparison value
23      */
24     none : function(s){
25         return s;
26     },
27     
28     /**
29      * The regular expression used to strip tags
30      * @type {RegExp}
31      * @property
32      */
33     stripTagsRE : /<\/?[^>]+>/gi,
34     
35     /**
36      * Strips all HTML tags to sort on text only
37      * @param {Mixed} s The value being converted
38      * @return {String} The comparison value
39      */
40     asText : function(s){
41         return String(s).replace(this.stripTagsRE, "");
42     },
43     
44     /**
45      * Strips all HTML tags to sort on text only - Case insensitive
46      * @param {Mixed} s The value being converted
47      * @return {String} The comparison value
48      */
49     asUCText : function(s){
50         return String(s).toUpperCase().replace(this.stripTagsRE, "");
51     },
52     
53     /**
54      * Case insensitive string
55      * @param {Mixed} s The value being converted
56      * @return {String} The comparison value
57      */
58     asUCString : function(s) {
59         return String(s).toUpperCase();
60     },
61     
62     /**
63      * Date sorting
64      * @param {Mixed} s The value being converted
65      * @return {Number} The comparison value
66      */
67     asDate : function(s) {
68         if(!s){
69             return 0;
70         }
71         if(s instanceof Date){
72             return s.getTime();
73         }
74         return Date.parse(String(s));
75     },
76     
77     /**
78      * Float sorting
79      * @param {Mixed} s The value being converted
80      * @return {Float} The comparison value
81      */
82     asFloat : function(s) {
83         var val = parseFloat(String(s).replace(/,/g, ""));
84         if(isNaN(val)) {
85             val = 0;
86         }
87         return val;
88     },
89     
90     /**
91      * Integer sorting
92      * @param {Mixed} s The value being converted
93      * @return {Number} The comparison value
94      */
95     asInt : function(s) {
96         var val = parseInt(String(s).replace(/,/g, ""));
97         if(isNaN(val)) {
98             val = 0;
99         }
100         return val;
101     }
102 };/*
103  * Based on:
104  * Ext JS Library 1.1.1
105  * Copyright(c) 2006-2007, Ext JS, LLC.
106  *
107  * Originally Released Under LGPL - original licence link has changed is not relivant.
108  *
109  * Fork - LGPL
110  * <script type="text/javascript">
111  */
112
113 /**
114 * @class Roo.data.Record
115  * Instances of this class encapsulate both record <em>definition</em> information, and record
116  * <em>value</em> information for use in {@link Roo.data.Store} objects, or any code which needs
117  * to access Records cached in an {@link Roo.data.Store} object.<br>
118  * <p>
119  * Constructors for this class are generated by passing an Array of field definition objects to {@link #create}.
120  * Instances are usually only created by {@link Roo.data.Reader} implementations when processing unformatted data
121  * objects.<br>
122  * <p>
123  * Record objects generated by this constructor inherit all the methods of Roo.data.Record listed below.
124  * @constructor
125  * This constructor should not be used to create Record objects. Instead, use the constructor generated by
126  * {@link #create}. The parameters are the same.
127  * @param {Array} data An associative Array of data values keyed by the field name.
128  * @param {Object} id (Optional) The id of the record. This id should be unique, and is used by the
129  * {@link Roo.data.Store} object which owns the Record to index its collection of Records. If
130  * not specified an integer id is generated.
131  */
132 Roo.data.Record = function(data, id){
133     this.id = (id || id === 0) ? id : ++Roo.data.Record.AUTO_ID;
134     this.data = data;
135 };
136
137 /**
138  * Generate a constructor for a specific record layout.
139  * @param {Array} o An Array of field definition objects which specify field names, and optionally,
140  * data types, and a mapping for an {@link Roo.data.Reader} to extract the field's value from a data object.
141  * Each field definition object may contain the following properties: <ul>
142  * <li><b>name</b> : String<p style="margin-left:1em">The name by which the field is referenced within the Record. This is referenced by,
143  * for example the <em>dataIndex</em> property in column definition objects passed to {@link Roo.grid.ColumnModel}</p></li>
144  * <li><b>mapping</b> : String<p style="margin-left:1em">(Optional) A path specification for use by the {@link Roo.data.Reader} implementation
145  * that is creating the Record to access the data value from the data object. If an {@link Roo.data.JsonReader}
146  * is being used, then this is a string containing the javascript expression to reference the data relative to 
147  * the record item's root. If an {@link Roo.data.XmlReader} is being used, this is an {@link Roo.DomQuery} path
148  * to the data item relative to the record element. If the mapping expression is the same as the field name,
149  * this may be omitted.</p></li>
150  * <li><b>type</b> : String<p style="margin-left:1em">(Optional) The data type for conversion to displayable value. Possible values are
151  * <ul><li>auto (Default, implies no conversion)</li>
152  * <li>string</li>
153  * <li>int</li>
154  * <li>float</li>
155  * <li>boolean</li>
156  * <li>date</li></ul></p></li>
157  * <li><b>sortType</b> : Mixed<p style="margin-left:1em">(Optional) A member of {@link Roo.data.SortTypes}.</p></li>
158  * <li><b>sortDir</b> : String<p style="margin-left:1em">(Optional) Initial direction to sort. "ASC" or "DESC"</p></li>
159  * <li><b>convert</b> : Function<p style="margin-left:1em">(Optional) A function which converts the value provided
160  * by the Reader into an object that will be stored in the Record. It is passed the
161  * following parameters:<ul>
162  * <li><b>v</b> : Mixed<p style="margin-left:1em">The data value as read by the Reader.</p></li>
163  * </ul></p></li>
164  * <li><b>dateFormat</b> : String<p style="margin-left:1em">(Optional) A format String for the Date.parseDate function.</p></li>
165  * </ul>
166  * <br>usage:<br><pre><code>
167 var TopicRecord = Roo.data.Record.create(
168     {name: 'title', mapping: 'topic_title'},
169     {name: 'author', mapping: 'username'},
170     {name: 'totalPosts', mapping: 'topic_replies', type: 'int'},
171     {name: 'lastPost', mapping: 'post_time', type: 'date'},
172     {name: 'lastPoster', mapping: 'user2'},
173     {name: 'excerpt', mapping: 'post_text'}
174 );
175
176 var myNewRecord = new TopicRecord({
177     title: 'Do my job please',
178     author: 'noobie',
179     totalPosts: 1,
180     lastPost: new Date(),
181     lastPoster: 'Animal',
182     excerpt: 'No way dude!'
183 });
184 myStore.add(myNewRecord);
185 </code></pre>
186  * @method create
187  * @static
188  */
189 Roo.data.Record.create = function(o){
190     var f = function(){
191         f.superclass.constructor.apply(this, arguments);
192     };
193     Roo.extend(f, Roo.data.Record);
194     var p = f.prototype;
195     p.fields = new Roo.util.MixedCollection(false, function(field){
196         return field.name;
197     });
198     for(var i = 0, len = o.length; i < len; i++){
199         p.fields.add(new Roo.data.Field(o[i]));
200     }
201     f.getField = function(name){
202         return p.fields.get(name);  
203     };
204     return f;
205 };
206
207 Roo.data.Record.AUTO_ID = 1000;
208 Roo.data.Record.EDIT = 'edit';
209 Roo.data.Record.REJECT = 'reject';
210 Roo.data.Record.COMMIT = 'commit';
211
212 Roo.data.Record.prototype = {
213     /**
214      * Readonly flag - true if this record has been modified.
215      * @type Boolean
216      */
217     dirty : false,
218     editing : false,
219     error: null,
220     modified: null,
221
222     // private
223     join : function(store){
224         this.store = store;
225     },
226
227     /**
228      * Set the named field to the specified value.
229      * @param {String} name The name of the field to set.
230      * @param {Object} value The value to set the field to.
231      */
232     set : function(name, value){
233         if(this.data[name] == value){
234             return;
235         }
236         this.dirty = true;
237         if(!this.modified){
238             this.modified = {};
239         }
240         if(typeof this.modified[name] == 'undefined'){
241             this.modified[name] = this.data[name];
242         }
243         this.data[name] = value;
244         if(!this.editing && this.store){
245             this.store.afterEdit(this);
246         }       
247     },
248
249     /**
250      * Get the value of the named field.
251      * @param {String} name The name of the field to get the value of.
252      * @return {Object} The value of the field.
253      */
254     get : function(name){
255         return this.data[name]; 
256     },
257
258     // private
259     beginEdit : function(){
260         this.editing = true;
261         this.modified = {}; 
262     },
263
264     // private
265     cancelEdit : function(){
266         this.editing = false;
267         delete this.modified;
268     },
269
270     // private
271     endEdit : function(){
272         this.editing = false;
273         if(this.dirty && this.store){
274             this.store.afterEdit(this);
275         }
276     },
277
278     /**
279      * Usually called by the {@link Roo.data.Store} which owns the Record.
280      * Rejects all changes made to the Record since either creation, or the last commit operation.
281      * Modified fields are reverted to their original values.
282      * <p>
283      * Developers should subscribe to the {@link Roo.data.Store#update} event to have their code notified
284      * of reject operations.
285      */
286     reject : function(){
287         var m = this.modified;
288         for(var n in m){
289             if(typeof m[n] != "function"){
290                 this.data[n] = m[n];
291             }
292         }
293         this.dirty = false;
294         delete this.modified;
295         this.editing = false;
296         if(this.store){
297             this.store.afterReject(this);
298         }
299     },
300
301     /**
302      * Usually called by the {@link Roo.data.Store} which owns the Record.
303      * Commits all changes made to the Record since either creation, or the last commit operation.
304      * <p>
305      * Developers should subscribe to the {@link Roo.data.Store#update} event to have their code notified
306      * of commit operations.
307      */
308     commit : function(){
309         this.dirty = false;
310         delete this.modified;
311         this.editing = false;
312         if(this.store){
313             this.store.afterCommit(this);
314         }
315     },
316
317     // private
318     hasError : function(){
319         return this.error != null;
320     },
321
322     // private
323     clearError : function(){
324         this.error = null;
325     },
326
327     /**
328      * Creates a copy of this record.
329      * @param {String} id (optional) A new record id if you don't want to use this record's id
330      * @return {Record}
331      */
332     copy : function(newId) {
333         return new this.constructor(Roo.apply({}, this.data), newId || this.id);
334     }
335 };/*
336  * Based on:
337  * Ext JS Library 1.1.1
338  * Copyright(c) 2006-2007, Ext JS, LLC.
339  *
340  * Originally Released Under LGPL - original licence link has changed is not relivant.
341  *
342  * Fork - LGPL
343  * <script type="text/javascript">
344  */
345
346
347
348 /**
349  * @class Roo.data.Store
350  * @extends Roo.util.Observable
351  * The Store class encapsulates a client side cache of {@link Roo.data.Record} objects which provide input data
352  * for widgets such as the Roo.grid.Grid, or the Roo.form.ComboBox.<br>
353  * <p>
354  * A Store object uses an implementation of {@link Roo.data.DataProxy} to access a data object unless you call loadData() directly and pass in your data. The Store object
355  * has no knowledge of the format of the data returned by the Proxy.<br>
356  * <p>
357  * A Store object uses its configured implementation of {@link Roo.data.DataReader} to create {@link Roo.data.Record}
358  * instances from the data object. These records are cached and made available through accessor functions.
359  * @constructor
360  * Creates a new Store.
361  * @param {Object} config A config object containing the objects needed for the Store to access data,
362  * and read the data into Records.
363  */
364 Roo.data.Store = function(config){
365     this.data = new Roo.util.MixedCollection(false);
366     this.data.getKey = function(o){
367         return o.id;
368     };
369     this.baseParams = {};
370     // private
371     this.paramNames = {
372         "start" : "start",
373         "limit" : "limit",
374         "sort" : "sort",
375         "dir" : "dir",
376         "multisort" : "_multisort"
377     };
378
379     if(config && config.data){
380         this.inlineData = config.data;
381         delete config.data;
382     }
383
384     Roo.apply(this, config);
385     
386     if(this.reader){ // reader passed
387         this.reader = Roo.factory(this.reader, Roo.data);
388         this.reader.xmodule = this.xmodule || false;
389         if(!this.recordType){
390             this.recordType = this.reader.recordType;
391         }
392         if(this.reader.onMetaChange){
393             this.reader.onMetaChange = this.onMetaChange.createDelegate(this);
394         }
395     }
396
397     if(this.recordType){
398         this.fields = this.recordType.prototype.fields;
399     }
400     this.modified = [];
401
402     this.addEvents({
403         /**
404          * @event datachanged
405          * Fires when the data cache has changed, and a widget which is using this Store
406          * as a Record cache should refresh its view.
407          * @param {Store} this
408          */
409         datachanged : true,
410         /**
411          * @event metachange
412          * Fires when this store's reader provides new metadata (fields). This is currently only support for JsonReaders.
413          * @param {Store} this
414          * @param {Object} meta The JSON metadata
415          */
416         metachange : true,
417         /**
418          * @event add
419          * Fires when Records have been added to the Store
420          * @param {Store} this
421          * @param {Roo.data.Record[]} records The array of Records added
422          * @param {Number} index The index at which the record(s) were added
423          */
424         add : true,
425         /**
426          * @event remove
427          * Fires when a Record has been removed from the Store
428          * @param {Store} this
429          * @param {Roo.data.Record} record The Record that was removed
430          * @param {Number} index The index at which the record was removed
431          */
432         remove : true,
433         /**
434          * @event update
435          * Fires when a Record has been updated
436          * @param {Store} this
437          * @param {Roo.data.Record} record The Record that was updated
438          * @param {String} operation The update operation being performed.  Value may be one of:
439          * <pre><code>
440  Roo.data.Record.EDIT
441  Roo.data.Record.REJECT
442  Roo.data.Record.COMMIT
443          * </code></pre>
444          */
445         update : true,
446         /**
447          * @event clear
448          * Fires when the data cache has been cleared.
449          * @param {Store} this
450          */
451         clear : true,
452         /**
453          * @event beforeload
454          * Fires before a request is made for a new data object.  If the beforeload handler returns false
455          * the load action will be canceled.
456          * @param {Store} this
457          * @param {Object} options The loading options that were specified (see {@link #load} for details)
458          */
459         beforeload : true,
460         /**
461          * @event beforeloadadd
462          * Fires after a new set of Records has been loaded.
463          * @param {Store} this
464          * @param {Roo.data.Record[]} records The Records that were loaded
465          * @param {Object} options The loading options that were specified (see {@link #load} for details)
466          */
467         beforeloadadd : true,
468         /**
469          * @event load
470          * Fires after a new set of Records has been loaded, before they are added to the store.
471          * @param {Store} this
472          * @param {Roo.data.Record[]} records The Records that were loaded
473          * @param {Object} options The loading options that were specified (see {@link #load} for details)
474          * @params {Object} return from reader
475          */
476         load : true,
477         /**
478          * @event loadexception
479          * Fires if an exception occurs in the Proxy during loading.
480          * Called with the signature of the Proxy's "loadexception" event.
481          * If you return Json { data: [] , success: false, .... } then this will be thrown with the following args
482          * 
483          * @param {Proxy} 
484          * @param {Object} return from JsonData.reader() - success, totalRecords, records
485          * @param {Object} load options 
486          * @param {Object} jsonData from your request (normally this contains the Exception)
487          */
488         loadexception : true
489     });
490     
491     if(this.proxy){
492         this.proxy = Roo.factory(this.proxy, Roo.data);
493         this.proxy.xmodule = this.xmodule || false;
494         this.relayEvents(this.proxy,  ["loadexception"]);
495     }
496     this.sortToggle = {};
497     this.sortOrder = []; // array of order of sorting - updated by grid if multisort is enabled.
498
499     Roo.data.Store.superclass.constructor.call(this);
500
501     if(this.inlineData){
502         this.loadData(this.inlineData);
503         delete this.inlineData;
504     }
505 };
506
507 Roo.extend(Roo.data.Store, Roo.util.Observable, {
508      /**
509     * @cfg {boolean} isLocal   flag if data is locally available (and can be always looked up
510     * without a remote query - used by combo/forms at present.
511     */
512     
513     /**
514     * @cfg {Roo.data.DataProxy} proxy [required] The Proxy object which provides access to a data object.
515     */
516     /**
517     * @cfg {Array} data Inline data to be loaded when the store is initialized.
518     */
519     /**
520     * @cfg {Roo.data.DataReader} reader [required]  The Reader object which processes the data object and returns
521     * an Array of Roo.data.record objects which are cached keyed by their <em>id</em> property.
522     */
523     /**
524     * @cfg {Object} baseParams An object containing properties which are to be sent as parameters
525     * on any HTTP request
526     */
527     /**
528     * @cfg {Object} sortInfo A config object in the format: {field: "fieldName", direction: "ASC|DESC"}
529     */
530     /**
531     * @cfg {Boolean} multiSort enable multi column sorting (sort is based on the order of columns, remote only at present)
532     */
533     multiSort: false,
534     /**
535     * @cfg {boolean} remoteSort True if sorting is to be handled by requesting the Proxy to provide a refreshed
536     * version of the data object in sorted order, as opposed to sorting the Record cache in place (defaults to false).
537     */
538     remoteSort : false,
539
540     /**
541     * @cfg {boolean} pruneModifiedRecords True to clear all modified record information each time the store is
542      * loaded or when a record is removed. (defaults to false).
543     */
544     pruneModifiedRecords : false,
545
546     // private
547     lastOptions : null,
548
549     /**
550      * Add Records to the Store and fires the add event.
551      * @param {Roo.data.Record[]} records An Array of Roo.data.Record objects to add to the cache.
552      */
553     add : function(records){
554         records = [].concat(records);
555         for(var i = 0, len = records.length; i < len; i++){
556             records[i].join(this);
557         }
558         var index = this.data.length;
559         this.data.addAll(records);
560         this.fireEvent("add", this, records, index);
561     },
562
563     /**
564      * Remove a Record from the Store and fires the remove event.
565      * @param {Ext.data.Record} record The Roo.data.Record object to remove from the cache.
566      */
567     remove : function(record){
568         var index = this.data.indexOf(record);
569         this.data.removeAt(index);
570  
571         if(this.pruneModifiedRecords){
572             this.modified.remove(record);
573         }
574         this.fireEvent("remove", this, record, index);
575     },
576
577     /**
578      * Remove all Records from the Store and fires the clear event.
579      */
580     removeAll : function(){
581         this.data.clear();
582         if(this.pruneModifiedRecords){
583             this.modified = [];
584         }
585         this.fireEvent("clear", this);
586     },
587
588     /**
589      * Inserts Records to the Store at the given index and fires the add event.
590      * @param {Number} index The start index at which to insert the passed Records.
591      * @param {Roo.data.Record[]} records An Array of Roo.data.Record objects to add to the cache.
592      */
593     insert : function(index, records){
594         records = [].concat(records);
595         for(var i = 0, len = records.length; i < len; i++){
596             this.data.insert(index, records[i]);
597             records[i].join(this);
598         }
599         this.fireEvent("add", this, records, index);
600     },
601
602     /**
603      * Get the index within the cache of the passed Record.
604      * @param {Roo.data.Record} record The Roo.data.Record object to to find.
605      * @return {Number} The index of the passed Record. Returns -1 if not found.
606      */
607     indexOf : function(record){
608         return this.data.indexOf(record);
609     },
610
611     /**
612      * Get the index within the cache of the Record with the passed id.
613      * @param {String} id The id of the Record to find.
614      * @return {Number} The index of the Record. Returns -1 if not found.
615      */
616     indexOfId : function(id){
617         return this.data.indexOfKey(id);
618     },
619
620     /**
621      * Get the Record with the specified id.
622      * @param {String} id The id of the Record to find.
623      * @return {Roo.data.Record} The Record with the passed id. Returns undefined if not found.
624      */
625     getById : function(id){
626         return this.data.key(id);
627     },
628
629     /**
630      * Get the Record at the specified index.
631      * @param {Number} index The index of the Record to find.
632      * @return {Roo.data.Record} The Record at the passed index. Returns undefined if not found.
633      */
634     getAt : function(index){
635         return this.data.itemAt(index);
636     },
637
638     /**
639      * Returns a range of Records between specified indices.
640      * @param {Number} startIndex (optional) The starting index (defaults to 0)
641      * @param {Number} endIndex (optional) The ending index (defaults to the last Record in the Store)
642      * @return {Roo.data.Record[]} An array of Records
643      */
644     getRange : function(start, end){
645         return this.data.getRange(start, end);
646     },
647
648     // private
649     storeOptions : function(o){
650         o = Roo.apply({}, o);
651         delete o.callback;
652         delete o.scope;
653         this.lastOptions = o;
654     },
655
656     /**
657      * Loads the Record cache from the configured Proxy using the configured Reader.
658      * <p>
659      * If using remote paging, then the first load call must specify the <em>start</em>
660      * and <em>limit</em> properties in the options.params property to establish the initial
661      * position within the dataset, and the number of Records to cache on each read from the Proxy.
662      * <p>
663      * <strong>It is important to note that for remote data sources, loading is asynchronous,
664      * and this call will return before the new data has been loaded. Perform any post-processing
665      * in a callback function, or in a "load" event handler.</strong>
666      * <p>
667      * @param {Object} options An object containing properties which control loading options:<ul>
668      * <li>params {Object} An object containing properties to pass as HTTP parameters to a remote data source.</li>
669      * <li>params.data {Object} if you are using a MemoryProxy / JsonReader, use this as the data to load stuff..
670      * <pre>
671                 {
672                     data : data,  // array of key=>value data like JsonReader
673                     total : data.length,
674                     success : true
675                     
676                 }
677         </pre>
678             }.</li>
679      * <li>callback {Function} A function to be called after the Records have been loaded. The callback is
680      * passed the following arguments:<ul>
681      * <li>r : Roo.data.Record[]</li>
682      * <li>options: Options object from the load call</li>
683      * <li>success: Boolean success indicator</li></ul></li>
684      * <li>scope {Object} Scope with which to call the callback (defaults to the Store object)</li>
685      * <li>add {Boolean} indicator to append loaded records rather than replace the current cache.</li>
686      * </ul>
687      */
688     load : function(options){
689         options = options || {};
690         if(this.fireEvent("beforeload", this, options) !== false){
691             this.storeOptions(options);
692             var p = Roo.apply(options.params || {}, this.baseParams);
693             // if meta was not loaded from remote source.. try requesting it.
694             if (!this.reader.metaFromRemote) {
695                 p._requestMeta = 1;
696             }
697             if(this.sortInfo && this.remoteSort){
698                 var pn = this.paramNames;
699                 p[pn["sort"]] = this.sortInfo.field;
700                 p[pn["dir"]] = this.sortInfo.direction;
701             }
702             if (this.multiSort) {
703                 var pn = this.paramNames;
704                 p[pn["multisort"]] = Roo.encode( { sort : this.sortToggle, order: this.sortOrder });
705             }
706             
707             this.proxy.load(p, this.reader, this.loadRecords, this, options);
708         }
709     },
710
711     /**
712      * Reloads the Record cache from the configured Proxy using the configured Reader and
713      * the options from the last load operation performed.
714      * @param {Object} options (optional) An object containing properties which may override the options
715      * used in the last load operation. See {@link #load} for details (defaults to null, in which case
716      * the most recently used options are reused).
717      */
718     reload : function(options){
719         this.load(Roo.applyIf(options||{}, this.lastOptions));
720     },
721
722     // private
723     // Called as a callback by the Reader during a load operation.
724     loadRecords : function(o, options, success){
725          
726         if(!o){
727             if(success !== false){
728                 this.fireEvent("load", this, [], options, o);
729             }
730             if(options.callback){
731                 options.callback.call(options.scope || this, [], options, false);
732             }
733             return;
734         }
735         // if data returned failure - throw an exception.
736         if (o.success === false) {
737             // show a message if no listener is registered.
738             if (!this.hasListener('loadexception') && typeof(o.raw.errorMsg) != 'undefined') {
739                     Roo.MessageBox.alert("Error loading",o.raw.errorMsg);
740             }
741             // loadmask wil be hooked into this..
742             this.fireEvent("loadexception", this, o, options, o.raw.errorMsg);
743             return;
744         }
745         var r = o.records, t = o.totalRecords || r.length;
746         
747         this.fireEvent("beforeloadadd", this, r, options, o);
748         
749         if(!options || options.add !== true){
750             if(this.pruneModifiedRecords){
751                 this.modified = [];
752             }
753             for(var i = 0, len = r.length; i < len; i++){
754                 r[i].join(this);
755             }
756             if(this.snapshot){
757                 this.data = this.snapshot;
758                 delete this.snapshot;
759             }
760             this.data.clear();
761             this.data.addAll(r);
762             this.totalLength = t;
763             this.applySort();
764             this.fireEvent("datachanged", this);
765         }else{
766             this.totalLength = Math.max(t, this.data.length+r.length);
767             this.add(r);
768         }
769         
770         if(this.parent && !Roo.isIOS && !this.useNativeIOS && this.parent.emptyTitle.length) {
771                 
772             var e = new Roo.data.Record({});
773
774             e.set(this.parent.displayField, this.parent.emptyTitle);
775             e.set(this.parent.valueField, '');
776
777             this.insert(0, e);
778         }
779             
780         this.fireEvent("load", this, r, options, o);
781         if(options.callback){
782             options.callback.call(options.scope || this, r, options, true);
783         }
784     },
785
786
787     /**
788      * Loads data from a passed data block. A Reader which understands the format of the data
789      * must have been configured in the constructor.
790      * @param {Object} data The data block from which to read the Records.  The format of the data expected
791      * is dependent on the type of Reader that is configured and should correspond to that Reader's readRecords parameter.
792      * @param {Boolean} append (Optional) True to append the new Records rather than replace the existing cache.
793      */
794     loadData : function(o, append){
795         var r = this.reader.readRecords(o);
796         this.loadRecords(r, {add: append}, true);
797     },
798     
799      /**
800      * using 'cn' the nested child reader read the child array into it's child stores.
801      * @param {Object} rec The record with a 'children array
802      */
803     loadDataFromChildren : function(rec)
804     {
805         this.loadData(this.reader.toLoadData(rec));
806     },
807     
808
809     /**
810      * Gets the number of cached records.
811      * <p>
812      * <em>If using paging, this may not be the total size of the dataset. If the data object
813      * used by the Reader contains the dataset size, then the getTotalCount() function returns
814      * the data set size</em>
815      */
816     getCount : function(){
817         return this.data.length || 0;
818     },
819
820     /**
821      * Gets the total number of records in the dataset as returned by the server.
822      * <p>
823      * <em>If using paging, for this to be accurate, the data object used by the Reader must contain
824      * the dataset size</em>
825      */
826     getTotalCount : function(){
827         return this.totalLength || 0;
828     },
829
830     /**
831      * Returns the sort state of the Store as an object with two properties:
832      * <pre><code>
833  field {String} The name of the field by which the Records are sorted
834  direction {String} The sort order, "ASC" or "DESC"
835      * </code></pre>
836      */
837     getSortState : function(){
838         return this.sortInfo;
839     },
840
841     // private
842     applySort : function(){
843         if(this.sortInfo && !this.remoteSort){
844             var s = this.sortInfo, f = s.field;
845             var st = this.fields.get(f).sortType;
846             var fn = function(r1, r2){
847                 var v1 = st(r1.data[f]), v2 = st(r2.data[f]);
848                 return v1 > v2 ? 1 : (v1 < v2 ? -1 : 0);
849             };
850             this.data.sort(s.direction, fn);
851             if(this.snapshot && this.snapshot != this.data){
852                 this.snapshot.sort(s.direction, fn);
853             }
854         }
855     },
856
857     /**
858      * Sets the default sort column and order to be used by the next load operation.
859      * @param {String} fieldName The name of the field to sort by.
860      * @param {String} dir (optional) The sort order, "ASC" or "DESC" (defaults to "ASC")
861      */
862     setDefaultSort : function(field, dir){
863         this.sortInfo = {field: field, direction: dir ? dir.toUpperCase() : "ASC"};
864     },
865
866     /**
867      * Sort the Records.
868      * If remote sorting is used, the sort is performed on the server, and the cache is
869      * reloaded. If local sorting is used, the cache is sorted internally.
870      * @param {String} fieldName The name of the field to sort by.
871      * @param {String} dir (optional) The sort order, "ASC" or "DESC" (defaults to "ASC")
872      */
873     sort : function(fieldName, dir){
874         var f = this.fields.get(fieldName);
875         if(!dir){
876             this.sortToggle[f.name] = this.sortToggle[f.name] || f.sortDir;
877             
878             if(this.multiSort || (this.sortInfo && this.sortInfo.field == f.name) ){ // toggle sort dir
879                 dir = (this.sortToggle[f.name] || "ASC").toggle("ASC", "DESC");
880             }else{
881                 dir = f.sortDir;
882             }
883         }
884         this.sortToggle[f.name] = dir;
885         this.sortInfo = {field: f.name, direction: dir};
886         if(!this.remoteSort){
887             this.applySort();
888             this.fireEvent("datachanged", this);
889         }else{
890             this.load(this.lastOptions);
891         }
892     },
893
894     /**
895      * Calls the specified function for each of the Records in the cache.
896      * @param {Function} fn The function to call. The Record is passed as the first parameter.
897      * Returning <em>false</em> aborts and exits the iteration.
898      * @param {Object} scope (optional) The scope in which to call the function (defaults to the Record).
899      */
900     each : function(fn, scope){
901         this.data.each(fn, scope);
902     },
903
904     /**
905      * Gets all records modified since the last commit.  Modified records are persisted across load operations
906      * (e.g., during paging).
907      * @return {Roo.data.Record[]} An array of Records containing outstanding modifications.
908      */
909     getModifiedRecords : function(){
910         return this.modified;
911     },
912
913     // private
914     createFilterFn : function(property, value, anyMatch){
915         if(!value.exec){ // not a regex
916             value = String(value);
917             if(value.length == 0){
918                 return false;
919             }
920             value = new RegExp((anyMatch === true ? '' : '^') + Roo.escapeRe(value), "i");
921         }
922         return function(r){
923             return value.test(r.data[property]);
924         };
925     },
926
927     /**
928      * Sums the value of <i>property</i> for each record between start and end and returns the result.
929      * @param {String} property A field on your records
930      * @param {Number} start The record index to start at (defaults to 0)
931      * @param {Number} end The last record index to include (defaults to length - 1)
932      * @return {Number} The sum
933      */
934     sum : function(property, start, end){
935         var rs = this.data.items, v = 0;
936         start = start || 0;
937         end = (end || end === 0) ? end : rs.length-1;
938
939         for(var i = start; i <= end; i++){
940             v += (rs[i].data[property] || 0);
941         }
942         return v;
943     },
944
945     /**
946      * Filter the records by a specified property.
947      * @param {String} field A field on your records
948      * @param {String/RegExp} value Either a string that the field
949      * should start with or a RegExp to test against the field
950      * @param {Boolean} anyMatch True to match any part not just the beginning
951      */
952     filter : function(property, value, anyMatch){
953         var fn = this.createFilterFn(property, value, anyMatch);
954         return fn ? this.filterBy(fn) : this.clearFilter();
955     },
956
957     /**
958      * Filter by a function. The specified function will be called with each
959      * record in this data source. If the function returns true the record is included,
960      * otherwise it is filtered.
961      * @param {Function} fn The function to be called, it will receive 2 args (record, id)
962      * @param {Object} scope (optional) The scope of the function (defaults to this)
963      */
964     filterBy : function(fn, scope){
965         this.snapshot = this.snapshot || this.data;
966         this.data = this.queryBy(fn, scope||this);
967         this.fireEvent("datachanged", this);
968     },
969
970     /**
971      * Query the records by a specified property.
972      * @param {String} field A field on your records
973      * @param {String/RegExp} value Either a string that the field
974      * should start with or a RegExp to test against the field
975      * @param {Boolean} anyMatch True to match any part not just the beginning
976      * @return {MixedCollection} Returns an Roo.util.MixedCollection of the matched records
977      */
978     query : function(property, value, anyMatch){
979         var fn = this.createFilterFn(property, value, anyMatch);
980         return fn ? this.queryBy(fn) : this.data.clone();
981     },
982
983     /**
984      * Query by a function. The specified function will be called with each
985      * record in this data source. If the function returns true the record is included
986      * in the results.
987      * @param {Function} fn The function to be called, it will receive 2 args (record, id)
988      * @param {Object} scope (optional) The scope of the function (defaults to this)
989       @return {MixedCollection} Returns an Roo.util.MixedCollection of the matched records
990      **/
991     queryBy : function(fn, scope){
992         var data = this.snapshot || this.data;
993         return data.filterBy(fn, scope||this);
994     },
995
996     /**
997      * Collects unique values for a particular dataIndex from this store.
998      * @param {String} dataIndex The property to collect
999      * @param {Boolean} allowNull (optional) Pass true to allow null, undefined or empty string values
1000      * @param {Boolean} bypassFilter (optional) Pass true to collect from all records, even ones which are filtered
1001      * @return {Array} An array of the unique values
1002      **/
1003     collect : function(dataIndex, allowNull, bypassFilter){
1004         var d = (bypassFilter === true && this.snapshot) ?
1005                 this.snapshot.items : this.data.items;
1006         var v, sv, r = [], l = {};
1007         for(var i = 0, len = d.length; i < len; i++){
1008             v = d[i].data[dataIndex];
1009             sv = String(v);
1010             if((allowNull || !Roo.isEmpty(v)) && !l[sv]){
1011                 l[sv] = true;
1012                 r[r.length] = v;
1013             }
1014         }
1015         return r;
1016     },
1017
1018     /**
1019      * Revert to a view of the Record cache with no filtering applied.
1020      * @param {Boolean} suppressEvent If true the filter is cleared silently without notifying listeners
1021      */
1022     clearFilter : function(suppressEvent){
1023         if(this.snapshot && this.snapshot != this.data){
1024             this.data = this.snapshot;
1025             delete this.snapshot;
1026             if(suppressEvent !== true){
1027                 this.fireEvent("datachanged", this);
1028             }
1029         }
1030     },
1031
1032     // private
1033     afterEdit : function(record){
1034         if(this.modified.indexOf(record) == -1){
1035             this.modified.push(record);
1036         }
1037         this.fireEvent("update", this, record, Roo.data.Record.EDIT);
1038     },
1039     
1040     // private
1041     afterReject : function(record){
1042         this.modified.remove(record);
1043         this.fireEvent("update", this, record, Roo.data.Record.REJECT);
1044     },
1045
1046     // private
1047     afterCommit : function(record){
1048         this.modified.remove(record);
1049         this.fireEvent("update", this, record, Roo.data.Record.COMMIT);
1050     },
1051
1052     /**
1053      * Commit all Records with outstanding changes. To handle updates for changes, subscribe to the
1054      * Store's "update" event, and perform updating when the third parameter is Roo.data.Record.COMMIT.
1055      */
1056     commitChanges : function(){
1057         var m = this.modified.slice(0);
1058         this.modified = [];
1059         for(var i = 0, len = m.length; i < len; i++){
1060             m[i].commit();
1061         }
1062     },
1063
1064     /**
1065      * Cancel outstanding changes on all changed records.
1066      */
1067     rejectChanges : function(){
1068         var m = this.modified.slice(0);
1069         this.modified = [];
1070         for(var i = 0, len = m.length; i < len; i++){
1071             m[i].reject();
1072         }
1073     },
1074
1075     onMetaChange : function(meta, rtype, o){
1076         this.recordType = rtype;
1077         this.fields = rtype.prototype.fields;
1078         delete this.snapshot;
1079         this.sortInfo = meta.sortInfo || this.sortInfo;
1080         this.modified = [];
1081         this.fireEvent('metachange', this, this.reader.meta);
1082     },
1083     
1084     moveIndex : function(data, type)
1085     {
1086         var index = this.indexOf(data);
1087         
1088         var newIndex = index + type;
1089         
1090         this.remove(data);
1091         
1092         this.insert(newIndex, data);
1093         
1094     }
1095 });/*
1096  * Based on:
1097  * Ext JS Library 1.1.1
1098  * Copyright(c) 2006-2007, Ext JS, LLC.
1099  *
1100  * Originally Released Under LGPL - original licence link has changed is not relivant.
1101  *
1102  * Fork - LGPL
1103  * <script type="text/javascript">
1104  */
1105
1106 /**
1107  * @class Roo.data.SimpleStore
1108  * @extends Roo.data.Store
1109  * Small helper class to make creating Stores from Array data easier.
1110  * @cfg {Number} id The array index of the record id. Leave blank to auto generate ids.
1111  * @cfg {Array} fields An array of field definition objects, or field name strings.
1112  * @cfg {Object} an existing reader (eg. copied from another store)
1113  * @cfg {Array} data The multi-dimensional array of data
1114  * @cfg {Roo.data.DataProxy} proxy [not-required]  
1115  * @cfg {Roo.data.Reader} reader  [not-required] 
1116  * @constructor
1117  * @param {Object} config
1118  */
1119 Roo.data.SimpleStore = function(config)
1120 {
1121     Roo.data.SimpleStore.superclass.constructor.call(this, {
1122         isLocal : true,
1123         reader: typeof(config.reader) != 'undefined' ? config.reader : new Roo.data.ArrayReader({
1124                 id: config.id
1125             },
1126             Roo.data.Record.create(config.fields)
1127         ),
1128         proxy : new Roo.data.MemoryProxy(config.data)
1129     });
1130     this.load();
1131 };
1132 Roo.extend(Roo.data.SimpleStore, Roo.data.Store);/*
1133  * Based on:
1134  * Ext JS Library 1.1.1
1135  * Copyright(c) 2006-2007, Ext JS, LLC.
1136  *
1137  * Originally Released Under LGPL - original licence link has changed is not relivant.
1138  *
1139  * Fork - LGPL
1140  * <script type="text/javascript">
1141  */
1142
1143 /**
1144 /**
1145  * @extends Roo.data.Store
1146  * @class Roo.data.JsonStore
1147  * Small helper class to make creating Stores for JSON data easier. <br/>
1148 <pre><code>
1149 var store = new Roo.data.JsonStore({
1150     url: 'get-images.php',
1151     root: 'images',
1152     fields: ['name', 'url', {name:'size', type: 'float'}, {name:'lastmod', type:'date'}]
1153 });
1154 </code></pre>
1155  * <b>Note: Although they are not listed, this class inherits all of the config options of Store,
1156  * JsonReader and HttpProxy (unless inline data is provided).</b>
1157  * @cfg {Array} fields An array of field definition objects, or field name strings.
1158  * @constructor
1159  * @param {Object} config
1160  */
1161 Roo.data.JsonStore = function(c){
1162     Roo.data.JsonStore.superclass.constructor.call(this, Roo.apply(c, {
1163         proxy: !c.data ? new Roo.data.HttpProxy({url: c.url}) : undefined,
1164         reader: new Roo.data.JsonReader(c, c.fields)
1165     }));
1166 };
1167 Roo.extend(Roo.data.JsonStore, Roo.data.Store);/*
1168  * Based on:
1169  * Ext JS Library 1.1.1
1170  * Copyright(c) 2006-2007, Ext JS, LLC.
1171  *
1172  * Originally Released Under LGPL - original licence link has changed is not relivant.
1173  *
1174  * Fork - LGPL
1175  * <script type="text/javascript">
1176  */
1177
1178  
1179 Roo.data.Field = function(config){
1180     if(typeof config == "string"){
1181         config = {name: config};
1182     }
1183     Roo.apply(this, config);
1184     
1185     if(!this.type){
1186         this.type = "auto";
1187     }
1188     
1189     var st = Roo.data.SortTypes;
1190     // named sortTypes are supported, here we look them up
1191     if(typeof this.sortType == "string"){
1192         this.sortType = st[this.sortType];
1193     }
1194     
1195     // set default sortType for strings and dates
1196     if(!this.sortType){
1197         switch(this.type){
1198             case "string":
1199                 this.sortType = st.asUCString;
1200                 break;
1201             case "date":
1202                 this.sortType = st.asDate;
1203                 break;
1204             default:
1205                 this.sortType = st.none;
1206         }
1207     }
1208
1209     // define once
1210     var stripRe = /[\$,%]/g;
1211
1212     // prebuilt conversion function for this field, instead of
1213     // switching every time we're reading a value
1214     if(!this.convert){
1215         var cv, dateFormat = this.dateFormat;
1216         switch(this.type){
1217             case "":
1218             case "auto":
1219             case undefined:
1220                 cv = function(v){ return v; };
1221                 break;
1222             case "string":
1223                 cv = function(v){ return (v === undefined || v === null) ? '' : String(v); };
1224                 break;
1225             case "int":
1226                 cv = function(v){
1227                     return v !== undefined && v !== null && v !== '' ?
1228                            parseInt(String(v).replace(stripRe, ""), 10) : '';
1229                     };
1230                 break;
1231             case "float":
1232                 cv = function(v){
1233                     return v !== undefined && v !== null && v !== '' ?
1234                            parseFloat(String(v).replace(stripRe, ""), 10) : ''; 
1235                     };
1236                 break;
1237             case "bool":
1238             case "boolean":
1239                 cv = function(v){ return v === true || v === "true" || v == 1; };
1240                 break;
1241             case "date":
1242                 cv = function(v){
1243                     if(!v){
1244                         return '';
1245                     }
1246                     if(v instanceof Date){
1247                         return v;
1248                     }
1249                     if(dateFormat){
1250                         if(dateFormat == "timestamp"){
1251                             return new Date(v*1000);
1252                         }
1253                         return Date.parseDate(v, dateFormat);
1254                     }
1255                     var parsed = Date.parse(v);
1256                     return parsed ? new Date(parsed) : null;
1257                 };
1258              break;
1259             
1260         }
1261         this.convert = cv;
1262     }
1263 };
1264
1265 Roo.data.Field.prototype = {
1266     dateFormat: null,
1267     defaultValue: "",
1268     mapping: null,
1269     sortType : null,
1270     sortDir : "ASC"
1271 };/*
1272  * Based on:
1273  * Ext JS Library 1.1.1
1274  * Copyright(c) 2006-2007, Ext JS, LLC.
1275  *
1276  * Originally Released Under LGPL - original licence link has changed is not relivant.
1277  *
1278  * Fork - LGPL
1279  * <script type="text/javascript">
1280  */
1281  
1282 // Base class for reading structured data from a data source.  This class is intended to be
1283 // extended (see ArrayReader, JsonReader and XmlReader) and should not be created directly.
1284
1285 /**
1286  * @class Roo.data.DataReader
1287  * @abstract
1288  * Base class for reading structured data from a data source.  This class is intended to be
1289  * extended (see {Roo.data.ArrayReader}, {Roo.data.JsonReader} and {Roo.data.XmlReader}) and should not be created directly.
1290  */
1291
1292 Roo.data.DataReader = function(meta, recordType){
1293     
1294     this.meta = meta;
1295     
1296     this.recordType = recordType instanceof Array ? 
1297         Roo.data.Record.create(recordType) : recordType;
1298 };
1299
1300 Roo.data.DataReader.prototype = {
1301     
1302     
1303     readerType : 'Data',
1304      /**
1305      * Create an empty record
1306      * @param {Object} data (optional) - overlay some values
1307      * @return {Roo.data.Record} record created.
1308      */
1309     newRow :  function(d) {
1310         var da =  {};
1311         this.recordType.prototype.fields.each(function(c) {
1312             switch( c.type) {
1313                 case 'int' : da[c.name] = 0; break;
1314                 case 'date' : da[c.name] = new Date(); break;
1315                 case 'float' : da[c.name] = 0.0; break;
1316                 case 'boolean' : da[c.name] = false; break;
1317                 default : da[c.name] = ""; break;
1318             }
1319             
1320         });
1321         return new this.recordType(Roo.apply(da, d));
1322     }
1323     
1324     
1325 };/*
1326  * Based on:
1327  * Ext JS Library 1.1.1
1328  * Copyright(c) 2006-2007, Ext JS, LLC.
1329  *
1330  * Originally Released Under LGPL - original licence link has changed is not relivant.
1331  *
1332  * Fork - LGPL
1333  * <script type="text/javascript">
1334  */
1335
1336 /**
1337  * @class Roo.data.DataProxy
1338  * @extends Roo.util.Observable
1339  * @abstract
1340  * This class is an abstract base class for implementations which provide retrieval of
1341  * unformatted data objects.<br>
1342  * <p>
1343  * DataProxy implementations are usually used in conjunction with an implementation of Roo.data.DataReader
1344  * (of the appropriate type which knows how to parse the data object) to provide a block of
1345  * {@link Roo.data.Records} to an {@link Roo.data.Store}.<br>
1346  * <p>
1347  * Custom implementations must implement the load method as described in
1348  * {@link Roo.data.HttpProxy#load}.
1349  */
1350 Roo.data.DataProxy = function(){
1351     this.addEvents({
1352         /**
1353          * @event beforeload
1354          * Fires before a network request is made to retrieve a data object.
1355          * @param {Object} This DataProxy object.
1356          * @param {Object} params The params parameter to the load function.
1357          */
1358         beforeload : true,
1359         /**
1360          * @event load
1361          * Fires before the load method's callback is called.
1362          * @param {Object} This DataProxy object.
1363          * @param {Object} o The data object.
1364          * @param {Object} arg The callback argument object passed to the load function.
1365          */
1366         load : true,
1367         /**
1368          * @event loadexception
1369          * Fires if an Exception occurs during data retrieval.
1370          * @param {Object} This DataProxy object.
1371          * @param {Object} o The data object.
1372          * @param {Object} arg The callback argument object passed to the load function.
1373          * @param {Object} e The Exception.
1374          */
1375         loadexception : true
1376     });
1377     Roo.data.DataProxy.superclass.constructor.call(this);
1378 };
1379
1380 Roo.extend(Roo.data.DataProxy, Roo.util.Observable);
1381
1382     /**
1383      * @cfg {void} listeners (Not available) Constructor blocks listeners from being set
1384      */
1385 /*
1386  * Based on:
1387  * Ext JS Library 1.1.1
1388  * Copyright(c) 2006-2007, Ext JS, LLC.
1389  *
1390  * Originally Released Under LGPL - original licence link has changed is not relivant.
1391  *
1392  * Fork - LGPL
1393  * <script type="text/javascript">
1394  */
1395 /**
1396  * @class Roo.data.MemoryProxy
1397  * An implementation of Roo.data.DataProxy that simply passes the data specified in its constructor
1398  * to the Reader when its load method is called.
1399  * @constructor
1400  * @param {Object} data The data object which the Reader uses to construct a block of Roo.data.Records.
1401  */
1402 Roo.data.MemoryProxy = function(data){
1403     if (data.data) {
1404         data = data.data;
1405     }
1406     Roo.data.MemoryProxy.superclass.constructor.call(this);
1407     this.data = data;
1408 };
1409
1410 Roo.extend(Roo.data.MemoryProxy, Roo.data.DataProxy, {
1411     
1412     /**
1413      * Load data from the requested source (in this case an in-memory
1414      * data object passed to the constructor), read the data object into
1415      * a block of Roo.data.Records using the passed Roo.data.DataReader implementation, and
1416      * process that block using the passed callback.
1417      * @param {Object} params This parameter is not used by the MemoryProxy class.
1418      * @param {Roo.data.DataReader} reader The Reader object which converts the data
1419      * object into a block of Roo.data.Records.
1420      * @param {Function} callback The function into which to pass the block of Roo.data.records.
1421      * The function must be passed <ul>
1422      * <li>The Record block object</li>
1423      * <li>The "arg" argument from the load function</li>
1424      * <li>A boolean success indicator</li>
1425      * </ul>
1426      * @param {Object} scope The scope in which to call the callback
1427      * @param {Object} arg An optional argument which is passed to the callback as its second parameter.
1428      */
1429     load : function(params, reader, callback, scope, arg){
1430         params = params || {};
1431         var result;
1432         try {
1433             result = reader.readRecords(params.data ? params.data :this.data);
1434         }catch(e){
1435             this.fireEvent("loadexception", this, arg, null, e);
1436             callback.call(scope, null, arg, false);
1437             return;
1438         }
1439         callback.call(scope, result, arg, true);
1440     },
1441     
1442     // private
1443     update : function(params, records){
1444         
1445     }
1446 });/*
1447  * Based on:
1448  * Ext JS Library 1.1.1
1449  * Copyright(c) 2006-2007, Ext JS, LLC.
1450  *
1451  * Originally Released Under LGPL - original licence link has changed is not relivant.
1452  *
1453  * Fork - LGPL
1454  * <script type="text/javascript">
1455  */
1456 /**
1457  * @class Roo.data.HttpProxy
1458  * @extends Roo.data.DataProxy
1459  * An implementation of {@link Roo.data.DataProxy} that reads a data object from an {@link Roo.data.Connection} object
1460  * configured to reference a certain URL.<br><br>
1461  * <p>
1462  * <em>Note that this class cannot be used to retrieve data from a domain other than the domain
1463  * from which the running page was served.<br><br>
1464  * <p>
1465  * For cross-domain access to remote data, use an {@link Roo.data.ScriptTagProxy}.</em><br><br>
1466  * <p>
1467  * Be aware that to enable the browser to parse an XML document, the server must set
1468  * the Content-Type header in the HTTP response to "text/xml".
1469  * @constructor
1470  * @param {Object} conn Connection config options to add to each request (e.g. {url: 'foo.php'} or
1471  * an {@link Roo.data.Connection} object.  If a Connection config is passed, the singleton {@link Roo.Ajax} object
1472  * will be used to make the request.
1473  */
1474 Roo.data.HttpProxy = function(conn){
1475     Roo.data.HttpProxy.superclass.constructor.call(this);
1476     // is conn a conn config or a real conn?
1477     this.conn = conn;
1478     this.useAjax = !conn || !conn.events;
1479   
1480 };
1481
1482 Roo.extend(Roo.data.HttpProxy, Roo.data.DataProxy, {
1483     // thse are take from connection...
1484     
1485     /**
1486      * @cfg {String} url (Optional) The default URL to be used for requests to the server. (defaults to undefined)
1487      */
1488     /**
1489      * @cfg {Object} extraParams (Optional) An object containing properties which are used as
1490      * extra parameters to each request made by this object. (defaults to undefined)
1491      */
1492     /**
1493      * @cfg {Object} defaultHeaders (Optional) An object containing request headers which are added
1494      *  to each request made by this object. (defaults to undefined)
1495      */
1496     /**
1497      * @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)
1498      */
1499     /**
1500      * @cfg {Number} timeout (Optional) The timeout in milliseconds to be used for requests. (defaults to 30000)
1501      */
1502      /**
1503      * @cfg {Boolean} autoAbort (Optional) Whether this request should abort any pending requests. (defaults to false)
1504      * @type Boolean
1505      */
1506   
1507
1508     /**
1509      * @cfg {Boolean} disableCaching (Optional) True to add a unique cache-buster param to GET requests. (defaults to true)
1510      * @type Boolean
1511      */
1512     /**
1513      * Return the {@link Roo.data.Connection} object being used by this Proxy.
1514      * @return {Connection} The Connection object. This object may be used to subscribe to events on
1515      * a finer-grained basis than the DataProxy events.
1516      */
1517     getConnection : function(){
1518         return this.useAjax ? Roo.Ajax : this.conn;
1519     },
1520
1521     /**
1522      * Load data from the configured {@link Roo.data.Connection}, read the data object into
1523      * a block of Roo.data.Records using the passed {@link Roo.data.DataReader} implementation, and
1524      * process that block using the passed callback.
1525      * @param {Object} params An object containing properties which are to be used as HTTP parameters
1526      * for the request to the remote server.
1527      * @param {Roo.data.DataReader} reader The Reader object which converts the data
1528      * object into a block of Roo.data.Records.
1529      * @param {Function} callback The function into which to pass the block of Roo.data.Records.
1530      * The function must be passed <ul>
1531      * <li>The Record block object</li>
1532      * <li>The "arg" argument from the load function</li>
1533      * <li>A boolean success indicator</li>
1534      * </ul>
1535      * @param {Object} scope The scope in which to call the callback
1536      * @param {Object} arg An optional argument which is passed to the callback as its second parameter.
1537      */
1538     load : function(params, reader, callback, scope, arg){
1539         if(this.fireEvent("beforeload", this, params) !== false){
1540             var  o = {
1541                 params : params || {},
1542                 request: {
1543                     callback : callback,
1544                     scope : scope,
1545                     arg : arg
1546                 },
1547                 reader: reader,
1548                 callback : this.loadResponse,
1549                 scope: this
1550             };
1551             if(this.useAjax){
1552                 Roo.applyIf(o, this.conn);
1553                 if(this.activeRequest){
1554                     Roo.Ajax.abort(this.activeRequest);
1555                 }
1556                 this.activeRequest = Roo.Ajax.request(o);
1557             }else{
1558                 this.conn.request(o);
1559             }
1560         }else{
1561             callback.call(scope||this, null, arg, false);
1562         }
1563     },
1564
1565     // private
1566     loadResponse : function(o, success, response){
1567         delete this.activeRequest;
1568         if(!success){
1569             this.fireEvent("loadexception", this, o, response);
1570             o.request.callback.call(o.request.scope, null, o.request.arg, false);
1571             return;
1572         }
1573         var result;
1574         try {
1575             result = o.reader.read(response);
1576         }catch(e){
1577             o.success = false;
1578             o.raw = { errorMsg : response.responseText };
1579             this.fireEvent("loadexception", this, o, response, e);
1580             o.request.callback.call(o.request.scope, o, o.request.arg, false);
1581             return;
1582         }
1583         
1584         this.fireEvent("load", this, o, o.request.arg);
1585         o.request.callback.call(o.request.scope, result, o.request.arg, true);
1586     },
1587
1588     // private
1589     update : function(dataSet){
1590
1591     },
1592
1593     // private
1594     updateResponse : function(dataSet){
1595
1596     }
1597 });/*
1598  * Based on:
1599  * Ext JS Library 1.1.1
1600  * Copyright(c) 2006-2007, Ext JS, LLC.
1601  *
1602  * Originally Released Under LGPL - original licence link has changed is not relivant.
1603  *
1604  * Fork - LGPL
1605  * <script type="text/javascript">
1606  */
1607
1608 /**
1609  * @class Roo.data.ScriptTagProxy
1610  * An implementation of Roo.data.DataProxy that reads a data object from a URL which may be in a domain
1611  * other than the originating domain of the running page.<br><br>
1612  * <p>
1613  * <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
1614  * of the running page, you must use this class, rather than DataProxy.</em><br><br>
1615  * <p>
1616  * The content passed back from a server resource requested by a ScriptTagProxy is executable JavaScript
1617  * source code that is used as the source inside a &lt;script> tag.<br><br>
1618  * <p>
1619  * In order for the browser to process the returned data, the server must wrap the data object
1620  * with a call to a callback function, the name of which is passed as a parameter by the ScriptTagProxy.
1621  * Below is a Java example for a servlet which returns data for either a ScriptTagProxy, or an HttpProxy
1622  * depending on whether the callback name was passed:
1623  * <p>
1624  * <pre><code>
1625 boolean scriptTag = false;
1626 String cb = request.getParameter("callback");
1627 if (cb != null) {
1628     scriptTag = true;
1629     response.setContentType("text/javascript");
1630 } else {
1631     response.setContentType("application/x-json");
1632 }
1633 Writer out = response.getWriter();
1634 if (scriptTag) {
1635     out.write(cb + "(");
1636 }
1637 out.print(dataBlock.toJsonString());
1638 if (scriptTag) {
1639     out.write(");");
1640 }
1641 </pre></code>
1642  *
1643  * @constructor
1644  * @param {Object} config A configuration object.
1645  */
1646 Roo.data.ScriptTagProxy = function(config){
1647     Roo.data.ScriptTagProxy.superclass.constructor.call(this);
1648     Roo.apply(this, config);
1649     this.head = document.getElementsByTagName("head")[0];
1650 };
1651
1652 Roo.data.ScriptTagProxy.TRANS_ID = 1000;
1653
1654 Roo.extend(Roo.data.ScriptTagProxy, Roo.data.DataProxy, {
1655     /**
1656      * @cfg {String} url The URL from which to request the data object.
1657      */
1658     /**
1659      * @cfg {Number} timeout (Optional) The number of milliseconds to wait for a response. Defaults to 30 seconds.
1660      */
1661     timeout : 30000,
1662     /**
1663      * @cfg {String} callbackParam (Optional) The name of the parameter to pass to the server which tells
1664      * the server the name of the callback function set up by the load call to process the returned data object.
1665      * Defaults to "callback".<p>The server-side processing must read this parameter value, and generate
1666      * javascript output which calls this named function passing the data object as its only parameter.
1667      */
1668     callbackParam : "callback",
1669     /**
1670      *  @cfg {Boolean} nocache (Optional) Defaults to true. Disable cacheing by adding a unique parameter
1671      * name to the request.
1672      */
1673     nocache : true,
1674
1675     /**
1676      * Load data from the configured URL, read the data object into
1677      * a block of Roo.data.Records using the passed Roo.data.DataReader implementation, and
1678      * process that block using the passed callback.
1679      * @param {Object} params An object containing properties which are to be used as HTTP parameters
1680      * for the request to the remote server.
1681      * @param {Roo.data.DataReader} reader The Reader object which converts the data
1682      * object into a block of Roo.data.Records.
1683      * @param {Function} callback The function into which to pass the block of Roo.data.Records.
1684      * The function must be passed <ul>
1685      * <li>The Record block object</li>
1686      * <li>The "arg" argument from the load function</li>
1687      * <li>A boolean success indicator</li>
1688      * </ul>
1689      * @param {Object} scope The scope in which to call the callback
1690      * @param {Object} arg An optional argument which is passed to the callback as its second parameter.
1691      */
1692     load : function(params, reader, callback, scope, arg){
1693         if(this.fireEvent("beforeload", this, params) !== false){
1694
1695             var p = Roo.urlEncode(Roo.apply(params, this.extraParams));
1696
1697             var url = this.url;
1698             url += (url.indexOf("?") != -1 ? "&" : "?") + p;
1699             if(this.nocache){
1700                 url += "&_dc=" + (new Date().getTime());
1701             }
1702             var transId = ++Roo.data.ScriptTagProxy.TRANS_ID;
1703             var trans = {
1704                 id : transId,
1705                 cb : "stcCallback"+transId,
1706                 scriptId : "stcScript"+transId,
1707                 params : params,
1708                 arg : arg,
1709                 url : url,
1710                 callback : callback,
1711                 scope : scope,
1712                 reader : reader
1713             };
1714             var conn = this;
1715
1716             window[trans.cb] = function(o){
1717                 conn.handleResponse(o, trans);
1718             };
1719
1720             url += String.format("&{0}={1}", this.callbackParam, trans.cb);
1721
1722             if(this.autoAbort !== false){
1723                 this.abort();
1724             }
1725
1726             trans.timeoutId = this.handleFailure.defer(this.timeout, this, [trans]);
1727
1728             var script = document.createElement("script");
1729             script.setAttribute("src", url);
1730             script.setAttribute("type", "text/javascript");
1731             script.setAttribute("id", trans.scriptId);
1732             this.head.appendChild(script);
1733
1734             this.trans = trans;
1735         }else{
1736             callback.call(scope||this, null, arg, false);
1737         }
1738     },
1739
1740     // private
1741     isLoading : function(){
1742         return this.trans ? true : false;
1743     },
1744
1745     /**
1746      * Abort the current server request.
1747      */
1748     abort : function(){
1749         if(this.isLoading()){
1750             this.destroyTrans(this.trans);
1751         }
1752     },
1753
1754     // private
1755     destroyTrans : function(trans, isLoaded){
1756         this.head.removeChild(document.getElementById(trans.scriptId));
1757         clearTimeout(trans.timeoutId);
1758         if(isLoaded){
1759             window[trans.cb] = undefined;
1760             try{
1761                 delete window[trans.cb];
1762             }catch(e){}
1763         }else{
1764             // if hasn't been loaded, wait for load to remove it to prevent script error
1765             window[trans.cb] = function(){
1766                 window[trans.cb] = undefined;
1767                 try{
1768                     delete window[trans.cb];
1769                 }catch(e){}
1770             };
1771         }
1772     },
1773
1774     // private
1775     handleResponse : function(o, trans){
1776         this.trans = false;
1777         this.destroyTrans(trans, true);
1778         var result;
1779         try {
1780             result = trans.reader.readRecords(o);
1781         }catch(e){
1782             this.fireEvent("loadexception", this, o, trans.arg, e);
1783             trans.callback.call(trans.scope||window, null, trans.arg, false);
1784             return;
1785         }
1786         this.fireEvent("load", this, o, trans.arg);
1787         trans.callback.call(trans.scope||window, result, trans.arg, true);
1788     },
1789
1790     // private
1791     handleFailure : function(trans){
1792         this.trans = false;
1793         this.destroyTrans(trans, false);
1794         this.fireEvent("loadexception", this, null, trans.arg);
1795         trans.callback.call(trans.scope||window, null, trans.arg, false);
1796     }
1797 });/*
1798  * Based on:
1799  * Ext JS Library 1.1.1
1800  * Copyright(c) 2006-2007, Ext JS, LLC.
1801  *
1802  * Originally Released Under LGPL - original licence link has changed is not relivant.
1803  *
1804  * Fork - LGPL
1805  * <script type="text/javascript">
1806  */
1807
1808 /**
1809  * @class Roo.data.JsonReader
1810  * @extends Roo.data.DataReader
1811  * Data reader class to create an Array of Roo.data.Record objects from a JSON response
1812  * based on mappings in a provided Roo.data.Record constructor.
1813  * 
1814  * The default behaviour of a store is to send ?_requestMeta=1, unless the class has recieved 'metaData' property
1815  * in the reply previously. 
1816  * 
1817  * <p>
1818  * Example code:
1819  * <pre><code>
1820 var RecordDef = Roo.data.Record.create([
1821     {name: 'name', mapping: 'name'},     // "mapping" property not needed if it's the same as "name"
1822     {name: 'occupation'}                 // This field will use "occupation" as the mapping.
1823 ]);
1824 var myReader = new Roo.data.JsonReader({
1825     totalProperty: "results",    // The property which contains the total dataset size (optional)
1826     root: "rows",                // The property which contains an Array of row objects
1827     id: "id"                     // The property within each row object that provides an ID for the record (optional)
1828 }, RecordDef);
1829 </code></pre>
1830  * <p>
1831  * This would consume a JSON file like this:
1832  * <pre><code>
1833 { 'results': 2, 'rows': [
1834     { 'id': 1, 'name': 'Bill', occupation: 'Gardener' },
1835     { 'id': 2, 'name': 'Ben', occupation: 'Horticulturalist' } ]
1836 }
1837 </code></pre>
1838  * @cfg {String} totalProperty Name of the property from which to retrieve the total number of records
1839  * in the dataset. This is only needed if the whole dataset is not passed in one go, but is being
1840  * paged from the remote server.
1841  * @cfg {String} successProperty Name of the property from which to retrieve the success attribute used by forms.
1842  * @cfg {String} root name of the property which contains the Array of row objects.
1843  * @cfg {String} id Name of the property within a row object that contains a record identifier value.
1844  * @cfg {Array} fields Array of field definition objects
1845  * @constructor
1846  * Create a new JsonReader
1847  * @param {Object} meta Metadata configuration options
1848  * @param {Object} recordType Either an Array of field definition objects,
1849  * or an {@link Roo.data.Record} object created using {@link Roo.data.Record#create}.
1850  */
1851 Roo.data.JsonReader = function(meta, recordType){
1852     
1853     meta = meta || {};
1854     // set some defaults:
1855     Roo.applyIf(meta, {
1856         totalProperty: 'total',
1857         successProperty : 'success',
1858         root : 'data',
1859         id : 'id'
1860     });
1861     
1862     Roo.data.JsonReader.superclass.constructor.call(this, meta, recordType||meta.fields);
1863 };
1864 Roo.extend(Roo.data.JsonReader, Roo.data.DataReader, {
1865     
1866     readerType : 'Json',
1867     
1868     /**
1869      * @prop {Boolean} metaFromRemote  - if the meta data was loaded from the remote source.
1870      * Used by Store query builder to append _requestMeta to params.
1871      * 
1872      */
1873     metaFromRemote : false,
1874     /**
1875      * This method is only used by a DataProxy which has retrieved data from a remote server.
1876      * @param {Object} response The XHR object which contains the JSON data in its responseText.
1877      * @return {Object} data A data block which is used by an Roo.data.Store object as
1878      * a cache of Roo.data.Records.
1879      */
1880     read : function(response){
1881         var json = response.responseText;
1882        
1883         var o = /* eval:var:o */ eval("("+json+")");
1884         if(!o) {
1885             throw {message: "JsonReader.read: Json object not found"};
1886         }
1887         
1888         if(o.metaData){
1889             
1890             delete this.ef;
1891             this.metaFromRemote = true;
1892             this.meta = o.metaData;
1893             this.recordType = Roo.data.Record.create(o.metaData.fields);
1894             this.onMetaChange(this.meta, this.recordType, o);
1895         }
1896         return this.readRecords(o);
1897     },
1898
1899     // private function a store will implement
1900     onMetaChange : function(meta, recordType, o){
1901
1902     },
1903
1904     /**
1905          * @ignore
1906          */
1907     simpleAccess: function(obj, subsc) {
1908         return obj[subsc];
1909     },
1910
1911         /**
1912          * @ignore
1913          */
1914     getJsonAccessor: function(){
1915         var re = /[\[\.]/;
1916         return function(expr) {
1917             try {
1918                 return(re.test(expr))
1919                     ? new Function("obj", "return obj." + expr)
1920                     : function(obj){
1921                         return obj[expr];
1922                     };
1923             } catch(e){}
1924             return Roo.emptyFn;
1925         };
1926     }(),
1927
1928     /**
1929      * Create a data block containing Roo.data.Records from an XML document.
1930      * @param {Object} o An object which contains an Array of row objects in the property specified
1931      * in the config as 'root, and optionally a property, specified in the config as 'totalProperty'
1932      * which contains the total size of the dataset.
1933      * @return {Object} data A data block which is used by an Roo.data.Store object as
1934      * a cache of Roo.data.Records.
1935      */
1936     readRecords : function(o){
1937         /**
1938          * After any data loads, the raw JSON data is available for further custom processing.
1939          * @type Object
1940          */
1941         this.o = o;
1942         var s = this.meta, Record = this.recordType,
1943             f = Record ? Record.prototype.fields : null, fi = f ? f.items : [], fl = f ? f.length : 0;
1944
1945 //      Generate extraction functions for the totalProperty, the root, the id, and for each field
1946         if (!this.ef) {
1947             if(s.totalProperty) {
1948                     this.getTotal = this.getJsonAccessor(s.totalProperty);
1949                 }
1950                 if(s.successProperty) {
1951                     this.getSuccess = this.getJsonAccessor(s.successProperty);
1952                 }
1953                 this.getRoot = s.root ? this.getJsonAccessor(s.root) : function(p){return p;};
1954                 if (s.id) {
1955                         var g = this.getJsonAccessor(s.id);
1956                         this.getId = function(rec) {
1957                                 var r = g(rec);  
1958                                 return (r === undefined || r === "") ? null : r;
1959                         };
1960                 } else {
1961                         this.getId = function(){return null;};
1962                 }
1963             this.ef = [];
1964             for(var jj = 0; jj < fl; jj++){
1965                 f = fi[jj];
1966                 var map = (f.mapping !== undefined && f.mapping !== null) ? f.mapping : f.name;
1967                 this.ef[jj] = this.getJsonAccessor(map);
1968             }
1969         }
1970
1971         var root = this.getRoot(o), c = root.length, totalRecords = c, success = true;
1972         if(s.totalProperty){
1973             var vt = parseInt(this.getTotal(o), 10);
1974             if(!isNaN(vt)){
1975                 totalRecords = vt;
1976             }
1977         }
1978         if(s.successProperty){
1979             var vs = this.getSuccess(o);
1980             if(vs === false || vs === 'false'){
1981                 success = false;
1982             }
1983         }
1984         var records = [];
1985         for(var i = 0; i < c; i++){
1986             var n = root[i];
1987             var values = {};
1988             var id = this.getId(n);
1989             for(var j = 0; j < fl; j++){
1990                 f = fi[j];
1991                                 var v = this.ef[j](n);
1992                                 if (!f.convert) {
1993                                         Roo.log('missing convert for ' + f.name);
1994                                         Roo.log(f);
1995                                         continue;
1996                                 }
1997                                 values[f.name] = f.convert((v !== undefined) ? v : f.defaultValue);
1998             }
1999                         if (!Record) {
2000                                 return {
2001                                         raw : { errorMsg : "JSON Reader Error: fields or metadata not available to create Record" },
2002                                         success : false,
2003                                         records : [],
2004                                         totalRecords : 0
2005                                 };
2006                         }
2007             var record = new Record(values, id);
2008             record.json = n;
2009             records[i] = record;
2010         }
2011         return {
2012             raw : o,
2013             success : success,
2014             records : records,
2015             totalRecords : totalRecords
2016         };
2017     },
2018     // used when loading children.. @see loadDataFromChildren
2019     toLoadData: function(rec)
2020     {
2021         // expect rec just to be an array.. eg [a,b,c, [...] << cn ]
2022         var data = typeof(rec.data.cn) == 'undefined' ? [] : rec.data.cn;
2023         return { data : data, total : data.length };
2024         
2025     }
2026 });/*
2027  * Based on:
2028  * Ext JS Library 1.1.1
2029  * Copyright(c) 2006-2007, Ext JS, LLC.
2030  *
2031  * Originally Released Under LGPL - original licence link has changed is not relivant.
2032  *
2033  * Fork - LGPL
2034  * <script type="text/javascript">
2035  */
2036
2037 /**
2038  * @class Roo.data.XmlReader
2039  * @extends Roo.data.DataReader
2040  * Data reader class to create an Array of {@link Roo.data.Record} objects from an XML document
2041  * based on mappings in a provided Roo.data.Record constructor.<br><br>
2042  * <p>
2043  * <em>Note that in order for the browser to parse a returned XML document, the Content-Type
2044  * header in the HTTP response must be set to "text/xml".</em>
2045  * <p>
2046  * Example code:
2047  * <pre><code>
2048 var RecordDef = Roo.data.Record.create([
2049    {name: 'name', mapping: 'name'},     // "mapping" property not needed if it's the same as "name"
2050    {name: 'occupation'}                 // This field will use "occupation" as the mapping.
2051 ]);
2052 var myReader = new Roo.data.XmlReader({
2053    totalRecords: "results", // The element which contains the total dataset size (optional)
2054    record: "row",           // The repeated element which contains row information
2055    id: "id"                 // The element within the row that provides an ID for the record (optional)
2056 }, RecordDef);
2057 </code></pre>
2058  * <p>
2059  * This would consume an XML file like this:
2060  * <pre><code>
2061 &lt;?xml?>
2062 &lt;dataset>
2063  &lt;results>2&lt;/results>
2064  &lt;row>
2065    &lt;id>1&lt;/id>
2066    &lt;name>Bill&lt;/name>
2067    &lt;occupation>Gardener&lt;/occupation>
2068  &lt;/row>
2069  &lt;row>
2070    &lt;id>2&lt;/id>
2071    &lt;name>Ben&lt;/name>
2072    &lt;occupation>Horticulturalist&lt;/occupation>
2073  &lt;/row>
2074 &lt;/dataset>
2075 </code></pre>
2076  * @cfg {String} totalRecords The DomQuery path from which to retrieve the total number of records
2077  * in the dataset. This is only needed if the whole dataset is not passed in one go, but is being
2078  * paged from the remote server.
2079  * @cfg {String} record The DomQuery path to the repeated element which contains record information.
2080  * @cfg {String} success The DomQuery path to the success attribute used by forms.
2081  * @cfg {String} id The DomQuery path relative from the record element to the element that contains
2082  * a record identifier value.
2083  * @constructor
2084  * Create a new XmlReader
2085  * @param {Object} meta Metadata configuration options
2086  * @param {Mixed} recordType The definition of the data record type to produce.  This can be either a valid
2087  * Record subclass created with {@link Roo.data.Record#create}, or an array of objects with which to call
2088  * Roo.data.Record.create.  See the {@link Roo.data.Record} class for more details.
2089  */
2090 Roo.data.XmlReader = function(meta, recordType){
2091     meta = meta || {};
2092     Roo.data.XmlReader.superclass.constructor.call(this, meta, recordType||meta.fields);
2093 };
2094 Roo.extend(Roo.data.XmlReader, Roo.data.DataReader, {
2095     
2096     readerType : 'Xml',
2097     
2098     /**
2099      * This method is only used by a DataProxy which has retrieved data from a remote server.
2100          * @param {Object} response The XHR object which contains the parsed XML document.  The response is expected
2101          * to contain a method called 'responseXML' that returns an XML document object.
2102      * @return {Object} records A data block which is used by an {@link Roo.data.Store} as
2103      * a cache of Roo.data.Records.
2104      */
2105     read : function(response){
2106         var doc = response.responseXML;
2107         if(!doc) {
2108             throw {message: "XmlReader.read: XML Document not available"};
2109         }
2110         return this.readRecords(doc);
2111     },
2112
2113     /**
2114      * Create a data block containing Roo.data.Records from an XML document.
2115          * @param {Object} doc A parsed XML document.
2116      * @return {Object} records A data block which is used by an {@link Roo.data.Store} as
2117      * a cache of Roo.data.Records.
2118      */
2119     readRecords : function(doc){
2120         /**
2121          * After any data loads/reads, the raw XML Document is available for further custom processing.
2122          * @type XMLDocument
2123          */
2124         this.xmlData = doc;
2125         var root = doc.documentElement || doc;
2126         var q = Roo.DomQuery;
2127         var recordType = this.recordType, fields = recordType.prototype.fields;
2128         var sid = this.meta.id;
2129         var totalRecords = 0, success = true;
2130         if(this.meta.totalRecords){
2131             totalRecords = q.selectNumber(this.meta.totalRecords, root, 0);
2132         }
2133         
2134         if(this.meta.success){
2135             var sv = q.selectValue(this.meta.success, root, true);
2136             success = sv !== false && sv !== 'false';
2137         }
2138         var records = [];
2139         var ns = q.select(this.meta.record, root);
2140         for(var i = 0, len = ns.length; i < len; i++) {
2141                 var n = ns[i];
2142                 var values = {};
2143                 var id = sid ? q.selectValue(sid, n) : undefined;
2144                 for(var j = 0, jlen = fields.length; j < jlen; j++){
2145                     var f = fields.items[j];
2146                 var v = q.selectValue(f.mapping || f.name, n, f.defaultValue);
2147                     v = f.convert(v);
2148                     values[f.name] = v;
2149                 }
2150                 var record = new recordType(values, id);
2151                 record.node = n;
2152                 records[records.length] = record;
2153             }
2154
2155             return {
2156                 success : success,
2157                 records : records,
2158                 totalRecords : totalRecords || records.length
2159             };
2160     }
2161 });/*
2162  * Based on:
2163  * Ext JS Library 1.1.1
2164  * Copyright(c) 2006-2007, Ext JS, LLC.
2165  *
2166  * Originally Released Under LGPL - original licence link has changed is not relivant.
2167  *
2168  * Fork - LGPL
2169  * <script type="text/javascript">
2170  */
2171
2172 /**
2173  * @class Roo.data.ArrayReader
2174  * @extends Roo.data.DataReader
2175  * Data reader class to create an Array of Roo.data.Record objects from an Array.
2176  * Each element of that Array represents a row of data fields. The
2177  * fields are pulled into a Record object using as a subscript, the <em>mapping</em> property
2178  * of the field definition if it exists, or the field's ordinal position in the definition.<br>
2179  * <p>
2180  * Example code:.
2181  * <pre><code>
2182 var RecordDef = Roo.data.Record.create([
2183     {name: 'name', mapping: 1},         // "mapping" only needed if an "id" field is present which
2184     {name: 'occupation', mapping: 2}    // precludes using the ordinal position as the index.
2185 ]);
2186 var myReader = new Roo.data.ArrayReader({
2187     id: 0                     // The subscript within row Array that provides an ID for the Record (optional)
2188 }, RecordDef);
2189 </code></pre>
2190  * <p>
2191  * This would consume an Array like this:
2192  * <pre><code>
2193 [ [1, 'Bill', 'Gardener'], [2, 'Ben', 'Horticulturalist'] ]
2194   </code></pre>
2195  
2196  * @constructor
2197  * Create a new JsonReader
2198  * @param {Object} meta Metadata configuration options.
2199  * @param {Object|Array} recordType Either an Array of field definition objects
2200  * 
2201  * @cfg {Array} fields Array of field definition objects
2202  * @cfg {String} id Name of the property within a row object that contains a record identifier value.
2203  * as specified to {@link Roo.data.Record#create},
2204  * or an {@link Roo.data.Record} object
2205  *
2206  * 
2207  * created using {@link Roo.data.Record#create}.
2208  */
2209 Roo.data.ArrayReader = function(meta, recordType)
2210 {    
2211     Roo.data.ArrayReader.superclass.constructor.call(this, meta, recordType||meta.fields);
2212 };
2213
2214 Roo.extend(Roo.data.ArrayReader, Roo.data.JsonReader, {
2215     
2216       /**
2217      * Create a data block containing Roo.data.Records from an XML document.
2218      * @param {Object} o An Array of row objects which represents the dataset.
2219      * @return {Object} A data block which is used by an {@link Roo.data.Store} object as
2220      * a cache of Roo.data.Records.
2221      */
2222     readRecords : function(o)
2223     {
2224         var sid = this.meta ? this.meta.id : null;
2225         var recordType = this.recordType, fields = recordType.prototype.fields;
2226         var records = [];
2227         var root = o;
2228         for(var i = 0; i < root.length; i++){
2229             var n = root[i];
2230             var values = {};
2231             var id = ((sid || sid === 0) && n[sid] !== undefined && n[sid] !== "" ? n[sid] : null);
2232             for(var j = 0, jlen = fields.length; j < jlen; j++){
2233                 var f = fields.items[j];
2234                 var k = f.mapping !== undefined && f.mapping !== null ? f.mapping : j;
2235                 var v = n[k] !== undefined ? n[k] : f.defaultValue;
2236                 v = f.convert(v);
2237                 values[f.name] = v;
2238             }
2239             var record = new recordType(values, id);
2240             record.json = n;
2241             records[records.length] = record;
2242         }
2243         return {
2244             records : records,
2245             totalRecords : records.length
2246         };
2247     },
2248     // used when loading children.. @see loadDataFromChildren
2249     toLoadData: function(rec)
2250     {
2251         // expect rec just to be an array.. eg [a,b,c, [...] << cn ]
2252         return typeof(rec.data.cn) == 'undefined' ? [] : rec.data.cn;
2253         
2254     }
2255     
2256     
2257 });/*
2258  * Based on:
2259  * Ext JS Library 1.1.1
2260  * Copyright(c) 2006-2007, Ext JS, LLC.
2261  *
2262  * Originally Released Under LGPL - original licence link has changed is not relivant.
2263  *
2264  * Fork - LGPL
2265  * <script type="text/javascript">
2266  */
2267
2268
2269 /**
2270  * @class Roo.data.Tree
2271  * @extends Roo.util.Observable
2272  * Represents a tree data structure and bubbles all the events for its nodes. The nodes
2273  * in the tree have most standard DOM functionality.
2274  * @constructor
2275  * @param {Node} root (optional) The root node
2276  */
2277 Roo.data.Tree = function(root){
2278    this.nodeHash = {};
2279    /**
2280     * The root node for this tree
2281     * @type Node
2282     */
2283    this.root = null;
2284    if(root){
2285        this.setRootNode(root);
2286    }
2287    this.addEvents({
2288        /**
2289         * @event append
2290         * Fires when a new child node is appended to a node in this tree.
2291         * @param {Tree} tree The owner tree
2292         * @param {Node} parent The parent node
2293         * @param {Node} node The newly appended node
2294         * @param {Number} index The index of the newly appended node
2295         */
2296        "append" : true,
2297        /**
2298         * @event remove
2299         * Fires when a child node is removed from a node in this tree.
2300         * @param {Tree} tree The owner tree
2301         * @param {Node} parent The parent node
2302         * @param {Node} node The child node removed
2303         */
2304        "remove" : true,
2305        /**
2306         * @event move
2307         * Fires when a node is moved to a new location in the tree
2308         * @param {Tree} tree The owner tree
2309         * @param {Node} node The node moved
2310         * @param {Node} oldParent The old parent of this node
2311         * @param {Node} newParent The new parent of this node
2312         * @param {Number} index The index it was moved to
2313         */
2314        "move" : true,
2315        /**
2316         * @event insert
2317         * Fires when a new child node is inserted in a node in this tree.
2318         * @param {Tree} tree The owner tree
2319         * @param {Node} parent The parent node
2320         * @param {Node} node The child node inserted
2321         * @param {Node} refNode The child node the node was inserted before
2322         */
2323        "insert" : true,
2324        /**
2325         * @event beforeappend
2326         * Fires before a new child is appended to a node in this tree, return false to cancel the append.
2327         * @param {Tree} tree The owner tree
2328         * @param {Node} parent The parent node
2329         * @param {Node} node The child node to be appended
2330         */
2331        "beforeappend" : true,
2332        /**
2333         * @event beforeremove
2334         * Fires before a child is removed from a node in this tree, return false to cancel the remove.
2335         * @param {Tree} tree The owner tree
2336         * @param {Node} parent The parent node
2337         * @param {Node} node The child node to be removed
2338         */
2339        "beforeremove" : true,
2340        /**
2341         * @event beforemove
2342         * Fires before a node is moved to a new location in the tree. Return false to cancel the move.
2343         * @param {Tree} tree The owner tree
2344         * @param {Node} node The node being moved
2345         * @param {Node} oldParent The parent of the node
2346         * @param {Node} newParent The new parent the node is moving to
2347         * @param {Number} index The index it is being moved to
2348         */
2349        "beforemove" : true,
2350        /**
2351         * @event beforeinsert
2352         * Fires before a new child is inserted in a node in this tree, return false to cancel the insert.
2353         * @param {Tree} tree The owner tree
2354         * @param {Node} parent The parent node
2355         * @param {Node} node The child node to be inserted
2356         * @param {Node} refNode The child node the node is being inserted before
2357         */
2358        "beforeinsert" : true
2359    });
2360
2361     Roo.data.Tree.superclass.constructor.call(this);
2362 };
2363
2364 Roo.extend(Roo.data.Tree, Roo.util.Observable, {
2365     pathSeparator: "/",
2366
2367     proxyNodeEvent : function(){
2368         return this.fireEvent.apply(this, arguments);
2369     },
2370
2371     /**
2372      * Returns the root node for this tree.
2373      * @return {Node}
2374      */
2375     getRootNode : function(){
2376         return this.root;
2377     },
2378
2379     /**
2380      * Sets the root node for this tree.
2381      * @param {Node} node
2382      * @return {Node}
2383      */
2384     setRootNode : function(node){
2385         this.root = node;
2386         node.ownerTree = this;
2387         node.isRoot = true;
2388         this.registerNode(node);
2389         return node;
2390     },
2391
2392     /**
2393      * Gets a node in this tree by its id.
2394      * @param {String} id
2395      * @return {Node}
2396      */
2397     getNodeById : function(id){
2398         return this.nodeHash[id];
2399     },
2400
2401     registerNode : function(node){
2402         this.nodeHash[node.id] = node;
2403     },
2404
2405     unregisterNode : function(node){
2406         delete this.nodeHash[node.id];
2407     },
2408
2409     toString : function(){
2410         return "[Tree"+(this.id?" "+this.id:"")+"]";
2411     }
2412 });
2413
2414 /**
2415  * @class Roo.data.Node
2416  * @extends Roo.util.Observable
2417  * @cfg {Boolean} leaf true if this node is a leaf and does not have children
2418  * @cfg {String} id The id for this node. If one is not specified, one is generated.
2419  * @constructor
2420  * @param {Object} attributes The attributes/config for the node
2421  */
2422 Roo.data.Node = function(attributes){
2423     /**
2424      * The attributes supplied for the node. You can use this property to access any custom attributes you supplied.
2425      * @type {Object}
2426      */
2427     this.attributes = attributes || {};
2428     this.leaf = this.attributes.leaf;
2429     /**
2430      * The node id. @type String
2431      */
2432     this.id = this.attributes.id;
2433     if(!this.id){
2434         this.id = Roo.id(null, "ynode-");
2435         this.attributes.id = this.id;
2436     }
2437      
2438     
2439     /**
2440      * All child nodes of this node. @type Array
2441      */
2442     this.childNodes = [];
2443     if(!this.childNodes.indexOf){ // indexOf is a must
2444         this.childNodes.indexOf = function(o){
2445             for(var i = 0, len = this.length; i < len; i++){
2446                 if(this[i] == o) {
2447                     return i;
2448                 }
2449             }
2450             return -1;
2451         };
2452     }
2453     /**
2454      * The parent node for this node. @type Node
2455      */
2456     this.parentNode = null;
2457     /**
2458      * The first direct child node of this node, or null if this node has no child nodes. @type Node
2459      */
2460     this.firstChild = null;
2461     /**
2462      * The last direct child node of this node, or null if this node has no child nodes. @type Node
2463      */
2464     this.lastChild = null;
2465     /**
2466      * The node immediately preceding this node in the tree, or null if there is no sibling node. @type Node
2467      */
2468     this.previousSibling = null;
2469     /**
2470      * The node immediately following this node in the tree, or null if there is no sibling node. @type Node
2471      */
2472     this.nextSibling = null;
2473
2474     this.addEvents({
2475        /**
2476         * @event append
2477         * Fires when a new child node is appended
2478         * @param {Tree} tree The owner tree
2479         * @param {Node} this This node
2480         * @param {Node} node The newly appended node
2481         * @param {Number} index The index of the newly appended node
2482         */
2483        "append" : true,
2484        /**
2485         * @event remove
2486         * Fires when a child node is removed
2487         * @param {Tree} tree The owner tree
2488         * @param {Node} this This node
2489         * @param {Node} node The removed node
2490         */
2491        "remove" : true,
2492        /**
2493         * @event move
2494         * Fires when this node is moved to a new location in the tree
2495         * @param {Tree} tree The owner tree
2496         * @param {Node} this This node
2497         * @param {Node} oldParent The old parent of this node
2498         * @param {Node} newParent The new parent of this node
2499         * @param {Number} index The index it was moved to
2500         */
2501        "move" : true,
2502        /**
2503         * @event insert
2504         * Fires when a new child node is inserted.
2505         * @param {Tree} tree The owner tree
2506         * @param {Node} this This node
2507         * @param {Node} node The child node inserted
2508         * @param {Node} refNode The child node the node was inserted before
2509         */
2510        "insert" : true,
2511        /**
2512         * @event beforeappend
2513         * Fires before a new child is appended, return false to cancel the append.
2514         * @param {Tree} tree The owner tree
2515         * @param {Node} this This node
2516         * @param {Node} node The child node to be appended
2517         */
2518        "beforeappend" : true,
2519        /**
2520         * @event beforeremove
2521         * Fires before a child is removed, return false to cancel the remove.
2522         * @param {Tree} tree The owner tree
2523         * @param {Node} this This node
2524         * @param {Node} node The child node to be removed
2525         */
2526        "beforeremove" : true,
2527        /**
2528         * @event beforemove
2529         * Fires before this node is moved to a new location in the tree. Return false to cancel the move.
2530         * @param {Tree} tree The owner tree
2531         * @param {Node} this This node
2532         * @param {Node} oldParent The parent of this node
2533         * @param {Node} newParent The new parent this node is moving to
2534         * @param {Number} index The index it is being moved to
2535         */
2536        "beforemove" : true,
2537        /**
2538         * @event beforeinsert
2539         * Fires before a new child is inserted, return false to cancel the insert.
2540         * @param {Tree} tree The owner tree
2541         * @param {Node} this This node
2542         * @param {Node} node The child node to be inserted
2543         * @param {Node} refNode The child node the node is being inserted before
2544         */
2545        "beforeinsert" : true
2546    });
2547     this.listeners = this.attributes.listeners;
2548     Roo.data.Node.superclass.constructor.call(this);
2549 };
2550
2551 Roo.extend(Roo.data.Node, Roo.util.Observable, {
2552     fireEvent : function(evtName){
2553         // first do standard event for this node
2554         if(Roo.data.Node.superclass.fireEvent.apply(this, arguments) === false){
2555             return false;
2556         }
2557         // then bubble it up to the tree if the event wasn't cancelled
2558         var ot = this.getOwnerTree();
2559         if(ot){
2560             if(ot.proxyNodeEvent.apply(ot, arguments) === false){
2561                 return false;
2562             }
2563         }
2564         return true;
2565     },
2566
2567     /**
2568      * Returns true if this node is a leaf
2569      * @return {Boolean}
2570      */
2571     isLeaf : function(){
2572         return this.leaf === true;
2573     },
2574
2575     // private
2576     setFirstChild : function(node){
2577         this.firstChild = node;
2578     },
2579
2580     //private
2581     setLastChild : function(node){
2582         this.lastChild = node;
2583     },
2584
2585
2586     /**
2587      * Returns true if this node is the last child of its parent
2588      * @return {Boolean}
2589      */
2590     isLast : function(){
2591        return (!this.parentNode ? true : this.parentNode.lastChild == this);
2592     },
2593
2594     /**
2595      * Returns true if this node is the first child of its parent
2596      * @return {Boolean}
2597      */
2598     isFirst : function(){
2599        return (!this.parentNode ? true : this.parentNode.firstChild == this);
2600     },
2601
2602     hasChildNodes : function(){
2603         return !this.isLeaf() && this.childNodes.length > 0;
2604     },
2605
2606     /**
2607      * Insert node(s) as the last child node of this node.
2608      * @param {Node/Array} node The node or Array of nodes to append
2609      * @return {Node} The appended node if single append, or null if an array was passed
2610      */
2611     appendChild : function(node){
2612         var multi = false;
2613         if(node instanceof Array){
2614             multi = node;
2615         }else if(arguments.length > 1){
2616             multi = arguments;
2617         }
2618         
2619         // if passed an array or multiple args do them one by one
2620         if(multi){
2621             for(var i = 0, len = multi.length; i < len; i++) {
2622                 this.appendChild(multi[i]);
2623             }
2624         }else{
2625             if(this.fireEvent("beforeappend", this.ownerTree, this, node) === false){
2626                 return false;
2627             }
2628             var index = this.childNodes.length;
2629             var oldParent = node.parentNode;
2630             // it's a move, make sure we move it cleanly
2631             if(oldParent){
2632                 if(node.fireEvent("beforemove", node.getOwnerTree(), node, oldParent, this, index) === false){
2633                     return false;
2634                 }
2635                 oldParent.removeChild(node);
2636             }
2637             
2638             index = this.childNodes.length;
2639             if(index == 0){
2640                 this.setFirstChild(node);
2641             }
2642             this.childNodes.push(node);
2643             node.parentNode = this;
2644             var ps = this.childNodes[index-1];
2645             if(ps){
2646                 node.previousSibling = ps;
2647                 ps.nextSibling = node;
2648             }else{
2649                 node.previousSibling = null;
2650             }
2651             node.nextSibling = null;
2652             this.setLastChild(node);
2653             node.setOwnerTree(this.getOwnerTree());
2654             this.fireEvent("append", this.ownerTree, this, node, index);
2655             if(this.ownerTree) {
2656                 this.ownerTree.fireEvent("appendnode", this, node, index);
2657             }
2658             if(oldParent){
2659                 node.fireEvent("move", this.ownerTree, node, oldParent, this, index);
2660             }
2661             return node;
2662         }
2663     },
2664
2665     /**
2666      * Removes a child node from this node.
2667      * @param {Node} node The node to remove
2668      * @return {Node} The removed node
2669      */
2670     removeChild : function(node){
2671         var index = this.childNodes.indexOf(node);
2672         if(index == -1){
2673             return false;
2674         }
2675         if(this.fireEvent("beforeremove", this.ownerTree, this, node) === false){
2676             return false;
2677         }
2678
2679         // remove it from childNodes collection
2680         this.childNodes.splice(index, 1);
2681
2682         // update siblings
2683         if(node.previousSibling){
2684             node.previousSibling.nextSibling = node.nextSibling;
2685         }
2686         if(node.nextSibling){
2687             node.nextSibling.previousSibling = node.previousSibling;
2688         }
2689
2690         // update child refs
2691         if(this.firstChild == node){
2692             this.setFirstChild(node.nextSibling);
2693         }
2694         if(this.lastChild == node){
2695             this.setLastChild(node.previousSibling);
2696         }
2697
2698         node.setOwnerTree(null);
2699         // clear any references from the node
2700         node.parentNode = null;
2701         node.previousSibling = null;
2702         node.nextSibling = null;
2703         this.fireEvent("remove", this.ownerTree, this, node);
2704         return node;
2705     },
2706
2707     /**
2708      * Inserts the first node before the second node in this nodes childNodes collection.
2709      * @param {Node} node The node to insert
2710      * @param {Node} refNode The node to insert before (if null the node is appended)
2711      * @return {Node} The inserted node
2712      */
2713     insertBefore : function(node, refNode){
2714         if(!refNode){ // like standard Dom, refNode can be null for append
2715             return this.appendChild(node);
2716         }
2717         // nothing to do
2718         if(node == refNode){
2719             return false;
2720         }
2721
2722         if(this.fireEvent("beforeinsert", this.ownerTree, this, node, refNode) === false){
2723             return false;
2724         }
2725         var index = this.childNodes.indexOf(refNode);
2726         var oldParent = node.parentNode;
2727         var refIndex = index;
2728
2729         // when moving internally, indexes will change after remove
2730         if(oldParent == this && this.childNodes.indexOf(node) < index){
2731             refIndex--;
2732         }
2733
2734         // it's a move, make sure we move it cleanly
2735         if(oldParent){
2736             if(node.fireEvent("beforemove", node.getOwnerTree(), node, oldParent, this, index, refNode) === false){
2737                 return false;
2738             }
2739             oldParent.removeChild(node);
2740         }
2741         if(refIndex == 0){
2742             this.setFirstChild(node);
2743         }
2744         this.childNodes.splice(refIndex, 0, node);
2745         node.parentNode = this;
2746         var ps = this.childNodes[refIndex-1];
2747         if(ps){
2748             node.previousSibling = ps;
2749             ps.nextSibling = node;
2750         }else{
2751             node.previousSibling = null;
2752         }
2753         node.nextSibling = refNode;
2754         refNode.previousSibling = node;
2755         node.setOwnerTree(this.getOwnerTree());
2756         this.fireEvent("insert", this.ownerTree, this, node, refNode);
2757         if(oldParent){
2758             node.fireEvent("move", this.ownerTree, node, oldParent, this, refIndex, refNode);
2759         }
2760         return node;
2761     },
2762
2763     /**
2764      * Returns the child node at the specified index.
2765      * @param {Number} index
2766      * @return {Node}
2767      */
2768     item : function(index){
2769         return this.childNodes[index];
2770     },
2771
2772     /**
2773      * Replaces one child node in this node with another.
2774      * @param {Node} newChild The replacement node
2775      * @param {Node} oldChild The node to replace
2776      * @return {Node} The replaced node
2777      */
2778     replaceChild : function(newChild, oldChild){
2779         this.insertBefore(newChild, oldChild);
2780         this.removeChild(oldChild);
2781         return oldChild;
2782     },
2783
2784     /**
2785      * Returns the index of a child node
2786      * @param {Node} node
2787      * @return {Number} The index of the node or -1 if it was not found
2788      */
2789     indexOf : function(child){
2790         return this.childNodes.indexOf(child);
2791     },
2792
2793     /**
2794      * Returns the tree this node is in.
2795      * @return {Tree}
2796      */
2797     getOwnerTree : function(){
2798         // if it doesn't have one, look for one
2799         if(!this.ownerTree){
2800             var p = this;
2801             while(p){
2802                 if(p.ownerTree){
2803                     this.ownerTree = p.ownerTree;
2804                     break;
2805                 }
2806                 p = p.parentNode;
2807             }
2808         }
2809         return this.ownerTree;
2810     },
2811
2812     /**
2813      * Returns depth of this node (the root node has a depth of 0)
2814      * @return {Number}
2815      */
2816     getDepth : function(){
2817         var depth = 0;
2818         var p = this;
2819         while(p.parentNode){
2820             ++depth;
2821             p = p.parentNode;
2822         }
2823         return depth;
2824     },
2825
2826     // private
2827     setOwnerTree : function(tree){
2828         // if it's move, we need to update everyone
2829         if(tree != this.ownerTree){
2830             if(this.ownerTree){
2831                 this.ownerTree.unregisterNode(this);
2832             }
2833             this.ownerTree = tree;
2834             var cs = this.childNodes;
2835             for(var i = 0, len = cs.length; i < len; i++) {
2836                 cs[i].setOwnerTree(tree);
2837             }
2838             if(tree){
2839                 tree.registerNode(this);
2840             }
2841         }
2842     },
2843
2844     /**
2845      * Returns the path for this node. The path can be used to expand or select this node programmatically.
2846      * @param {String} attr (optional) The attr to use for the path (defaults to the node's id)
2847      * @return {String} The path
2848      */
2849     getPath : function(attr){
2850         attr = attr || "id";
2851         var p = this.parentNode;
2852         var b = [this.attributes[attr]];
2853         while(p){
2854             b.unshift(p.attributes[attr]);
2855             p = p.parentNode;
2856         }
2857         var sep = this.getOwnerTree().pathSeparator;
2858         return sep + b.join(sep);
2859     },
2860
2861     /**
2862      * Bubbles up the tree from this node, calling the specified function with each node. The scope (<i>this</i>) of
2863      * function call will be the scope provided or the current node. The arguments to the function
2864      * will be the args provided or the current node. If the function returns false at any point,
2865      * the bubble is stopped.
2866      * @param {Function} fn The function to call
2867      * @param {Object} scope (optional) The scope of the function (defaults to current node)
2868      * @param {Array} args (optional) The args to call the function with (default to passing the current node)
2869      */
2870     bubble : function(fn, scope, args){
2871         var p = this;
2872         while(p){
2873             if(fn.call(scope || p, args || p) === false){
2874                 break;
2875             }
2876             p = p.parentNode;
2877         }
2878     },
2879
2880     /**
2881      * Cascades down the tree from this node, calling the specified function with each node. The scope (<i>this</i>) of
2882      * function call will be the scope provided or the current node. The arguments to the function
2883      * will be the args provided or the current node. If the function returns false at any point,
2884      * the cascade is stopped on that branch.
2885      * @param {Function} fn The function to call
2886      * @param {Object} scope (optional) The scope of the function (defaults to current node)
2887      * @param {Array} args (optional) The args to call the function with (default to passing the current node)
2888      */
2889     cascade : function(fn, scope, args){
2890         if(fn.call(scope || this, args || this) !== false){
2891             var cs = this.childNodes;
2892             for(var i = 0, len = cs.length; i < len; i++) {
2893                 cs[i].cascade(fn, scope, args);
2894             }
2895         }
2896     },
2897
2898     /**
2899      * Interates the child nodes of this node, calling the specified function with each node. The scope (<i>this</i>) of
2900      * function call will be the scope provided or the current node. The arguments to the function
2901      * will be the args provided or the current node. If the function returns false at any point,
2902      * the iteration stops.
2903      * @param {Function} fn The function to call
2904      * @param {Object} scope (optional) The scope of the function (defaults to current node)
2905      * @param {Array} args (optional) The args to call the function with (default to passing the current node)
2906      */
2907     eachChild : function(fn, scope, args){
2908         var cs = this.childNodes;
2909         for(var i = 0, len = cs.length; i < len; i++) {
2910                 if(fn.call(scope || this, args || cs[i]) === false){
2911                     break;
2912                 }
2913         }
2914     },
2915
2916     /**
2917      * Finds the first child that has the attribute with the specified value.
2918      * @param {String} attribute The attribute name
2919      * @param {Mixed} value The value to search for
2920      * @return {Node} The found child or null if none was found
2921      */
2922     findChild : function(attribute, value){
2923         var cs = this.childNodes;
2924         for(var i = 0, len = cs.length; i < len; i++) {
2925                 if(cs[i].attributes[attribute] == value){
2926                     return cs[i];
2927                 }
2928         }
2929         return null;
2930     },
2931
2932     /**
2933      * Finds the first child by a custom function. The child matches if the function passed
2934      * returns true.
2935      * @param {Function} fn
2936      * @param {Object} scope (optional)
2937      * @return {Node} The found child or null if none was found
2938      */
2939     findChildBy : function(fn, scope){
2940         var cs = this.childNodes;
2941         for(var i = 0, len = cs.length; i < len; i++) {
2942                 if(fn.call(scope||cs[i], cs[i]) === true){
2943                     return cs[i];
2944                 }
2945         }
2946         return null;
2947     },
2948
2949     /**
2950      * Sorts this nodes children using the supplied sort function
2951      * @param {Function} fn
2952      * @param {Object} scope (optional)
2953      */
2954     sort : function(fn, scope){
2955         var cs = this.childNodes;
2956         var len = cs.length;
2957         if(len > 0){
2958             var sortFn = scope ? function(){fn.apply(scope, arguments);} : fn;
2959             cs.sort(sortFn);
2960             for(var i = 0; i < len; i++){
2961                 var n = cs[i];
2962                 n.previousSibling = cs[i-1];
2963                 n.nextSibling = cs[i+1];
2964                 if(i == 0){
2965                     this.setFirstChild(n);
2966                 }
2967                 if(i == len-1){
2968                     this.setLastChild(n);
2969                 }
2970             }
2971         }
2972     },
2973
2974     /**
2975      * Returns true if this node is an ancestor (at any point) of the passed node.
2976      * @param {Node} node
2977      * @return {Boolean}
2978      */
2979     contains : function(node){
2980         return node.isAncestor(this);
2981     },
2982
2983     /**
2984      * Returns true if the passed node is an ancestor (at any point) of this node.
2985      * @param {Node} node
2986      * @return {Boolean}
2987      */
2988     isAncestor : function(node){
2989         var p = this.parentNode;
2990         while(p){
2991             if(p == node){
2992                 return true;
2993             }
2994             p = p.parentNode;
2995         }
2996         return false;
2997     },
2998
2999     toString : function(){
3000         return "[Node"+(this.id?" "+this.id:"")+"]";
3001     }
3002 });/*
3003  * Based on:
3004  * Ext JS Library 1.1.1
3005  * Copyright(c) 2006-2007, Ext JS, LLC.
3006  *
3007  * Originally Released Under LGPL - original licence link has changed is not relivant.
3008  *
3009  * Fork - LGPL
3010  * <script type="text/javascript">
3011  */
3012
3013
3014 /**
3015  * @class Roo.Shadow
3016  * Simple class that can provide a shadow effect for any element.  Note that the element MUST be absolutely positioned,
3017  * and the shadow does not provide any shimming.  This should be used only in simple cases -- for more advanced
3018  * functionality that can also provide the same shadow effect, see the {@link Roo.Layer} class.
3019  * @constructor
3020  * Create a new Shadow
3021  * @param {Object} config The config object
3022  */
3023 Roo.Shadow = function(config){
3024     Roo.apply(this, config);
3025     if(typeof this.mode != "string"){
3026         this.mode = this.defaultMode;
3027     }
3028     var o = this.offset, a = {h: 0};
3029     var rad = Math.floor(this.offset/2);
3030     switch(this.mode.toLowerCase()){ // all this hideous nonsense calculates the various offsets for shadows
3031         case "drop":
3032             a.w = 0;
3033             a.l = a.t = o;
3034             a.t -= 1;
3035             if(Roo.isIE){
3036                 a.l -= this.offset + rad;
3037                 a.t -= this.offset + rad;
3038                 a.w -= rad;
3039                 a.h -= rad;
3040                 a.t += 1;
3041             }
3042         break;
3043         case "sides":
3044             a.w = (o*2);
3045             a.l = -o;
3046             a.t = o-1;
3047             if(Roo.isIE){
3048                 a.l -= (this.offset - rad);
3049                 a.t -= this.offset + rad;
3050                 a.l += 1;
3051                 a.w -= (this.offset - rad)*2;
3052                 a.w -= rad + 1;
3053                 a.h -= 1;
3054             }
3055         break;
3056         case "frame":
3057             a.w = a.h = (o*2);
3058             a.l = a.t = -o;
3059             a.t += 1;
3060             a.h -= 2;
3061             if(Roo.isIE){
3062                 a.l -= (this.offset - rad);
3063                 a.t -= (this.offset - rad);
3064                 a.l += 1;
3065                 a.w -= (this.offset + rad + 1);
3066                 a.h -= (this.offset + rad);
3067                 a.h += 1;
3068             }
3069         break;
3070     };
3071
3072     this.adjusts = a;
3073 };
3074
3075 Roo.Shadow.prototype = {
3076     /**
3077      * @cfg {String} mode
3078      * The shadow display mode.  Supports the following options:<br />
3079      * sides: Shadow displays on both sides and bottom only<br />
3080      * frame: Shadow displays equally on all four sides<br />
3081      * drop: Traditional bottom-right drop shadow (default)
3082      */
3083     mode: false,
3084     /**
3085      * @cfg {String} offset
3086      * The number of pixels to offset the shadow from the element (defaults to 4)
3087      */
3088     offset: 4,
3089
3090     // private
3091     defaultMode: "drop",
3092
3093     /**
3094      * Displays the shadow under the target element
3095      * @param {String/HTMLElement/Element} targetEl The id or element under which the shadow should display
3096      */
3097     show : function(target){
3098         target = Roo.get(target);
3099         if(!this.el){
3100             this.el = Roo.Shadow.Pool.pull();
3101             if(this.el.dom.nextSibling != target.dom){
3102                 this.el.insertBefore(target);
3103             }
3104         }
3105         this.el.setStyle("z-index", this.zIndex || parseInt(target.getStyle("z-index"), 10)-1);
3106         if(Roo.isIE){
3107             this.el.dom.style.filter="progid:DXImageTransform.Microsoft.alpha(opacity=50) progid:DXImageTransform.Microsoft.Blur(pixelradius="+(this.offset)+")";
3108         }
3109         this.realign(
3110             target.getLeft(true),
3111             target.getTop(true),
3112             target.getWidth(),
3113             target.getHeight()
3114         );
3115         this.el.dom.style.display = "block";
3116     },
3117
3118     /**
3119      * Returns true if the shadow is visible, else false
3120      */
3121     isVisible : function(){
3122         return this.el ? true : false;  
3123     },
3124
3125     /**
3126      * Direct alignment when values are already available. Show must be called at least once before
3127      * calling this method to ensure it is initialized.
3128      * @param {Number} left The target element left position
3129      * @param {Number} top The target element top position
3130      * @param {Number} width The target element width
3131      * @param {Number} height The target element height
3132      */
3133     realign : function(l, t, w, h){
3134         if(!this.el){
3135             return;
3136         }
3137         var a = this.adjusts, d = this.el.dom, s = d.style;
3138         var iea = 0;
3139         s.left = (l+a.l)+"px";
3140         s.top = (t+a.t)+"px";
3141         var sw = (w+a.w), sh = (h+a.h), sws = sw +"px", shs = sh + "px";
3142  
3143         if(s.width != sws || s.height != shs){
3144             s.width = sws;
3145             s.height = shs;
3146             if(!Roo.isIE){
3147                 var cn = d.childNodes;
3148                 var sww = Math.max(0, (sw-12))+"px";
3149                 cn[0].childNodes[1].style.width = sww;
3150                 cn[1].childNodes[1].style.width = sww;
3151                 cn[2].childNodes[1].style.width = sww;
3152                 cn[1].style.height = Math.max(0, (sh-12))+"px";
3153             }
3154         }
3155     },
3156
3157     /**
3158      * Hides this shadow
3159      */
3160     hide : function(){
3161         if(this.el){
3162             this.el.dom.style.display = "none";
3163             Roo.Shadow.Pool.push(this.el);
3164             delete this.el;
3165         }
3166     },
3167
3168     /**
3169      * Adjust the z-index of this shadow
3170      * @param {Number} zindex The new z-index
3171      */
3172     setZIndex : function(z){
3173         this.zIndex = z;
3174         if(this.el){
3175             this.el.setStyle("z-index", z);
3176         }
3177     }
3178 };
3179
3180 // Private utility class that manages the internal Shadow cache
3181 Roo.Shadow.Pool = function(){
3182     var p = [];
3183     var markup = Roo.isIE ?
3184                  '<div class="x-ie-shadow"></div>' :
3185                  '<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>';
3186     return {
3187         pull : function(){
3188             var sh = p.shift();
3189             if(!sh){
3190                 sh = Roo.get(Roo.DomHelper.insertHtml("beforeBegin", document.body.firstChild, markup));
3191                 sh.autoBoxAdjust = false;
3192             }
3193             return sh;
3194         },
3195
3196         push : function(sh){
3197             p.push(sh);
3198         }
3199     };
3200 }();/*
3201  * Based on:
3202  * Ext JS Library 1.1.1
3203  * Copyright(c) 2006-2007, Ext JS, LLC.
3204  *
3205  * Originally Released Under LGPL - original licence link has changed is not relivant.
3206  *
3207  * Fork - LGPL
3208  * <script type="text/javascript">
3209  */
3210
3211
3212 /**
3213  * @class Roo.SplitBar
3214  * @extends Roo.util.Observable
3215  * Creates draggable splitter bar functionality from two elements (element to be dragged and element to be resized).
3216  * <br><br>
3217  * Usage:
3218  * <pre><code>
3219 var split = new Roo.SplitBar("elementToDrag", "elementToSize",
3220                    Roo.SplitBar.HORIZONTAL, Roo.SplitBar.LEFT);
3221 split.setAdapter(new Roo.SplitBar.AbsoluteLayoutAdapter("container"));
3222 split.minSize = 100;
3223 split.maxSize = 600;
3224 split.animate = true;
3225 split.on('moved', splitterMoved);
3226 </code></pre>
3227  * @constructor
3228  * Create a new SplitBar
3229  * @param {String/HTMLElement/Roo.Element} dragElement The element to be dragged and act as the SplitBar. 
3230  * @param {String/HTMLElement/Roo.Element} resizingElement The element to be resized based on where the SplitBar element is dragged 
3231  * @param {Number} orientation (optional) Either Roo.SplitBar.HORIZONTAL or Roo.SplitBar.VERTICAL. (Defaults to HORIZONTAL)
3232  * @param {Number} placement (optional) Either Roo.SplitBar.LEFT or Roo.SplitBar.RIGHT for horizontal or  
3233                         Roo.SplitBar.TOP or Roo.SplitBar.BOTTOM for vertical. (By default, this is determined automatically by the initial
3234                         position of the SplitBar).
3235  */
3236 Roo.SplitBar = function(dragElement, resizingElement, orientation, placement, existingProxy){
3237     
3238     /** @private */
3239     this.el = Roo.get(dragElement, true);
3240     this.el.dom.unselectable = "on";
3241     /** @private */
3242     this.resizingEl = Roo.get(resizingElement, true);
3243
3244     /**
3245      * @private
3246      * The orientation of the split. Either Roo.SplitBar.HORIZONTAL or Roo.SplitBar.VERTICAL. (Defaults to HORIZONTAL)
3247      * Note: If this is changed after creating the SplitBar, the placement property must be manually updated
3248      * @type Number
3249      */
3250     this.orientation = orientation || Roo.SplitBar.HORIZONTAL;
3251     
3252     /**
3253      * The minimum size of the resizing element. (Defaults to 0)
3254      * @type Number
3255      */
3256     this.minSize = 0;
3257     
3258     /**
3259      * The maximum size of the resizing element. (Defaults to 2000)
3260      * @type Number
3261      */
3262     this.maxSize = 2000;
3263     
3264     /**
3265      * Whether to animate the transition to the new size
3266      * @type Boolean
3267      */
3268     this.animate = false;
3269     
3270     /**
3271      * Whether to create a transparent shim that overlays the page when dragging, enables dragging across iframes.
3272      * @type Boolean
3273      */
3274     this.useShim = false;
3275     
3276     /** @private */
3277     this.shim = null;
3278     
3279     if(!existingProxy){
3280         /** @private */
3281         this.proxy = Roo.SplitBar.createProxy(this.orientation);
3282     }else{
3283         this.proxy = Roo.get(existingProxy).dom;
3284     }
3285     /** @private */
3286     this.dd = new Roo.dd.DDProxy(this.el.dom.id, "XSplitBars", {dragElId : this.proxy.id});
3287     
3288     /** @private */
3289     this.dd.b4StartDrag = this.onStartProxyDrag.createDelegate(this);
3290     
3291     /** @private */
3292     this.dd.endDrag = this.onEndProxyDrag.createDelegate(this);
3293     
3294     /** @private */
3295     this.dragSpecs = {};
3296     
3297     /**
3298      * @private The adapter to use to positon and resize elements
3299      */
3300     this.adapter = new Roo.SplitBar.BasicLayoutAdapter();
3301     this.adapter.init(this);
3302     
3303     if(this.orientation == Roo.SplitBar.HORIZONTAL){
3304         /** @private */
3305         this.placement = placement || (this.el.getX() > this.resizingEl.getX() ? Roo.SplitBar.LEFT : Roo.SplitBar.RIGHT);
3306         this.el.addClass("x-splitbar-h");
3307     }else{
3308         /** @private */
3309         this.placement = placement || (this.el.getY() > this.resizingEl.getY() ? Roo.SplitBar.TOP : Roo.SplitBar.BOTTOM);
3310         this.el.addClass("x-splitbar-v");
3311     }
3312     
3313     this.addEvents({
3314         /**
3315          * @event resize
3316          * Fires when the splitter is moved (alias for {@link #event-moved})
3317          * @param {Roo.SplitBar} this
3318          * @param {Number} newSize the new width or height
3319          */
3320         "resize" : true,
3321         /**
3322          * @event moved
3323          * Fires when the splitter is moved
3324          * @param {Roo.SplitBar} this
3325          * @param {Number} newSize the new width or height
3326          */
3327         "moved" : true,
3328         /**
3329          * @event beforeresize
3330          * Fires before the splitter is dragged
3331          * @param {Roo.SplitBar} this
3332          */
3333         "beforeresize" : true,
3334
3335         "beforeapply" : true
3336     });
3337
3338     Roo.util.Observable.call(this);
3339 };
3340
3341 Roo.extend(Roo.SplitBar, Roo.util.Observable, {
3342     onStartProxyDrag : function(x, y){
3343         this.fireEvent("beforeresize", this);
3344         if(!this.overlay){
3345             var o = Roo.DomHelper.insertFirst(document.body,  {cls: "x-drag-overlay", html: "&#160;"}, true);
3346             o.unselectable();
3347             o.enableDisplayMode("block");
3348             // all splitbars share the same overlay
3349             Roo.SplitBar.prototype.overlay = o;
3350         }
3351         this.overlay.setSize(Roo.lib.Dom.getViewWidth(true), Roo.lib.Dom.getViewHeight(true));
3352         this.overlay.show();
3353         Roo.get(this.proxy).setDisplayed("block");
3354         var size = this.adapter.getElementSize(this);
3355         this.activeMinSize = this.getMinimumSize();;
3356         this.activeMaxSize = this.getMaximumSize();;
3357         var c1 = size - this.activeMinSize;
3358         var c2 = Math.max(this.activeMaxSize - size, 0);
3359         if(this.orientation == Roo.SplitBar.HORIZONTAL){
3360             this.dd.resetConstraints();
3361             this.dd.setXConstraint(
3362                 this.placement == Roo.SplitBar.LEFT ? c1 : c2, 
3363                 this.placement == Roo.SplitBar.LEFT ? c2 : c1
3364             );
3365             this.dd.setYConstraint(0, 0);
3366         }else{
3367             this.dd.resetConstraints();
3368             this.dd.setXConstraint(0, 0);
3369             this.dd.setYConstraint(
3370                 this.placement == Roo.SplitBar.TOP ? c1 : c2, 
3371                 this.placement == Roo.SplitBar.TOP ? c2 : c1
3372             );
3373          }
3374         this.dragSpecs.startSize = size;
3375         this.dragSpecs.startPoint = [x, y];
3376         Roo.dd.DDProxy.prototype.b4StartDrag.call(this.dd, x, y);
3377     },
3378     
3379     /** 
3380      * @private Called after the drag operation by the DDProxy
3381      */
3382     onEndProxyDrag : function(e){
3383         Roo.get(this.proxy).setDisplayed(false);
3384         var endPoint = Roo.lib.Event.getXY(e);
3385         if(this.overlay){
3386             this.overlay.hide();
3387         }
3388         var newSize;
3389         if(this.orientation == Roo.SplitBar.HORIZONTAL){
3390             newSize = this.dragSpecs.startSize + 
3391                 (this.placement == Roo.SplitBar.LEFT ?
3392                     endPoint[0] - this.dragSpecs.startPoint[0] :
3393                     this.dragSpecs.startPoint[0] - endPoint[0]
3394                 );
3395         }else{
3396             newSize = this.dragSpecs.startSize + 
3397                 (this.placement == Roo.SplitBar.TOP ?
3398                     endPoint[1] - this.dragSpecs.startPoint[1] :
3399                     this.dragSpecs.startPoint[1] - endPoint[1]
3400                 );
3401         }
3402         newSize = Math.min(Math.max(newSize, this.activeMinSize), this.activeMaxSize);
3403         if(newSize != this.dragSpecs.startSize){
3404             if(this.fireEvent('beforeapply', this, newSize) !== false){
3405                 this.adapter.setElementSize(this, newSize);
3406                 this.fireEvent("moved", this, newSize);
3407                 this.fireEvent("resize", this, newSize);
3408             }
3409         }
3410     },
3411     
3412     /**
3413      * Get the adapter this SplitBar uses
3414      * @return The adapter object
3415      */
3416     getAdapter : function(){
3417         return this.adapter;
3418     },
3419     
3420     /**
3421      * Set the adapter this SplitBar uses
3422      * @param {Object} adapter A SplitBar adapter object
3423      */
3424     setAdapter : function(adapter){
3425         this.adapter = adapter;
3426         this.adapter.init(this);
3427     },
3428     
3429     /**
3430      * Gets the minimum size for the resizing element
3431      * @return {Number} The minimum size
3432      */
3433     getMinimumSize : function(){
3434         return this.minSize;
3435     },
3436     
3437     /**
3438      * Sets the minimum size for the resizing element
3439      * @param {Number} minSize The minimum size
3440      */
3441     setMinimumSize : function(minSize){
3442         this.minSize = minSize;
3443     },
3444     
3445     /**
3446      * Gets the maximum size for the resizing element
3447      * @return {Number} The maximum size
3448      */
3449     getMaximumSize : function(){
3450         return this.maxSize;
3451     },
3452     
3453     /**
3454      * Sets the maximum size for the resizing element
3455      * @param {Number} maxSize The maximum size
3456      */
3457     setMaximumSize : function(maxSize){
3458         this.maxSize = maxSize;
3459     },
3460     
3461     /**
3462      * Sets the initialize size for the resizing element
3463      * @param {Number} size The initial size
3464      */
3465     setCurrentSize : function(size){
3466         var oldAnimate = this.animate;
3467         this.animate = false;
3468         this.adapter.setElementSize(this, size);
3469         this.animate = oldAnimate;
3470     },
3471     
3472     /**
3473      * Destroy this splitbar. 
3474      * @param {Boolean} removeEl True to remove the element
3475      */
3476     destroy : function(removeEl){
3477         if(this.shim){
3478             this.shim.remove();
3479         }
3480         this.dd.unreg();
3481         this.proxy.parentNode.removeChild(this.proxy);
3482         if(removeEl){
3483             this.el.remove();
3484         }
3485     }
3486 });
3487
3488 /**
3489  * @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.
3490  */
3491 Roo.SplitBar.createProxy = function(dir){
3492     var proxy = new Roo.Element(document.createElement("div"));
3493     proxy.unselectable();
3494     var cls = 'x-splitbar-proxy';
3495     proxy.addClass(cls + ' ' + (dir == Roo.SplitBar.HORIZONTAL ? cls +'-h' : cls + '-v'));
3496     document.body.appendChild(proxy.dom);
3497     return proxy.dom;
3498 };
3499
3500 /** 
3501  * @class Roo.SplitBar.BasicLayoutAdapter
3502  * Default Adapter. It assumes the splitter and resizing element are not positioned
3503  * elements and only gets/sets the width of the element. Generally used for table based layouts.
3504  */
3505 Roo.SplitBar.BasicLayoutAdapter = function(){
3506 };
3507
3508 Roo.SplitBar.BasicLayoutAdapter.prototype = {
3509     // do nothing for now
3510     init : function(s){
3511     
3512     },
3513     /**
3514      * Called before drag operations to get the current size of the resizing element. 
3515      * @param {Roo.SplitBar} s The SplitBar using this adapter
3516      */
3517      getElementSize : function(s){
3518         if(s.orientation == Roo.SplitBar.HORIZONTAL){
3519             return s.resizingEl.getWidth();
3520         }else{
3521             return s.resizingEl.getHeight();
3522         }
3523     },
3524     
3525     /**
3526      * Called after drag operations to set the size of the resizing element.
3527      * @param {Roo.SplitBar} s The SplitBar using this adapter
3528      * @param {Number} newSize The new size to set
3529      * @param {Function} onComplete A function to be invoked when resizing is complete
3530      */
3531     setElementSize : function(s, newSize, onComplete){
3532         if(s.orientation == Roo.SplitBar.HORIZONTAL){
3533             if(!s.animate){
3534                 s.resizingEl.setWidth(newSize);
3535                 if(onComplete){
3536                     onComplete(s, newSize);
3537                 }
3538             }else{
3539                 s.resizingEl.setWidth(newSize, true, .1, onComplete, 'easeOut');
3540             }
3541         }else{
3542             
3543             if(!s.animate){
3544                 s.resizingEl.setHeight(newSize);
3545                 if(onComplete){
3546                     onComplete(s, newSize);
3547                 }
3548             }else{
3549                 s.resizingEl.setHeight(newSize, true, .1, onComplete, 'easeOut');
3550             }
3551         }
3552     }
3553 };
3554
3555 /** 
3556  *@class Roo.SplitBar.AbsoluteLayoutAdapter
3557  * @extends Roo.SplitBar.BasicLayoutAdapter
3558  * Adapter that  moves the splitter element to align with the resized sizing element. 
3559  * Used with an absolute positioned SplitBar.
3560  * @param {String/HTMLElement/Roo.Element} container The container that wraps around the absolute positioned content. If it's
3561  * document.body, make sure you assign an id to the body element.
3562  */
3563 Roo.SplitBar.AbsoluteLayoutAdapter = function(container){
3564     this.basic = new Roo.SplitBar.BasicLayoutAdapter();
3565     this.container = Roo.get(container);
3566 };
3567
3568 Roo.SplitBar.AbsoluteLayoutAdapter.prototype = {
3569     init : function(s){
3570         this.basic.init(s);
3571     },
3572     
3573     getElementSize : function(s){
3574         return this.basic.getElementSize(s);
3575     },
3576     
3577     setElementSize : function(s, newSize, onComplete){
3578         this.basic.setElementSize(s, newSize, this.moveSplitter.createDelegate(this, [s]));
3579     },
3580     
3581     moveSplitter : function(s){
3582         var yes = Roo.SplitBar;
3583         switch(s.placement){
3584             case yes.LEFT:
3585                 s.el.setX(s.resizingEl.getRight());
3586                 break;
3587             case yes.RIGHT:
3588                 s.el.setStyle("right", (this.container.getWidth() - s.resizingEl.getLeft()) + "px");
3589                 break;
3590             case yes.TOP:
3591                 s.el.setY(s.resizingEl.getBottom());
3592                 break;
3593             case yes.BOTTOM:
3594                 s.el.setY(s.resizingEl.getTop() - s.el.getHeight());
3595                 break;
3596         }
3597     }
3598 };
3599
3600 /**
3601  * Orientation constant - Create a vertical SplitBar
3602  * @static
3603  * @type Number
3604  */
3605 Roo.SplitBar.VERTICAL = 1;
3606
3607 /**
3608  * Orientation constant - Create a horizontal SplitBar
3609  * @static
3610  * @type Number
3611  */
3612 Roo.SplitBar.HORIZONTAL = 2;
3613
3614 /**
3615  * Placement constant - The resizing element is to the left of the splitter element
3616  * @static
3617  * @type Number
3618  */
3619 Roo.SplitBar.LEFT = 1;
3620
3621 /**
3622  * Placement constant - The resizing element is to the right of the splitter element
3623  * @static
3624  * @type Number
3625  */
3626 Roo.SplitBar.RIGHT = 2;
3627
3628 /**
3629  * Placement constant - The resizing element is positioned above the splitter element
3630  * @static
3631  * @type Number
3632  */
3633 Roo.SplitBar.TOP = 3;
3634
3635 /**
3636  * Placement constant - The resizing element is positioned under splitter element
3637  * @static
3638  * @type Number
3639  */
3640 Roo.SplitBar.BOTTOM = 4;
3641 /*
3642  * Based on:
3643  * Ext JS Library 1.1.1
3644  * Copyright(c) 2006-2007, Ext JS, LLC.
3645  *
3646  * Originally Released Under LGPL - original licence link has changed is not relivant.
3647  *
3648  * Fork - LGPL
3649  * <script type="text/javascript">
3650  */
3651
3652 /**
3653  * @class Roo.View
3654  * @extends Roo.util.Observable
3655  * Create a "View" for an element based on a data model or UpdateManager and the supplied DomHelper template. 
3656  * This class also supports single and multi selection modes. <br>
3657  * Create a data model bound view:
3658  <pre><code>
3659  var store = new Roo.data.Store(...);
3660
3661  var view = new Roo.View({
3662     el : "my-element",
3663     tpl : '&lt;div id="{0}"&gt;{2} - {1}&lt;/div&gt;', // auto create template
3664  
3665     singleSelect: true,
3666     selectedClass: "ydataview-selected",
3667     store: store
3668  });
3669
3670  // listen for node click?
3671  view.on("click", function(vw, index, node, e){
3672  alert('Node "' + node.id + '" at index: ' + index + " was clicked.");
3673  });
3674
3675  // load XML data
3676  dataModel.load("foobar.xml");
3677  </code></pre>
3678  For an example of creating a JSON/UpdateManager view, see {@link Roo.JsonView}.
3679  * <br><br>
3680  * <b>Note: The root of your template must be a single node. Table/row implementations may work but are not supported due to
3681  * IE"s limited insertion support with tables and Opera"s faulty event bubbling.</b>
3682  * 
3683  * Note: old style constructor is still suported (container, template, config)
3684  * 
3685  * @constructor
3686  * Create a new View
3687  * @param {Object} config The config object
3688  * 
3689  */
3690 Roo.View = function(config, depreciated_tpl, depreciated_config){
3691     
3692     this.parent = false;
3693     
3694     if (typeof(depreciated_tpl) == 'undefined') {
3695         // new way.. - universal constructor.
3696         Roo.apply(this, config);
3697         this.el  = Roo.get(this.el);
3698     } else {
3699         // old format..
3700         this.el  = Roo.get(config);
3701         this.tpl = depreciated_tpl;
3702         Roo.apply(this, depreciated_config);
3703     }
3704     this.wrapEl  = this.el.wrap().wrap();
3705     ///this.el = this.wrapEla.appendChild(document.createElement("div"));
3706     
3707     
3708     if(typeof(this.tpl) == "string"){
3709         this.tpl = new Roo.Template(this.tpl);
3710     } else {
3711         // support xtype ctors..
3712         this.tpl = new Roo.factory(this.tpl, Roo);
3713     }
3714     
3715     
3716     this.tpl.compile();
3717     
3718     /** @private */
3719     this.addEvents({
3720         /**
3721          * @event beforeclick
3722          * Fires before a click is processed. Returns false to cancel the default action.
3723          * @param {Roo.View} this
3724          * @param {Number} index The index of the target node
3725          * @param {HTMLElement} node The target node
3726          * @param {Roo.EventObject} e The raw event object
3727          */
3728             "beforeclick" : true,
3729         /**
3730          * @event click
3731          * Fires when a template node is clicked.
3732          * @param {Roo.View} this
3733          * @param {Number} index The index of the target node
3734          * @param {HTMLElement} node The target node
3735          * @param {Roo.EventObject} e The raw event object
3736          */
3737             "click" : true,
3738         /**
3739          * @event dblclick
3740          * Fires when a template node is double clicked.
3741          * @param {Roo.View} this
3742          * @param {Number} index The index of the target node
3743          * @param {HTMLElement} node The target node
3744          * @param {Roo.EventObject} e The raw event object
3745          */
3746             "dblclick" : true,
3747         /**
3748          * @event contextmenu
3749          * Fires when a template node is right clicked.
3750          * @param {Roo.View} this
3751          * @param {Number} index The index of the target node
3752          * @param {HTMLElement} node The target node
3753          * @param {Roo.EventObject} e The raw event object
3754          */
3755             "contextmenu" : true,
3756         /**
3757          * @event selectionchange
3758          * Fires when the selected nodes change.
3759          * @param {Roo.View} this
3760          * @param {Array} selections Array of the selected nodes
3761          */
3762             "selectionchange" : true,
3763     
3764         /**
3765          * @event beforeselect
3766          * Fires before a selection is made. If any handlers return false, the selection is cancelled.
3767          * @param {Roo.View} this
3768          * @param {HTMLElement} node The node to be selected
3769          * @param {Array} selections Array of currently selected nodes
3770          */
3771             "beforeselect" : true,
3772         /**
3773          * @event preparedata
3774          * Fires on every row to render, to allow you to change the data.
3775          * @param {Roo.View} this
3776          * @param {Object} data to be rendered (change this)
3777          */
3778           "preparedata" : true
3779           
3780           
3781         });
3782
3783
3784
3785     this.el.on({
3786         "click": this.onClick,
3787         "dblclick": this.onDblClick,
3788         "contextmenu": this.onContextMenu,
3789         scope:this
3790     });
3791
3792     this.selections = [];
3793     this.nodes = [];
3794     this.cmp = new Roo.CompositeElementLite([]);
3795     if(this.store){
3796         this.store = Roo.factory(this.store, Roo.data);
3797         this.setStore(this.store, true);
3798     }
3799     
3800     if ( this.footer && this.footer.xtype) {
3801            
3802          var fctr = this.wrapEl.appendChild(document.createElement("div"));
3803         
3804         this.footer.dataSource = this.store;
3805         this.footer.container = fctr;
3806         this.footer = Roo.factory(this.footer, Roo);
3807         fctr.insertFirst(this.el);
3808         
3809         // this is a bit insane - as the paging toolbar seems to detach the el..
3810 //        dom.parentNode.parentNode.parentNode
3811          // they get detached?
3812     }
3813     
3814     
3815     Roo.View.superclass.constructor.call(this);
3816     
3817     
3818 };
3819
3820 Roo.extend(Roo.View, Roo.util.Observable, {
3821     
3822      /**
3823      * @cfg {Roo.data.Store} store Data store to load data from.
3824      */
3825     store : false,
3826     
3827     /**
3828      * @cfg {String|Roo.Element} el The container element.
3829      */
3830     el : '',
3831     
3832     /**
3833      * @cfg {String|Roo.Template} tpl The template used by this View 
3834      */
3835     tpl : false,
3836     /**
3837      * @cfg {String} dataName the named area of the template to use as the data area
3838      *                          Works with domtemplates roo-name="name"
3839      */
3840     dataName: false,
3841     /**
3842      * @cfg {String} selectedClass The css class to add to selected nodes
3843      */
3844     selectedClass : "x-view-selected",
3845      /**
3846      * @cfg {String} emptyText The empty text to show when nothing is loaded.
3847      */
3848     emptyText : "",
3849     
3850     /**
3851      * @cfg {String} text to display on mask (default Loading)
3852      */
3853     mask : false,
3854     /**
3855      * @cfg {Boolean} multiSelect Allow multiple selection
3856      */
3857     multiSelect : false,
3858     /**
3859      * @cfg {Boolean} singleSelect Allow single selection
3860      */
3861     singleSelect:  false,
3862     
3863     /**
3864      * @cfg {Boolean} toggleSelect - selecting 
3865      */
3866     toggleSelect : false,
3867     
3868     /**
3869      * @cfg {Boolean} tickable - selecting 
3870      */
3871     tickable : false,
3872     
3873     /**
3874      * Returns the element this view is bound to.
3875      * @return {Roo.Element}
3876      */
3877     getEl : function(){
3878         return this.wrapEl;
3879     },
3880     
3881     
3882
3883     /**
3884      * Refreshes the view. - called by datachanged on the store. - do not call directly.
3885      */
3886     refresh : function(){
3887         //Roo.log('refresh');
3888         var t = this.tpl;
3889         
3890         // if we are using something like 'domtemplate', then
3891         // the what gets used is:
3892         // t.applySubtemplate(NAME, data, wrapping data..)
3893         // the outer template then get' applied with
3894         //     the store 'extra data'
3895         // and the body get's added to the
3896         //      roo-name="data" node?
3897         //      <span class='roo-tpl-{name}'></span> ?????
3898         
3899         
3900         
3901         this.clearSelections();
3902         this.el.update("");
3903         var html = [];
3904         var records = this.store.getRange();
3905         if(records.length < 1) {
3906             
3907             // is this valid??  = should it render a template??
3908             
3909             this.el.update(this.emptyText);
3910             return;
3911         }
3912         var el = this.el;
3913         if (this.dataName) {
3914             this.el.update(t.apply(this.store.meta)); //????
3915             el = this.el.child('.roo-tpl-' + this.dataName);
3916         }
3917         
3918         for(var i = 0, len = records.length; i < len; i++){
3919             var data = this.prepareData(records[i].data, i, records[i]);
3920             this.fireEvent("preparedata", this, data, i, records[i]);
3921             
3922             var d = Roo.apply({}, data);
3923             
3924             if(this.tickable){
3925                 Roo.apply(d, {'roo-id' : Roo.id()});
3926                 
3927                 var _this = this;
3928             
3929                 Roo.each(this.parent.item, function(item){
3930                     if(item[_this.parent.valueField] != data[_this.parent.valueField]){
3931                         return;
3932                     }
3933                     Roo.apply(d, {'roo-data-checked' : 'checked'});
3934                 });
3935             }
3936             
3937             html[html.length] = Roo.util.Format.trim(
3938                 this.dataName ?
3939                     t.applySubtemplate(this.dataName, d, this.store.meta) :
3940                     t.apply(d)
3941             );
3942         }
3943         
3944         
3945         
3946         el.update(html.join(""));
3947         this.nodes = el.dom.childNodes;
3948         this.updateIndexes(0);
3949     },
3950     
3951
3952     /**
3953      * Function to override to reformat the data that is sent to
3954      * the template for each node.
3955      * DEPRICATED - use the preparedata event handler.
3956      * @param {Array/Object} data The raw data (array of colData for a data model bound view or
3957      * a JSON object for an UpdateManager bound view).
3958      */
3959     prepareData : function(data, index, record)
3960     {
3961         this.fireEvent("preparedata", this, data, index, record);
3962         return data;
3963     },
3964
3965     onUpdate : function(ds, record){
3966         // Roo.log('on update');   
3967         this.clearSelections();
3968         var index = this.store.indexOf(record);
3969         var n = this.nodes[index];
3970         this.tpl.insertBefore(n, this.prepareData(record.data, index, record));
3971         n.parentNode.removeChild(n);
3972         this.updateIndexes(index, index);
3973     },
3974
3975     
3976     
3977 // --------- FIXME     
3978     onAdd : function(ds, records, index)
3979     {
3980         //Roo.log(['on Add', ds, records, index] );        
3981         this.clearSelections();
3982         if(this.nodes.length == 0){
3983             this.refresh();
3984             return;
3985         }
3986         var n = this.nodes[index];
3987         for(var i = 0, len = records.length; i < len; i++){
3988             var d = this.prepareData(records[i].data, i, records[i]);
3989             if(n){
3990                 this.tpl.insertBefore(n, d);
3991             }else{
3992                 
3993                 this.tpl.append(this.el, d);
3994             }
3995         }
3996         this.updateIndexes(index);
3997     },
3998
3999     onRemove : function(ds, record, index){
4000        // Roo.log('onRemove');
4001         this.clearSelections();
4002         var el = this.dataName  ?
4003             this.el.child('.roo-tpl-' + this.dataName) :
4004             this.el; 
4005         
4006         el.dom.removeChild(this.nodes[index]);
4007         this.updateIndexes(index);
4008     },
4009
4010     /**
4011      * Refresh an individual node.
4012      * @param {Number} index
4013      */
4014     refreshNode : function(index){
4015         this.onUpdate(this.store, this.store.getAt(index));
4016     },
4017
4018     updateIndexes : function(startIndex, endIndex){
4019         var ns = this.nodes;
4020         startIndex = startIndex || 0;
4021         endIndex = endIndex || ns.length - 1;
4022         for(var i = startIndex; i <= endIndex; i++){
4023             ns[i].nodeIndex = i;
4024         }
4025     },
4026
4027     /**
4028      * Changes the data store this view uses and refresh the view.
4029      * @param {Store} store
4030      */
4031     setStore : function(store, initial){
4032         if(!initial && this.store){
4033             this.store.un("datachanged", this.refresh);
4034             this.store.un("add", this.onAdd);
4035             this.store.un("remove", this.onRemove);
4036             this.store.un("update", this.onUpdate);
4037             this.store.un("clear", this.refresh);
4038             this.store.un("beforeload", this.onBeforeLoad);
4039             this.store.un("load", this.onLoad);
4040             this.store.un("loadexception", this.onLoad);
4041         }
4042         if(store){
4043           
4044             store.on("datachanged", this.refresh, this);
4045             store.on("add", this.onAdd, this);
4046             store.on("remove", this.onRemove, this);
4047             store.on("update", this.onUpdate, this);
4048             store.on("clear", this.refresh, this);
4049             store.on("beforeload", this.onBeforeLoad, this);
4050             store.on("load", this.onLoad, this);
4051             store.on("loadexception", this.onLoad, this);
4052         }
4053         
4054         if(store){
4055             this.refresh();
4056         }
4057     },
4058     /**
4059      * onbeforeLoad - masks the loading area.
4060      *
4061      */
4062     onBeforeLoad : function(store,opts)
4063     {
4064          //Roo.log('onBeforeLoad');   
4065         if (!opts.add) {
4066             this.el.update("");
4067         }
4068         this.el.mask(this.mask ? this.mask : "Loading" ); 
4069     },
4070     onLoad : function ()
4071     {
4072         this.el.unmask();
4073     },
4074     
4075
4076     /**
4077      * Returns the template node the passed child belongs to or null if it doesn't belong to one.
4078      * @param {HTMLElement} node
4079      * @return {HTMLElement} The template node
4080      */
4081     findItemFromChild : function(node){
4082         var el = this.dataName  ?
4083             this.el.child('.roo-tpl-' + this.dataName,true) :
4084             this.el.dom; 
4085         
4086         if(!node || node.parentNode == el){
4087                     return node;
4088             }
4089             var p = node.parentNode;
4090             while(p && p != el){
4091             if(p.parentNode == el){
4092                 return p;
4093             }
4094             p = p.parentNode;
4095         }
4096             return null;
4097     },
4098
4099     /** @ignore */
4100     onClick : function(e){
4101         var item = this.findItemFromChild(e.getTarget());
4102         if(item){
4103             var index = this.indexOf(item);
4104             if(this.onItemClick(item, index, e) !== false){
4105                 this.fireEvent("click", this, index, item, e);
4106             }
4107         }else{
4108             this.clearSelections();
4109         }
4110     },
4111
4112     /** @ignore */
4113     onContextMenu : function(e){
4114         var item = this.findItemFromChild(e.getTarget());
4115         if(item){
4116             this.fireEvent("contextmenu", this, this.indexOf(item), item, e);
4117         }
4118     },
4119
4120     /** @ignore */
4121     onDblClick : function(e){
4122         var item = this.findItemFromChild(e.getTarget());
4123         if(item){
4124             this.fireEvent("dblclick", this, this.indexOf(item), item, e);
4125         }
4126     },
4127
4128     onItemClick : function(item, index, e)
4129     {
4130         if(this.fireEvent("beforeclick", this, index, item, e) === false){
4131             return false;
4132         }
4133         if (this.toggleSelect) {
4134             var m = this.isSelected(item) ? 'unselect' : 'select';
4135             //Roo.log(m);
4136             var _t = this;
4137             _t[m](item, true, false);
4138             return true;
4139         }
4140         if(this.multiSelect || this.singleSelect){
4141             if(this.multiSelect && e.shiftKey && this.lastSelection){
4142                 this.select(this.getNodes(this.indexOf(this.lastSelection), index), false);
4143             }else{
4144                 this.select(item, this.multiSelect && e.ctrlKey);
4145                 this.lastSelection = item;
4146             }
4147             
4148             if(!this.tickable){
4149                 e.preventDefault();
4150             }
4151             
4152         }
4153         return true;
4154     },
4155
4156     /**
4157      * Get the number of selected nodes.
4158      * @return {Number}
4159      */
4160     getSelectionCount : function(){
4161         return this.selections.length;
4162     },
4163
4164     /**
4165      * Get the currently selected nodes.
4166      * @return {Array} An array of HTMLElements
4167      */
4168     getSelectedNodes : function(){
4169         return this.selections;
4170     },
4171
4172     /**
4173      * Get the indexes of the selected nodes.
4174      * @return {Array}
4175      */
4176     getSelectedIndexes : function(){
4177         var indexes = [], s = this.selections;
4178         for(var i = 0, len = s.length; i < len; i++){
4179             indexes.push(s[i].nodeIndex);
4180         }
4181         return indexes;
4182     },
4183
4184     /**
4185      * Clear all selections
4186      * @param {Boolean} suppressEvent (optional) true to skip firing of the selectionchange event
4187      */
4188     clearSelections : function(suppressEvent){
4189         if(this.nodes && (this.multiSelect || this.singleSelect) && this.selections.length > 0){
4190             this.cmp.elements = this.selections;
4191             this.cmp.removeClass(this.selectedClass);
4192             this.selections = [];
4193             if(!suppressEvent){
4194                 this.fireEvent("selectionchange", this, this.selections);
4195             }
4196         }
4197     },
4198
4199     /**
4200      * Returns true if the passed node is selected
4201      * @param {HTMLElement/Number} node The node or node index
4202      * @return {Boolean}
4203      */
4204     isSelected : function(node){
4205         var s = this.selections;
4206         if(s.length < 1){
4207             return false;
4208         }
4209         node = this.getNode(node);
4210         return s.indexOf(node) !== -1;
4211     },
4212
4213     /**
4214      * Selects nodes.
4215      * @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
4216      * @param {Boolean} keepExisting (optional) true to keep existing selections
4217      * @param {Boolean} suppressEvent (optional) true to skip firing of the selectionchange vent
4218      */
4219     select : function(nodeInfo, keepExisting, suppressEvent){
4220         if(nodeInfo instanceof Array){
4221             if(!keepExisting){
4222                 this.clearSelections(true);
4223             }
4224             for(var i = 0, len = nodeInfo.length; i < len; i++){
4225                 this.select(nodeInfo[i], true, true);
4226             }
4227             return;
4228         } 
4229         var node = this.getNode(nodeInfo);
4230         if(!node || this.isSelected(node)){
4231             return; // already selected.
4232         }
4233         if(!keepExisting){
4234             this.clearSelections(true);
4235         }
4236         
4237         if(this.fireEvent("beforeselect", this, node, this.selections) !== false){
4238             Roo.fly(node).addClass(this.selectedClass);
4239             this.selections.push(node);
4240             if(!suppressEvent){
4241                 this.fireEvent("selectionchange", this, this.selections);
4242             }
4243         }
4244         
4245         
4246     },
4247       /**
4248      * Unselects nodes.
4249      * @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
4250      * @param {Boolean} keepExisting (optional) true IGNORED (for campatibility with select)
4251      * @param {Boolean} suppressEvent (optional) true to skip firing of the selectionchange vent
4252      */
4253     unselect : function(nodeInfo, keepExisting, suppressEvent)
4254     {
4255         if(nodeInfo instanceof Array){
4256             Roo.each(this.selections, function(s) {
4257                 this.unselect(s, nodeInfo);
4258             }, this);
4259             return;
4260         }
4261         var node = this.getNode(nodeInfo);
4262         if(!node || !this.isSelected(node)){
4263             //Roo.log("not selected");
4264             return; // not selected.
4265         }
4266         // fireevent???
4267         var ns = [];
4268         Roo.each(this.selections, function(s) {
4269             if (s == node ) {
4270                 Roo.fly(node).removeClass(this.selectedClass);
4271
4272                 return;
4273             }
4274             ns.push(s);
4275         },this);
4276         
4277         this.selections= ns;
4278         this.fireEvent("selectionchange", this, this.selections);
4279     },
4280
4281     /**
4282      * Gets a template node.
4283      * @param {HTMLElement/String/Number} nodeInfo An HTMLElement template node, index of a template node or the id of a template node
4284      * @return {HTMLElement} The node or null if it wasn't found
4285      */
4286     getNode : function(nodeInfo){
4287         if(typeof nodeInfo == "string"){
4288             return document.getElementById(nodeInfo);
4289         }else if(typeof nodeInfo == "number"){
4290             return this.nodes[nodeInfo];
4291         }
4292         return nodeInfo;
4293     },
4294
4295     /**
4296      * Gets a range template nodes.
4297      * @param {Number} startIndex
4298      * @param {Number} endIndex
4299      * @return {Array} An array of nodes
4300      */
4301     getNodes : function(start, end){
4302         var ns = this.nodes;
4303         start = start || 0;
4304         end = typeof end == "undefined" ? ns.length - 1 : end;
4305         var nodes = [];
4306         if(start <= end){
4307             for(var i = start; i <= end; i++){
4308                 nodes.push(ns[i]);
4309             }
4310         } else{
4311             for(var i = start; i >= end; i--){
4312                 nodes.push(ns[i]);
4313             }
4314         }
4315         return nodes;
4316     },
4317
4318     /**
4319      * Finds the index of the passed node
4320      * @param {HTMLElement/String/Number} nodeInfo An HTMLElement template node, index of a template node or the id of a template node
4321      * @return {Number} The index of the node or -1
4322      */
4323     indexOf : function(node){
4324         node = this.getNode(node);
4325         if(typeof node.nodeIndex == "number"){
4326             return node.nodeIndex;
4327         }
4328         var ns = this.nodes;
4329         for(var i = 0, len = ns.length; i < len; i++){
4330             if(ns[i] == node){
4331                 return i;
4332             }
4333         }
4334         return -1;
4335     }
4336 });
4337 /*
4338  * Based on:
4339  * Ext JS Library 1.1.1
4340  * Copyright(c) 2006-2007, Ext JS, LLC.
4341  *
4342  * Originally Released Under LGPL - original licence link has changed is not relivant.
4343  *
4344  * Fork - LGPL
4345  * <script type="text/javascript">
4346  */
4347
4348 /**
4349  * @class Roo.JsonView
4350  * @extends Roo.View
4351  * Shortcut class to create a JSON + {@link Roo.UpdateManager} template view. Usage:
4352 <pre><code>
4353 var view = new Roo.JsonView({
4354     container: "my-element",
4355     tpl: '&lt;div id="{id}"&gt;{foo} - {bar}&lt;/div&gt;', // auto create template
4356     multiSelect: true, 
4357     jsonRoot: "data" 
4358 });
4359
4360 // listen for node click?
4361 view.on("click", function(vw, index, node, e){
4362     alert('Node "' + node.id + '" at index: ' + index + " was clicked.");
4363 });
4364
4365 // direct load of JSON data
4366 view.load("foobar.php");
4367
4368 // Example from my blog list
4369 var tpl = new Roo.Template(
4370     '&lt;div class="entry"&gt;' +
4371     '&lt;a class="entry-title" href="{link}"&gt;{title}&lt;/a&gt;' +
4372     "&lt;h4&gt;{date} by {author} | {comments} Comments&lt;/h4&gt;{description}" +
4373     "&lt;/div&gt;&lt;hr /&gt;"
4374 );
4375
4376 var moreView = new Roo.JsonView({
4377     container :  "entry-list", 
4378     template : tpl,
4379     jsonRoot: "posts"
4380 });
4381 moreView.on("beforerender", this.sortEntries, this);
4382 moreView.load({
4383     url: "/blog/get-posts.php",
4384     params: "allposts=true",
4385     text: "Loading Blog Entries..."
4386 });
4387 </code></pre>
4388
4389 * Note: old code is supported with arguments : (container, template, config)
4390
4391
4392  * @constructor
4393  * Create a new JsonView
4394  * 
4395  * @param {Object} config The config object
4396  * 
4397  */
4398 Roo.JsonView = function(config, depreciated_tpl, depreciated_config){
4399     
4400     
4401     Roo.JsonView.superclass.constructor.call(this, config, depreciated_tpl, depreciated_config);
4402
4403     var um = this.el.getUpdateManager();
4404     um.setRenderer(this);
4405     um.on("update", this.onLoad, this);
4406     um.on("failure", this.onLoadException, this);
4407
4408     /**
4409      * @event beforerender
4410      * Fires before rendering of the downloaded JSON data.
4411      * @param {Roo.JsonView} this
4412      * @param {Object} data The JSON data loaded
4413      */
4414     /**
4415      * @event load
4416      * Fires when data is loaded.
4417      * @param {Roo.JsonView} this
4418      * @param {Object} data The JSON data loaded
4419      * @param {Object} response The raw Connect response object
4420      */
4421     /**
4422      * @event loadexception
4423      * Fires when loading fails.
4424      * @param {Roo.JsonView} this
4425      * @param {Object} response The raw Connect response object
4426      */
4427     this.addEvents({
4428         'beforerender' : true,
4429         'load' : true,
4430         'loadexception' : true
4431     });
4432 };
4433 Roo.extend(Roo.JsonView, Roo.View, {
4434     /**
4435      * @type {String} The root property in the loaded JSON object that contains the data
4436      */
4437     jsonRoot : "",
4438
4439     /**
4440      * Refreshes the view.
4441      */
4442     refresh : function(){
4443         this.clearSelections();
4444         this.el.update("");
4445         var html = [];
4446         var o = this.jsonData;
4447         if(o && o.length > 0){
4448             for(var i = 0, len = o.length; i < len; i++){
4449                 var data = this.prepareData(o[i], i, o);
4450                 html[html.length] = this.tpl.apply(data);
4451             }
4452         }else{
4453             html.push(this.emptyText);
4454         }
4455         this.el.update(html.join(""));
4456         this.nodes = this.el.dom.childNodes;
4457         this.updateIndexes(0);
4458     },
4459
4460     /**
4461      * 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.
4462      * @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:
4463      <pre><code>
4464      view.load({
4465          url: "your-url.php",
4466          params: {param1: "foo", param2: "bar"}, // or a URL encoded string
4467          callback: yourFunction,
4468          scope: yourObject, //(optional scope)
4469          discardUrl: false,
4470          nocache: false,
4471          text: "Loading...",
4472          timeout: 30,
4473          scripts: false
4474      });
4475      </code></pre>
4476      * The only required property is <i>url</i>. The optional properties <i>nocache</i>, <i>text</i> and <i>scripts</i>
4477      * 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.
4478      * @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}
4479      * @param {Function} callback (optional) Callback when transaction is complete - called with signature (oElement, bSuccess)
4480      * @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.
4481      */
4482     load : function(){
4483         var um = this.el.getUpdateManager();
4484         um.update.apply(um, arguments);
4485     },
4486
4487     // note - render is a standard framework call...
4488     // using it for the response is really flaky... - it's called by UpdateManager normally, except when called by the XComponent/addXtype.
4489     render : function(el, response){
4490         
4491         this.clearSelections();
4492         this.el.update("");
4493         var o;
4494         try{
4495             if (response != '') {
4496                 o = Roo.util.JSON.decode(response.responseText);
4497                 if(this.jsonRoot){
4498                     
4499                     o = o[this.jsonRoot];
4500                 }
4501             }
4502         } catch(e){
4503         }
4504         /**
4505          * The current JSON data or null
4506          */
4507         this.jsonData = o;
4508         this.beforeRender();
4509         this.refresh();
4510     },
4511
4512 /**
4513  * Get the number of records in the current JSON dataset
4514  * @return {Number}
4515  */
4516     getCount : function(){
4517         return this.jsonData ? this.jsonData.length : 0;
4518     },
4519
4520 /**
4521  * Returns the JSON object for the specified node(s)
4522  * @param {HTMLElement/Array} node The node or an array of nodes
4523  * @return {Object/Array} If you pass in an array, you get an array back, otherwise
4524  * you get the JSON object for the node
4525  */
4526     getNodeData : function(node){
4527         if(node instanceof Array){
4528             var data = [];
4529             for(var i = 0, len = node.length; i < len; i++){
4530                 data.push(this.getNodeData(node[i]));
4531             }
4532             return data;
4533         }
4534         return this.jsonData[this.indexOf(node)] || null;
4535     },
4536
4537     beforeRender : function(){
4538         this.snapshot = this.jsonData;
4539         if(this.sortInfo){
4540             this.sort.apply(this, this.sortInfo);
4541         }
4542         this.fireEvent("beforerender", this, this.jsonData);
4543     },
4544
4545     onLoad : function(el, o){
4546         this.fireEvent("load", this, this.jsonData, o);
4547     },
4548
4549     onLoadException : function(el, o){
4550         this.fireEvent("loadexception", this, o);
4551     },
4552
4553 /**
4554  * Filter the data by a specific property.
4555  * @param {String} property A property on your JSON objects
4556  * @param {String/RegExp} value Either string that the property values
4557  * should start with, or a RegExp to test against the property
4558  */
4559     filter : function(property, value){
4560         if(this.jsonData){
4561             var data = [];
4562             var ss = this.snapshot;
4563             if(typeof value == "string"){
4564                 var vlen = value.length;
4565                 if(vlen == 0){
4566                     this.clearFilter();
4567                     return;
4568                 }
4569                 value = value.toLowerCase();
4570                 for(var i = 0, len = ss.length; i < len; i++){
4571                     var o = ss[i];
4572                     if(o[property].substr(0, vlen).toLowerCase() == value){
4573                         data.push(o);
4574                     }
4575                 }
4576             } else if(value.exec){ // regex?
4577                 for(var i = 0, len = ss.length; i < len; i++){
4578                     var o = ss[i];
4579                     if(value.test(o[property])){
4580                         data.push(o);
4581                     }
4582                 }
4583             } else{
4584                 return;
4585             }
4586             this.jsonData = data;
4587             this.refresh();
4588         }
4589     },
4590
4591 /**
4592  * Filter by a function. The passed function will be called with each
4593  * object in the current dataset. If the function returns true the value is kept,
4594  * otherwise it is filtered.
4595  * @param {Function} fn
4596  * @param {Object} scope (optional) The scope of the function (defaults to this JsonView)
4597  */
4598     filterBy : function(fn, scope){
4599         if(this.jsonData){
4600             var data = [];
4601             var ss = this.snapshot;
4602             for(var i = 0, len = ss.length; i < len; i++){
4603                 var o = ss[i];
4604                 if(fn.call(scope || this, o)){
4605                     data.push(o);
4606                 }
4607             }
4608             this.jsonData = data;
4609             this.refresh();
4610         }
4611     },
4612
4613 /**
4614  * Clears the current filter.
4615  */
4616     clearFilter : function(){
4617         if(this.snapshot && this.jsonData != this.snapshot){
4618             this.jsonData = this.snapshot;
4619             this.refresh();
4620         }
4621     },
4622
4623
4624 /**
4625  * Sorts the data for this view and refreshes it.
4626  * @param {String} property A property on your JSON objects to sort on
4627  * @param {String} direction (optional) "desc" or "asc" (defaults to "asc")
4628  * @param {Function} sortType (optional) A function to call to convert the data to a sortable value.
4629  */
4630     sort : function(property, dir, sortType){
4631         this.sortInfo = Array.prototype.slice.call(arguments, 0);
4632         if(this.jsonData){
4633             var p = property;
4634             var dsc = dir && dir.toLowerCase() == "desc";
4635             var f = function(o1, o2){
4636                 var v1 = sortType ? sortType(o1[p]) : o1[p];
4637                 var v2 = sortType ? sortType(o2[p]) : o2[p];
4638                 ;
4639                 if(v1 < v2){
4640                     return dsc ? +1 : -1;
4641                 } else if(v1 > v2){
4642                     return dsc ? -1 : +1;
4643                 } else{
4644                     return 0;
4645                 }
4646             };
4647             this.jsonData.sort(f);
4648             this.refresh();
4649             if(this.jsonData != this.snapshot){
4650                 this.snapshot.sort(f);
4651             }
4652         }
4653     }
4654 });/*
4655  * Based on:
4656  * Ext JS Library 1.1.1
4657  * Copyright(c) 2006-2007, Ext JS, LLC.
4658  *
4659  * Originally Released Under LGPL - original licence link has changed is not relivant.
4660  *
4661  * Fork - LGPL
4662  * <script type="text/javascript">
4663  */
4664  
4665
4666 /**
4667  * @class Roo.ColorPalette
4668  * @extends Roo.Component
4669  * Simple color palette class for choosing colors.  The palette can be rendered to any container.<br />
4670  * Here's an example of typical usage:
4671  * <pre><code>
4672 var cp = new Roo.ColorPalette({value:'993300'});  // initial selected color
4673 cp.render('my-div');
4674
4675 cp.on('select', function(palette, selColor){
4676     // do something with selColor
4677 });
4678 </code></pre>
4679  * @constructor
4680  * Create a new ColorPalette
4681  * @param {Object} config The config object
4682  */
4683 Roo.ColorPalette = function(config){
4684     Roo.ColorPalette.superclass.constructor.call(this, config);
4685     this.addEvents({
4686         /**
4687              * @event select
4688              * Fires when a color is selected
4689              * @param {ColorPalette} this
4690              * @param {String} color The 6-digit color hex code (without the # symbol)
4691              */
4692         select: true
4693     });
4694
4695     if(this.handler){
4696         this.on("select", this.handler, this.scope, true);
4697     }
4698 };
4699 Roo.extend(Roo.ColorPalette, Roo.Component, {
4700     /**
4701      * @cfg {String} itemCls
4702      * The CSS class to apply to the containing element (defaults to "x-color-palette")
4703      */
4704     itemCls : "x-color-palette",
4705     /**
4706      * @cfg {String} value
4707      * The initial color to highlight (should be a valid 6-digit color hex code without the # symbol).  Note that
4708      * the hex codes are case-sensitive.
4709      */
4710     value : null,
4711     clickEvent:'click',
4712     // private
4713     ctype: "Roo.ColorPalette",
4714
4715     /**
4716      * @cfg {Boolean} allowReselect If set to true then reselecting a color that is already selected fires the selection event
4717      */
4718     allowReselect : false,
4719
4720     /**
4721      * <p>An array of 6-digit color hex code strings (without the # symbol).  This array can contain any number
4722      * of colors, and each hex code should be unique.  The width of the palette is controlled via CSS by adjusting
4723      * the width property of the 'x-color-palette' class (or assigning a custom class), so you can balance the number
4724      * of colors with the width setting until the box is symmetrical.</p>
4725      * <p>You can override individual colors if needed:</p>
4726      * <pre><code>
4727 var cp = new Roo.ColorPalette();
4728 cp.colors[0] = "FF0000";  // change the first box to red
4729 </code></pre>
4730
4731 Or you can provide a custom array of your own for complete control:
4732 <pre><code>
4733 var cp = new Roo.ColorPalette();
4734 cp.colors = ["000000", "993300", "333300"];
4735 </code></pre>
4736      * @type Array
4737      */
4738     colors : [
4739         "000000", "993300", "333300", "003300", "003366", "000080", "333399", "333333",
4740         "800000", "FF6600", "808000", "008000", "008080", "0000FF", "666699", "808080",
4741         "FF0000", "FF9900", "99CC00", "339966", "33CCCC", "3366FF", "800080", "969696",
4742         "FF00FF", "FFCC00", "FFFF00", "00FF00", "00FFFF", "00CCFF", "993366", "C0C0C0",
4743         "FF99CC", "FFCC99", "FFFF99", "CCFFCC", "CCFFFF", "99CCFF", "CC99FF", "FFFFFF"
4744     ],
4745
4746     // private
4747     onRender : function(container, position){
4748         var t = new Roo.MasterTemplate(
4749             '<tpl><a href="#" class="color-{0}" hidefocus="on"><em><span style="background:#{0}" unselectable="on">&#160;</span></em></a></tpl>'
4750         );
4751         var c = this.colors;
4752         for(var i = 0, len = c.length; i < len; i++){
4753             t.add([c[i]]);
4754         }
4755         var el = document.createElement("div");
4756         el.className = this.itemCls;
4757         t.overwrite(el);
4758         container.dom.insertBefore(el, position);
4759         this.el = Roo.get(el);
4760         this.el.on(this.clickEvent, this.handleClick,  this, {delegate: "a"});
4761         if(this.clickEvent != 'click'){
4762             this.el.on('click', Roo.emptyFn,  this, {delegate: "a", preventDefault:true});
4763         }
4764     },
4765
4766     // private
4767     afterRender : function(){
4768         Roo.ColorPalette.superclass.afterRender.call(this);
4769         if(this.value){
4770             var s = this.value;
4771             this.value = null;
4772             this.select(s);
4773         }
4774     },
4775
4776     // private
4777     handleClick : function(e, t){
4778         e.preventDefault();
4779         if(!this.disabled){
4780             var c = t.className.match(/(?:^|\s)color-(.{6})(?:\s|$)/)[1];
4781             this.select(c.toUpperCase());
4782         }
4783     },
4784
4785     /**
4786      * Selects the specified color in the palette (fires the select event)
4787      * @param {String} color A valid 6-digit color hex code (# will be stripped if included)
4788      */
4789     select : function(color){
4790         color = color.replace("#", "");
4791         if(color != this.value || this.allowReselect){
4792             var el = this.el;
4793             if(this.value){
4794                 el.child("a.color-"+this.value).removeClass("x-color-palette-sel");
4795             }
4796             el.child("a.color-"+color).addClass("x-color-palette-sel");
4797             this.value = color;
4798             this.fireEvent("select", this, color);
4799         }
4800     }
4801 });/*
4802  * Based on:
4803  * Ext JS Library 1.1.1
4804  * Copyright(c) 2006-2007, Ext JS, LLC.
4805  *
4806  * Originally Released Under LGPL - original licence link has changed is not relivant.
4807  *
4808  * Fork - LGPL
4809  * <script type="text/javascript">
4810  */
4811  
4812 /**
4813  * @class Roo.DatePicker
4814  * @extends Roo.Component
4815  * Simple date picker class.
4816  * @constructor
4817  * Create a new DatePicker
4818  * @param {Object} config The config object
4819  */
4820 Roo.DatePicker = function(config){
4821     Roo.DatePicker.superclass.constructor.call(this, config);
4822
4823     this.value = config && config.value ?
4824                  config.value.clearTime() : new Date().clearTime();
4825
4826     this.addEvents({
4827         /**
4828              * @event select
4829              * Fires when a date is selected
4830              * @param {DatePicker} this
4831              * @param {Date} date The selected date
4832              */
4833         'select': true,
4834         /**
4835              * @event monthchange
4836              * Fires when the displayed month changes 
4837              * @param {DatePicker} this
4838              * @param {Date} date The selected month
4839              */
4840         'monthchange': true
4841     });
4842
4843     if(this.handler){
4844         this.on("select", this.handler,  this.scope || this);
4845     }
4846     // build the disabledDatesRE
4847     if(!this.disabledDatesRE && this.disabledDates){
4848         var dd = this.disabledDates;
4849         var re = "(?:";
4850         for(var i = 0; i < dd.length; i++){
4851             re += dd[i];
4852             if(i != dd.length-1) {
4853                 re += "|";
4854             }
4855         }
4856         this.disabledDatesRE = new RegExp(re + ")");
4857     }
4858 };
4859
4860 Roo.extend(Roo.DatePicker, Roo.Component, {
4861     /**
4862      * @cfg {String} todayText
4863      * The text to display on the button that selects the current date (defaults to "Today")
4864      */
4865     todayText : "Today",
4866     /**
4867      * @cfg {String} okText
4868      * The text to display on the ok button
4869      */
4870     okText : "&#160;OK&#160;", // &#160; to give the user extra clicking room
4871     /**
4872      * @cfg {String} cancelText
4873      * The text to display on the cancel button
4874      */
4875     cancelText : "Cancel",
4876     /**
4877      * @cfg {String} todayTip
4878      * The tooltip to display for the button that selects the current date (defaults to "{current date} (Spacebar)")
4879      */
4880     todayTip : "{0} (Spacebar)",
4881     /**
4882      * @cfg {Date} minDate
4883      * Minimum allowable date (JavaScript date object, defaults to null)
4884      */
4885     minDate : null,
4886     /**
4887      * @cfg {Date} maxDate
4888      * Maximum allowable date (JavaScript date object, defaults to null)
4889      */
4890     maxDate : null,
4891     /**
4892      * @cfg {String} minText
4893      * The error text to display if the minDate validation fails (defaults to "This date is before the minimum date")
4894      */
4895     minText : "This date is before the minimum date",
4896     /**
4897      * @cfg {String} maxText
4898      * The error text to display if the maxDate validation fails (defaults to "This date is after the maximum date")
4899      */
4900     maxText : "This date is after the maximum date",
4901     /**
4902      * @cfg {String} format
4903      * The default date format string which can be overriden for localization support.  The format must be
4904      * valid according to {@link Date#parseDate} (defaults to 'm/d/y').
4905      */
4906     format : "m/d/y",
4907     /**
4908      * @cfg {Array} disabledDays
4909      * An array of days to disable, 0-based. For example, [0, 6] disables Sunday and Saturday (defaults to null).
4910      */
4911     disabledDays : null,
4912     /**
4913      * @cfg {String} disabledDaysText
4914      * The tooltip to display when the date falls on a disabled day (defaults to "")
4915      */
4916     disabledDaysText : "",
4917     /**
4918      * @cfg {RegExp} disabledDatesRE
4919      * JavaScript regular expression used to disable a pattern of dates (defaults to null)
4920      */
4921     disabledDatesRE : null,
4922     /**
4923      * @cfg {String} disabledDatesText
4924      * The tooltip text to display when the date falls on a disabled date (defaults to "")
4925      */
4926     disabledDatesText : "",
4927     /**
4928      * @cfg {Boolean} constrainToViewport
4929      * True to constrain the date picker to the viewport (defaults to true)
4930      */
4931     constrainToViewport : true,
4932     /**
4933      * @cfg {Array} monthNames
4934      * An array of textual month names which can be overriden for localization support (defaults to Date.monthNames)
4935      */
4936     monthNames : Date.monthNames,
4937     /**
4938      * @cfg {Array} dayNames
4939      * An array of textual day names which can be overriden for localization support (defaults to Date.dayNames)
4940      */
4941     dayNames : Date.dayNames,
4942     /**
4943      * @cfg {String} nextText
4944      * The next month navigation button tooltip (defaults to 'Next Month (Control+Right)')
4945      */
4946     nextText: 'Next Month (Control+Right)',
4947     /**
4948      * @cfg {String} prevText
4949      * The previous month navigation button tooltip (defaults to 'Previous Month (Control+Left)')
4950      */
4951     prevText: 'Previous Month (Control+Left)',
4952     /**
4953      * @cfg {String} monthYearText
4954      * The header month selector tooltip (defaults to 'Choose a month (Control+Up/Down to move years)')
4955      */
4956     monthYearText: 'Choose a month (Control+Up/Down to move years)',
4957     /**
4958      * @cfg {Number} startDay
4959      * Day index at which the week should begin, 0-based (defaults to 0, which is Sunday)
4960      */
4961     startDay : 0,
4962     /**
4963      * @cfg {Bool} showClear
4964      * Show a clear button (usefull for date form elements that can be blank.)
4965      */
4966     
4967     showClear: false,
4968     
4969     /**
4970      * Sets the value of the date field
4971      * @param {Date} value The date to set
4972      */
4973     setValue : function(value){
4974         var old = this.value;
4975         
4976         if (typeof(value) == 'string') {
4977          
4978             value = Date.parseDate(value, this.format);
4979         }
4980         if (!value) {
4981             value = new Date();
4982         }
4983         
4984         this.value = value.clearTime(true);
4985         if(this.el){
4986             this.update(this.value);
4987         }
4988     },
4989
4990     /**
4991      * Gets the current selected value of the date field
4992      * @return {Date} The selected date
4993      */
4994     getValue : function(){
4995         return this.value;
4996     },
4997
4998     // private
4999     focus : function(){
5000         if(this.el){
5001             this.update(this.activeDate);
5002         }
5003     },
5004
5005     // privateval
5006     onRender : function(container, position){
5007         
5008         var m = [
5009              '<table cellspacing="0">',
5010                 '<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>',
5011                 '<tr><td colspan="3"><table class="x-date-inner" cellspacing="0"><thead><tr>'];
5012         var dn = this.dayNames;
5013         for(var i = 0; i < 7; i++){
5014             var d = this.startDay+i;
5015             if(d > 6){
5016                 d = d-7;
5017             }
5018             m.push("<th><span>", dn[d].substr(0,1), "</span></th>");
5019         }
5020         m[m.length] = "</tr></thead><tbody><tr>";
5021         for(var i = 0; i < 42; i++) {
5022             if(i % 7 == 0 && i != 0){
5023                 m[m.length] = "</tr><tr>";
5024             }
5025             m[m.length] = '<td><a href="#" hidefocus="on" class="x-date-date" tabIndex="1"><em><span></span></em></a></td>';
5026         }
5027         m[m.length] = '</tr></tbody></table></td></tr><tr>'+
5028             '<td colspan="3" class="x-date-bottom" align="center"></td></tr></table><div class="x-date-mp"></div>';
5029
5030         var el = document.createElement("div");
5031         el.className = "x-date-picker";
5032         el.innerHTML = m.join("");
5033
5034         container.dom.insertBefore(el, position);
5035
5036         this.el = Roo.get(el);
5037         this.eventEl = Roo.get(el.firstChild);
5038
5039         new Roo.util.ClickRepeater(this.el.child("td.x-date-left a"), {
5040             handler: this.showPrevMonth,
5041             scope: this,
5042             preventDefault:true,
5043             stopDefault:true
5044         });
5045
5046         new Roo.util.ClickRepeater(this.el.child("td.x-date-right a"), {
5047             handler: this.showNextMonth,
5048             scope: this,
5049             preventDefault:true,
5050             stopDefault:true
5051         });
5052
5053         this.eventEl.on("mousewheel", this.handleMouseWheel,  this);
5054
5055         this.monthPicker = this.el.down('div.x-date-mp');
5056         this.monthPicker.enableDisplayMode('block');
5057         
5058         var kn = new Roo.KeyNav(this.eventEl, {
5059             "left" : function(e){
5060                 e.ctrlKey ?
5061                     this.showPrevMonth() :
5062                     this.update(this.activeDate.add("d", -1));
5063             },
5064
5065             "right" : function(e){
5066                 e.ctrlKey ?
5067                     this.showNextMonth() :
5068                     this.update(this.activeDate.add("d", 1));
5069             },
5070
5071             "up" : function(e){
5072                 e.ctrlKey ?
5073                     this.showNextYear() :
5074                     this.update(this.activeDate.add("d", -7));
5075             },
5076
5077             "down" : function(e){
5078                 e.ctrlKey ?
5079                     this.showPrevYear() :
5080                     this.update(this.activeDate.add("d", 7));
5081             },
5082
5083             "pageUp" : function(e){
5084                 this.showNextMonth();
5085             },
5086
5087             "pageDown" : function(e){
5088                 this.showPrevMonth();
5089             },
5090
5091             "enter" : function(e){
5092                 e.stopPropagation();
5093                 return true;
5094             },
5095
5096             scope : this
5097         });
5098
5099         this.eventEl.on("click", this.handleDateClick,  this, {delegate: "a.x-date-date"});
5100
5101         this.eventEl.addKeyListener(Roo.EventObject.SPACE, this.selectToday,  this);
5102
5103         this.el.unselectable();
5104         
5105         this.cells = this.el.select("table.x-date-inner tbody td");
5106         this.textNodes = this.el.query("table.x-date-inner tbody span");
5107
5108         this.mbtn = new Roo.Button(this.el.child("td.x-date-middle", true), {
5109             text: "&#160;",
5110             tooltip: this.monthYearText
5111         });
5112
5113         this.mbtn.on('click', this.showMonthPicker, this);
5114         this.mbtn.el.child(this.mbtn.menuClassTarget).addClass("x-btn-with-menu");
5115
5116
5117         var today = (new Date()).dateFormat(this.format);
5118         
5119         var baseTb = new Roo.Toolbar(this.el.child("td.x-date-bottom", true));
5120         if (this.showClear) {
5121             baseTb.add( new Roo.Toolbar.Fill());
5122         }
5123         baseTb.add({
5124             text: String.format(this.todayText, today),
5125             tooltip: String.format(this.todayTip, today),
5126             handler: this.selectToday,
5127             scope: this
5128         });
5129         
5130         //var todayBtn = new Roo.Button(this.el.child("td.x-date-bottom", true), {
5131             
5132         //});
5133         if (this.showClear) {
5134             
5135             baseTb.add( new Roo.Toolbar.Fill());
5136             baseTb.add({
5137                 text: '&#160;',
5138                 cls: 'x-btn-icon x-btn-clear',
5139                 handler: function() {
5140                     //this.value = '';
5141                     this.fireEvent("select", this, '');
5142                 },
5143                 scope: this
5144             });
5145         }
5146         
5147         
5148         if(Roo.isIE){
5149             this.el.repaint();
5150         }
5151         this.update(this.value);
5152     },
5153
5154     createMonthPicker : function(){
5155         if(!this.monthPicker.dom.firstChild){
5156             var buf = ['<table border="0" cellspacing="0">'];
5157             for(var i = 0; i < 6; i++){
5158                 buf.push(
5159                     '<tr><td class="x-date-mp-month"><a href="#">', this.monthNames[i].substr(0, 3), '</a></td>',
5160                     '<td class="x-date-mp-month x-date-mp-sep"><a href="#">', this.monthNames[i+6].substr(0, 3), '</a></td>',
5161                     i == 0 ?
5162                     '<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>' :
5163                     '<td class="x-date-mp-year"><a href="#"></a></td><td class="x-date-mp-year"><a href="#"></a></td></tr>'
5164                 );
5165             }
5166             buf.push(
5167                 '<tr class="x-date-mp-btns"><td colspan="4"><button type="button" class="x-date-mp-ok">',
5168                     this.okText,
5169                     '</button><button type="button" class="x-date-mp-cancel">',
5170                     this.cancelText,
5171                     '</button></td></tr>',
5172                 '</table>'
5173             );
5174             this.monthPicker.update(buf.join(''));
5175             this.monthPicker.on('click', this.onMonthClick, this);
5176             this.monthPicker.on('dblclick', this.onMonthDblClick, this);
5177
5178             this.mpMonths = this.monthPicker.select('td.x-date-mp-month');
5179             this.mpYears = this.monthPicker.select('td.x-date-mp-year');
5180
5181             this.mpMonths.each(function(m, a, i){
5182                 i += 1;
5183                 if((i%2) == 0){
5184                     m.dom.xmonth = 5 + Math.round(i * .5);
5185                 }else{
5186                     m.dom.xmonth = Math.round((i-1) * .5);
5187                 }
5188             });
5189         }
5190     },
5191
5192     showMonthPicker : function(){
5193         this.createMonthPicker();
5194         var size = this.el.getSize();
5195         this.monthPicker.setSize(size);
5196         this.monthPicker.child('table').setSize(size);
5197
5198         this.mpSelMonth = (this.activeDate || this.value).getMonth();
5199         this.updateMPMonth(this.mpSelMonth);
5200         this.mpSelYear = (this.activeDate || this.value).getFullYear();
5201         this.updateMPYear(this.mpSelYear);
5202
5203         this.monthPicker.slideIn('t', {duration:.2});
5204     },
5205
5206     updateMPYear : function(y){
5207         this.mpyear = y;
5208         var ys = this.mpYears.elements;
5209         for(var i = 1; i <= 10; i++){
5210             var td = ys[i-1], y2;
5211             if((i%2) == 0){
5212                 y2 = y + Math.round(i * .5);
5213                 td.firstChild.innerHTML = y2;
5214                 td.xyear = y2;
5215             }else{
5216                 y2 = y - (5-Math.round(i * .5));
5217                 td.firstChild.innerHTML = y2;
5218                 td.xyear = y2;
5219             }
5220             this.mpYears.item(i-1)[y2 == this.mpSelYear ? 'addClass' : 'removeClass']('x-date-mp-sel');
5221         }
5222     },
5223
5224     updateMPMonth : function(sm){
5225         this.mpMonths.each(function(m, a, i){
5226             m[m.dom.xmonth == sm ? 'addClass' : 'removeClass']('x-date-mp-sel');
5227         });
5228     },
5229
5230     selectMPMonth: function(m){
5231         
5232     },
5233
5234     onMonthClick : function(e, t){
5235         e.stopEvent();
5236         var el = new Roo.Element(t), pn;
5237         if(el.is('button.x-date-mp-cancel')){
5238             this.hideMonthPicker();
5239         }
5240         else if(el.is('button.x-date-mp-ok')){
5241             this.update(new Date(this.mpSelYear, this.mpSelMonth, (this.activeDate || this.value).getDate()));
5242             this.hideMonthPicker();
5243         }
5244         else if(pn = el.up('td.x-date-mp-month', 2)){
5245             this.mpMonths.removeClass('x-date-mp-sel');
5246             pn.addClass('x-date-mp-sel');
5247             this.mpSelMonth = pn.dom.xmonth;
5248         }
5249         else if(pn = el.up('td.x-date-mp-year', 2)){
5250             this.mpYears.removeClass('x-date-mp-sel');
5251             pn.addClass('x-date-mp-sel');
5252             this.mpSelYear = pn.dom.xyear;
5253         }
5254         else if(el.is('a.x-date-mp-prev')){
5255             this.updateMPYear(this.mpyear-10);
5256         }
5257         else if(el.is('a.x-date-mp-next')){
5258             this.updateMPYear(this.mpyear+10);
5259         }
5260     },
5261
5262     onMonthDblClick : function(e, t){
5263         e.stopEvent();
5264         var el = new Roo.Element(t), pn;
5265         if(pn = el.up('td.x-date-mp-month', 2)){
5266             this.update(new Date(this.mpSelYear, pn.dom.xmonth, (this.activeDate || this.value).getDate()));
5267             this.hideMonthPicker();
5268         }
5269         else if(pn = el.up('td.x-date-mp-year', 2)){
5270             this.update(new Date(pn.dom.xyear, this.mpSelMonth, (this.activeDate || this.value).getDate()));
5271             this.hideMonthPicker();
5272         }
5273     },
5274
5275     hideMonthPicker : function(disableAnim){
5276         if(this.monthPicker){
5277             if(disableAnim === true){
5278                 this.monthPicker.hide();
5279             }else{
5280                 this.monthPicker.slideOut('t', {duration:.2});
5281             }
5282         }
5283     },
5284
5285     // private
5286     showPrevMonth : function(e){
5287         this.update(this.activeDate.add("mo", -1));
5288     },
5289
5290     // private
5291     showNextMonth : function(e){
5292         this.update(this.activeDate.add("mo", 1));
5293     },
5294
5295     // private
5296     showPrevYear : function(){
5297         this.update(this.activeDate.add("y", -1));
5298     },
5299
5300     // private
5301     showNextYear : function(){
5302         this.update(this.activeDate.add("y", 1));
5303     },
5304
5305     // private
5306     handleMouseWheel : function(e){
5307         var delta = e.getWheelDelta();
5308         if(delta > 0){
5309             this.showPrevMonth();
5310             e.stopEvent();
5311         } else if(delta < 0){
5312             this.showNextMonth();
5313             e.stopEvent();
5314         }
5315     },
5316
5317     // private
5318     handleDateClick : function(e, t){
5319         e.stopEvent();
5320         if(t.dateValue && !Roo.fly(t.parentNode).hasClass("x-date-disabled")){
5321             this.setValue(new Date(t.dateValue));
5322             this.fireEvent("select", this, this.value);
5323         }
5324     },
5325
5326     // private
5327     selectToday : function(){
5328         this.setValue(new Date().clearTime());
5329         this.fireEvent("select", this, this.value);
5330     },
5331
5332     // private
5333     update : function(date)
5334     {
5335         var vd = this.activeDate;
5336         this.activeDate = date;
5337         if(vd && this.el){
5338             var t = date.getTime();
5339             if(vd.getMonth() == date.getMonth() && vd.getFullYear() == date.getFullYear()){
5340                 this.cells.removeClass("x-date-selected");
5341                 this.cells.each(function(c){
5342                    if(c.dom.firstChild.dateValue == t){
5343                        c.addClass("x-date-selected");
5344                        setTimeout(function(){
5345                             try{c.dom.firstChild.focus();}catch(e){}
5346                        }, 50);
5347                        return false;
5348                    }
5349                 });
5350                 return;
5351             }
5352         }
5353         
5354         var days = date.getDaysInMonth();
5355         var firstOfMonth = date.getFirstDateOfMonth();
5356         var startingPos = firstOfMonth.getDay()-this.startDay;
5357
5358         if(startingPos <= this.startDay){
5359             startingPos += 7;
5360         }
5361
5362         var pm = date.add("mo", -1);
5363         var prevStart = pm.getDaysInMonth()-startingPos;
5364
5365         var cells = this.cells.elements;
5366         var textEls = this.textNodes;
5367         days += startingPos;
5368
5369         // convert everything to numbers so it's fast
5370         var day = 86400000;
5371         var d = (new Date(pm.getFullYear(), pm.getMonth(), prevStart)).clearTime();
5372         var today = new Date().clearTime().getTime();
5373         var sel = date.clearTime().getTime();
5374         var min = this.minDate ? this.minDate.clearTime() : Number.NEGATIVE_INFINITY;
5375         var max = this.maxDate ? this.maxDate.clearTime() : Number.POSITIVE_INFINITY;
5376         var ddMatch = this.disabledDatesRE;
5377         var ddText = this.disabledDatesText;
5378         var ddays = this.disabledDays ? this.disabledDays.join("") : false;
5379         var ddaysText = this.disabledDaysText;
5380         var format = this.format;
5381
5382         var setCellClass = function(cal, cell){
5383             cell.title = "";
5384             var t = d.getTime();
5385             cell.firstChild.dateValue = t;
5386             if(t == today){
5387                 cell.className += " x-date-today";
5388                 cell.title = cal.todayText;
5389             }
5390             if(t == sel){
5391                 cell.className += " x-date-selected";
5392                 setTimeout(function(){
5393                     try{cell.firstChild.focus();}catch(e){}
5394                 }, 50);
5395             }
5396             // disabling
5397             if(t < min) {
5398                 cell.className = " x-date-disabled";
5399                 cell.title = cal.minText;
5400                 return;
5401             }
5402             if(t > max) {
5403                 cell.className = " x-date-disabled";
5404                 cell.title = cal.maxText;
5405                 return;
5406             }
5407             if(ddays){
5408                 if(ddays.indexOf(d.getDay()) != -1){
5409                     cell.title = ddaysText;
5410                     cell.className = " x-date-disabled";
5411                 }
5412             }
5413             if(ddMatch && format){
5414                 var fvalue = d.dateFormat(format);
5415                 if(ddMatch.test(fvalue)){
5416                     cell.title = ddText.replace("%0", fvalue);
5417                     cell.className = " x-date-disabled";
5418                 }
5419             }
5420         };
5421
5422         var i = 0;
5423         for(; i < startingPos; i++) {
5424             textEls[i].innerHTML = (++prevStart);
5425             d.setDate(d.getDate()+1);
5426             cells[i].className = "x-date-prevday";
5427             setCellClass(this, cells[i]);
5428         }
5429         for(; i < days; i++){
5430             intDay = i - startingPos + 1;
5431             textEls[i].innerHTML = (intDay);
5432             d.setDate(d.getDate()+1);
5433             cells[i].className = "x-date-active";
5434             setCellClass(this, cells[i]);
5435         }
5436         var extraDays = 0;
5437         for(; i < 42; i++) {
5438              textEls[i].innerHTML = (++extraDays);
5439              d.setDate(d.getDate()+1);
5440              cells[i].className = "x-date-nextday";
5441              setCellClass(this, cells[i]);
5442         }
5443
5444         this.mbtn.setText(this.monthNames[date.getMonth()] + " " + date.getFullYear());
5445         this.fireEvent('monthchange', this, date);
5446         
5447         if(!this.internalRender){
5448             var main = this.el.dom.firstChild;
5449             var w = main.offsetWidth;
5450             this.el.setWidth(w + this.el.getBorderWidth("lr"));
5451             Roo.fly(main).setWidth(w);
5452             this.internalRender = true;
5453             // opera does not respect the auto grow header center column
5454             // then, after it gets a width opera refuses to recalculate
5455             // without a second pass
5456             if(Roo.isOpera && !this.secondPass){
5457                 main.rows[0].cells[1].style.width = (w - (main.rows[0].cells[0].offsetWidth+main.rows[0].cells[2].offsetWidth)) + "px";
5458                 this.secondPass = true;
5459                 this.update.defer(10, this, [date]);
5460             }
5461         }
5462         
5463         
5464     }
5465 });        /*
5466  * Based on:
5467  * Ext JS Library 1.1.1
5468  * Copyright(c) 2006-2007, Ext JS, LLC.
5469  *
5470  * Originally Released Under LGPL - original licence link has changed is not relivant.
5471  *
5472  * Fork - LGPL
5473  * <script type="text/javascript">
5474  */
5475 /**
5476  * @class Roo.TabPanel
5477  * @extends Roo.util.Observable
5478  * A lightweight tab container.
5479  * <br><br>
5480  * Usage:
5481  * <pre><code>
5482 // basic tabs 1, built from existing content
5483 var tabs = new Roo.TabPanel("tabs1");
5484 tabs.addTab("script", "View Script");
5485 tabs.addTab("markup", "View Markup");
5486 tabs.activate("script");
5487
5488 // more advanced tabs, built from javascript
5489 var jtabs = new Roo.TabPanel("jtabs");
5490 jtabs.addTab("jtabs-1", "Normal Tab", "My content was added during construction.");
5491
5492 // set up the UpdateManager
5493 var tab2 = jtabs.addTab("jtabs-2", "Ajax Tab 1");
5494 var updater = tab2.getUpdateManager();
5495 updater.setDefaultUrl("ajax1.htm");
5496 tab2.on('activate', updater.refresh, updater, true);
5497
5498 // Use setUrl for Ajax loading
5499 var tab3 = jtabs.addTab("jtabs-3", "Ajax Tab 2");
5500 tab3.setUrl("ajax2.htm", null, true);
5501
5502 // Disabled tab
5503 var tab4 = jtabs.addTab("tabs1-5", "Disabled Tab", "Can't see me cause I'm disabled");
5504 tab4.disable();
5505
5506 jtabs.activate("jtabs-1");
5507  * </code></pre>
5508  * @constructor
5509  * Create a new TabPanel.
5510  * @param {String/HTMLElement/Roo.Element} container The id, DOM element or Roo.Element container where this TabPanel is to be rendered.
5511  * @param {Object/Boolean} config Config object to set any properties for this TabPanel, or true to render the tabs on the bottom.
5512  */
5513 Roo.TabPanel = function(container, config){
5514     /**
5515     * The container element for this TabPanel.
5516     * @type Roo.Element
5517     */
5518     this.el = Roo.get(container, true);
5519     if(config){
5520         if(typeof config == "boolean"){
5521             this.tabPosition = config ? "bottom" : "top";
5522         }else{
5523             Roo.apply(this, config);
5524         }
5525     }
5526     if(this.tabPosition == "bottom"){
5527         this.bodyEl = Roo.get(this.createBody(this.el.dom));
5528         this.el.addClass("x-tabs-bottom");
5529     }
5530     this.stripWrap = Roo.get(this.createStrip(this.el.dom), true);
5531     this.stripEl = Roo.get(this.createStripList(this.stripWrap.dom), true);
5532     this.stripBody = Roo.get(this.stripWrap.dom.firstChild.firstChild, true);
5533     if(Roo.isIE){
5534         Roo.fly(this.stripWrap.dom.firstChild).setStyle("overflow-x", "hidden");
5535     }
5536     if(this.tabPosition != "bottom"){
5537         /** The body element that contains {@link Roo.TabPanelItem} bodies. +
5538          * @type Roo.Element
5539          */
5540         this.bodyEl = Roo.get(this.createBody(this.el.dom));
5541         this.el.addClass("x-tabs-top");
5542     }
5543     this.items = [];
5544
5545     this.bodyEl.setStyle("position", "relative");
5546
5547     this.active = null;
5548     this.activateDelegate = this.activate.createDelegate(this);
5549
5550     this.addEvents({
5551         /**
5552          * @event tabchange
5553          * Fires when the active tab changes
5554          * @param {Roo.TabPanel} this
5555          * @param {Roo.TabPanelItem} activePanel The new active tab
5556          */
5557         "tabchange": true,
5558         /**
5559          * @event beforetabchange
5560          * Fires before the active tab changes, set cancel to true on the "e" parameter to cancel the change
5561          * @param {Roo.TabPanel} this
5562          * @param {Object} e Set cancel to true on this object to cancel the tab change
5563          * @param {Roo.TabPanelItem} tab The tab being changed to
5564          */
5565         "beforetabchange" : true
5566     });
5567
5568     Roo.EventManager.onWindowResize(this.onResize, this);
5569     this.cpad = this.el.getPadding("lr");
5570     this.hiddenCount = 0;
5571
5572
5573     // toolbar on the tabbar support...
5574     if (this.toolbar) {
5575         var tcfg = this.toolbar;
5576         tcfg.container = this.stripEl.child('td.x-tab-strip-toolbar');  
5577         this.toolbar = new Roo.Toolbar(tcfg);
5578         if (Roo.isSafari) {
5579             var tbl = tcfg.container.child('table', true);
5580             tbl.setAttribute('width', '100%');
5581         }
5582         
5583     }
5584    
5585
5586
5587     Roo.TabPanel.superclass.constructor.call(this);
5588 };
5589
5590 Roo.extend(Roo.TabPanel, Roo.util.Observable, {
5591     /*
5592      *@cfg {String} tabPosition "top" or "bottom" (defaults to "top")
5593      */
5594     tabPosition : "top",
5595     /*
5596      *@cfg {Number} currentTabWidth The width of the current tab (defaults to 0)
5597      */
5598     currentTabWidth : 0,
5599     /*
5600      *@cfg {Number} minTabWidth The minimum width of a tab (defaults to 40) (ignored if {@link #resizeTabs} is not true)
5601      */
5602     minTabWidth : 40,
5603     /*
5604      *@cfg {Number} maxTabWidth The maximum width of a tab (defaults to 250) (ignored if {@link #resizeTabs} is not true)
5605      */
5606     maxTabWidth : 250,
5607     /*
5608      *@cfg {Number} preferredTabWidth The preferred (default) width of a tab (defaults to 175) (ignored if {@link #resizeTabs} is not true)
5609      */
5610     preferredTabWidth : 175,
5611     /*
5612      *@cfg {Boolean} resizeTabs True to enable dynamic tab resizing (defaults to false)
5613      */
5614     resizeTabs : false,
5615     /*
5616      *@cfg {Boolean} monitorResize Set this to true to turn on window resize monitoring (ignored if {@link #resizeTabs} is not true) (defaults to true)
5617      */
5618     monitorResize : true,
5619     /*
5620      *@cfg {Object} toolbar xtype description of toolbar to show at the right of the tab bar. 
5621      */
5622     toolbar : false,
5623
5624     /**
5625      * Creates a new {@link Roo.TabPanelItem} by looking for an existing element with the provided id -- if it's not found it creates one.
5626      * @param {String} id The id of the div to use <b>or create</b>
5627      * @param {String} text The text for the tab
5628      * @param {String} content (optional) Content to put in the TabPanelItem body
5629      * @param {Boolean} closable (optional) True to create a close icon on the tab
5630      * @return {Roo.TabPanelItem} The created TabPanelItem
5631      */
5632     addTab : function(id, text, content, closable){
5633         var item = new Roo.TabPanelItem(this, id, text, closable);
5634         this.addTabItem(item);
5635         if(content){
5636             item.setContent(content);
5637         }
5638         return item;
5639     },
5640
5641     /**
5642      * Returns the {@link Roo.TabPanelItem} with the specified id/index
5643      * @param {String/Number} id The id or index of the TabPanelItem to fetch.
5644      * @return {Roo.TabPanelItem}
5645      */
5646     getTab : function(id){
5647         return this.items[id];
5648     },
5649
5650     /**
5651      * Hides the {@link Roo.TabPanelItem} with the specified id/index
5652      * @param {String/Number} id The id or index of the TabPanelItem to hide.
5653      */
5654     hideTab : function(id){
5655         var t = this.items[id];
5656         if(!t.isHidden()){
5657            t.setHidden(true);
5658            this.hiddenCount++;
5659            this.autoSizeTabs();
5660         }
5661     },
5662
5663     /**
5664      * "Unhides" the {@link Roo.TabPanelItem} with the specified id/index.
5665      * @param {String/Number} id The id or index of the TabPanelItem to unhide.
5666      */
5667     unhideTab : function(id){
5668         var t = this.items[id];
5669         if(t.isHidden()){
5670            t.setHidden(false);
5671            this.hiddenCount--;
5672            this.autoSizeTabs();
5673         }
5674     },
5675
5676     /**
5677      * Adds an existing {@link Roo.TabPanelItem}.
5678      * @param {Roo.TabPanelItem} item The TabPanelItem to add
5679      */
5680     addTabItem : function(item){
5681         this.items[item.id] = item;
5682         this.items.push(item);
5683         if(this.resizeTabs){
5684            item.setWidth(this.currentTabWidth || this.preferredTabWidth);
5685            this.autoSizeTabs();
5686         }else{
5687             item.autoSize();
5688         }
5689     },
5690
5691     /**
5692      * Removes a {@link Roo.TabPanelItem}.
5693      * @param {String/Number} id The id or index of the TabPanelItem to remove.
5694      */
5695     removeTab : function(id){
5696         var items = this.items;
5697         var tab = items[id];
5698         if(!tab) { return; }
5699         var index = items.indexOf(tab);
5700         if(this.active == tab && items.length > 1){
5701             var newTab = this.getNextAvailable(index);
5702             if(newTab) {
5703                 newTab.activate();
5704             }
5705         }
5706         this.stripEl.dom.removeChild(tab.pnode.dom);
5707         if(tab.bodyEl.dom.parentNode == this.bodyEl.dom){ // if it was moved already prevent error
5708             this.bodyEl.dom.removeChild(tab.bodyEl.dom);
5709         }
5710         items.splice(index, 1);
5711         delete this.items[tab.id];
5712         tab.fireEvent("close", tab);
5713         tab.purgeListeners();
5714         this.autoSizeTabs();
5715     },
5716
5717     getNextAvailable : function(start){
5718         var items = this.items;
5719         var index = start;
5720         // look for a next tab that will slide over to
5721         // replace the one being removed
5722         while(index < items.length){
5723             var item = items[++index];
5724             if(item && !item.isHidden()){
5725                 return item;
5726             }
5727         }
5728         // if one isn't found select the previous tab (on the left)
5729         index = start;
5730         while(index >= 0){
5731             var item = items[--index];
5732             if(item && !item.isHidden()){
5733                 return item;
5734             }
5735         }
5736         return null;
5737     },
5738
5739     /**
5740      * Disables a {@link Roo.TabPanelItem}. It cannot be the active tab, if it is this call is ignored.
5741      * @param {String/Number} id The id or index of the TabPanelItem to disable.
5742      */
5743     disableTab : function(id){
5744         var tab = this.items[id];
5745         if(tab && this.active != tab){
5746             tab.disable();
5747         }
5748     },
5749
5750     /**
5751      * Enables a {@link Roo.TabPanelItem} that is disabled.
5752      * @param {String/Number} id The id or index of the TabPanelItem to enable.
5753      */
5754     enableTab : function(id){
5755         var tab = this.items[id];
5756         tab.enable();
5757     },
5758
5759     /**
5760      * Activates a {@link Roo.TabPanelItem}. The currently active one will be deactivated.
5761      * @param {String/Number} id The id or index of the TabPanelItem to activate.
5762      * @return {Roo.TabPanelItem} The TabPanelItem.
5763      */
5764     activate : function(id){
5765         var tab = this.items[id];
5766         if(!tab){
5767             return null;
5768         }
5769         if(tab == this.active || tab.disabled){
5770             return tab;
5771         }
5772         var e = {};
5773         this.fireEvent("beforetabchange", this, e, tab);
5774         if(e.cancel !== true && !tab.disabled){
5775             if(this.active){
5776                 this.active.hide();
5777             }
5778             this.active = this.items[id];
5779             this.active.show();
5780             this.fireEvent("tabchange", this, this.active);
5781         }
5782         return tab;
5783     },
5784
5785     /**
5786      * Gets the active {@link Roo.TabPanelItem}.
5787      * @return {Roo.TabPanelItem} The active TabPanelItem or null if none are active.
5788      */
5789     getActiveTab : function(){
5790         return this.active;
5791     },
5792
5793     /**
5794      * Updates the tab body element to fit the height of the container element
5795      * for overflow scrolling
5796      * @param {Number} targetHeight (optional) Override the starting height from the elements height
5797      */
5798     syncHeight : function(targetHeight){
5799         var height = (targetHeight || this.el.getHeight())-this.el.getBorderWidth("tb")-this.el.getPadding("tb");
5800         var bm = this.bodyEl.getMargins();
5801         var newHeight = height-(this.stripWrap.getHeight()||0)-(bm.top+bm.bottom);
5802         this.bodyEl.setHeight(newHeight);
5803         return newHeight;
5804     },
5805
5806     onResize : function(){
5807         if(this.monitorResize){
5808             this.autoSizeTabs();
5809         }
5810     },
5811
5812     /**
5813      * Disables tab resizing while tabs are being added (if {@link #resizeTabs} is false this does nothing)
5814      */
5815     beginUpdate : function(){
5816         this.updating = true;
5817     },
5818
5819     /**
5820      * Stops an update and resizes the tabs (if {@link #resizeTabs} is false this does nothing)
5821      */
5822     endUpdate : function(){
5823         this.updating = false;
5824         this.autoSizeTabs();
5825     },
5826
5827     /**
5828      * Manual call to resize the tabs (if {@link #resizeTabs} is false this does nothing)
5829      */
5830     autoSizeTabs : function(){
5831         var count = this.items.length;
5832         var vcount = count - this.hiddenCount;
5833         if(!this.resizeTabs || count < 1 || vcount < 1 || this.updating) {
5834             return;
5835         }
5836         var w = Math.max(this.el.getWidth() - this.cpad, 10);
5837         var availWidth = Math.floor(w / vcount);
5838         var b = this.stripBody;
5839         if(b.getWidth() > w){
5840             var tabs = this.items;
5841             this.setTabWidth(Math.max(availWidth, this.minTabWidth)-2);
5842             if(availWidth < this.minTabWidth){
5843                 /*if(!this.sleft){    // incomplete scrolling code
5844                     this.createScrollButtons();
5845                 }
5846                 this.showScroll();
5847                 this.stripClip.setWidth(w - (this.sleft.getWidth()+this.sright.getWidth()));*/
5848             }
5849         }else{
5850             if(this.currentTabWidth < this.preferredTabWidth){
5851                 this.setTabWidth(Math.min(availWidth, this.preferredTabWidth)-2);
5852             }
5853         }
5854     },
5855
5856     /**
5857      * Returns the number of tabs in this TabPanel.
5858      * @return {Number}
5859      */
5860      getCount : function(){
5861          return this.items.length;
5862      },
5863
5864     /**
5865      * Resizes all the tabs to the passed width
5866      * @param {Number} The new width
5867      */
5868     setTabWidth : function(width){
5869         this.currentTabWidth = width;
5870         for(var i = 0, len = this.items.length; i < len; i++) {
5871                 if(!this.items[i].isHidden()) {
5872                 this.items[i].setWidth(width);
5873             }
5874         }
5875     },
5876
5877     /**
5878      * Destroys this TabPanel
5879      * @param {Boolean} removeEl (optional) True to remove the element from the DOM as well (defaults to undefined)
5880      */
5881     destroy : function(removeEl){
5882         Roo.EventManager.removeResizeListener(this.onResize, this);
5883         for(var i = 0, len = this.items.length; i < len; i++){
5884             this.items[i].purgeListeners();
5885         }
5886         if(removeEl === true){
5887             this.el.update("");
5888             this.el.remove();
5889         }
5890     }
5891 });
5892
5893 /**
5894  * @class Roo.TabPanelItem
5895  * @extends Roo.util.Observable
5896  * Represents an individual item (tab plus body) in a TabPanel.
5897  * @param {Roo.TabPanel} tabPanel The {@link Roo.TabPanel} this TabPanelItem belongs to
5898  * @param {String} id The id of this TabPanelItem
5899  * @param {String} text The text for the tab of this TabPanelItem
5900  * @param {Boolean} closable True to allow this TabPanelItem to be closable (defaults to false)
5901  */
5902 Roo.TabPanelItem = function(tabPanel, id, text, closable){
5903     /**
5904      * The {@link Roo.TabPanel} this TabPanelItem belongs to
5905      * @type Roo.TabPanel
5906      */
5907     this.tabPanel = tabPanel;
5908     /**
5909      * The id for this TabPanelItem
5910      * @type String
5911      */
5912     this.id = id;
5913     /** @private */
5914     this.disabled = false;
5915     /** @private */
5916     this.text = text;
5917     /** @private */
5918     this.loaded = false;
5919     this.closable = closable;
5920
5921     /**
5922      * The body element for this TabPanelItem.
5923      * @type Roo.Element
5924      */
5925     this.bodyEl = Roo.get(tabPanel.createItemBody(tabPanel.bodyEl.dom, id));
5926     this.bodyEl.setVisibilityMode(Roo.Element.VISIBILITY);
5927     this.bodyEl.setStyle("display", "block");
5928     this.bodyEl.setStyle("zoom", "1");
5929     this.hideAction();
5930
5931     var els = tabPanel.createStripElements(tabPanel.stripEl.dom, text, closable);
5932     /** @private */
5933     this.el = Roo.get(els.el, true);
5934     this.inner = Roo.get(els.inner, true);
5935     this.textEl = Roo.get(this.el.dom.firstChild.firstChild.firstChild, true);
5936     this.pnode = Roo.get(els.el.parentNode, true);
5937     this.el.on("mousedown", this.onTabMouseDown, this);
5938     this.el.on("click", this.onTabClick, this);
5939     /** @private */
5940     if(closable){
5941         var c = Roo.get(els.close, true);
5942         c.dom.title = this.closeText;
5943         c.addClassOnOver("close-over");
5944         c.on("click", this.closeClick, this);
5945      }
5946
5947     this.addEvents({
5948          /**
5949          * @event activate
5950          * Fires when this tab becomes the active tab.
5951          * @param {Roo.TabPanel} tabPanel The parent TabPanel
5952          * @param {Roo.TabPanelItem} this
5953          */
5954         "activate": true,
5955         /**
5956          * @event beforeclose
5957          * Fires before this tab is closed. To cancel the close, set cancel to true on e (e.cancel = true).
5958          * @param {Roo.TabPanelItem} this
5959          * @param {Object} e Set cancel to true on this object to cancel the close.
5960          */
5961         "beforeclose": true,
5962         /**
5963          * @event close
5964          * Fires when this tab is closed.
5965          * @param {Roo.TabPanelItem} this
5966          */
5967          "close": true,
5968         /**
5969          * @event deactivate
5970          * Fires when this tab is no longer the active tab.
5971          * @param {Roo.TabPanel} tabPanel The parent TabPanel
5972          * @param {Roo.TabPanelItem} this
5973          */
5974          "deactivate" : true
5975     });
5976     this.hidden = false;
5977
5978     Roo.TabPanelItem.superclass.constructor.call(this);
5979 };
5980
5981 Roo.extend(Roo.TabPanelItem, Roo.util.Observable, {
5982     purgeListeners : function(){
5983        Roo.util.Observable.prototype.purgeListeners.call(this);
5984        this.el.removeAllListeners();
5985     },
5986     /**
5987      * Shows this TabPanelItem -- this <b>does not</b> deactivate the currently active TabPanelItem.
5988      */
5989     show : function(){
5990         this.pnode.addClass("on");
5991         this.showAction();
5992         if(Roo.isOpera){
5993             this.tabPanel.stripWrap.repaint();
5994         }
5995         this.fireEvent("activate", this.tabPanel, this);
5996     },
5997
5998     /**
5999      * Returns true if this tab is the active tab.
6000      * @return {Boolean}
6001      */
6002     isActive : function(){
6003         return this.tabPanel.getActiveTab() == this;
6004     },
6005
6006     /**
6007      * Hides this TabPanelItem -- if you don't activate another TabPanelItem this could look odd.
6008      */
6009     hide : function(){
6010         this.pnode.removeClass("on");
6011         this.hideAction();
6012         this.fireEvent("deactivate", this.tabPanel, this);
6013     },
6014
6015     hideAction : function(){
6016         this.bodyEl.hide();
6017         this.bodyEl.setStyle("position", "absolute");
6018         this.bodyEl.setLeft("-20000px");
6019         this.bodyEl.setTop("-20000px");
6020     },
6021
6022     showAction : function(){
6023         this.bodyEl.setStyle("position", "relative");
6024         this.bodyEl.setTop("");
6025         this.bodyEl.setLeft("");
6026         this.bodyEl.show();
6027     },
6028
6029     /**
6030      * Set the tooltip for the tab.
6031      * @param {String} tooltip The tab's tooltip
6032      */
6033     setTooltip : function(text){
6034         if(Roo.QuickTips && Roo.QuickTips.isEnabled()){
6035             this.textEl.dom.qtip = text;
6036             this.textEl.dom.removeAttribute('title');
6037         }else{
6038             this.textEl.dom.title = text;
6039         }
6040     },
6041
6042     onTabClick : function(e){
6043         e.preventDefault();
6044         this.tabPanel.activate(this.id);
6045     },
6046
6047     onTabMouseDown : function(e){
6048         e.preventDefault();
6049         this.tabPanel.activate(this.id);
6050     },
6051
6052     getWidth : function(){
6053         return this.inner.getWidth();
6054     },
6055
6056     setWidth : function(width){
6057         var iwidth = width - this.pnode.getPadding("lr");
6058         this.inner.setWidth(iwidth);
6059         this.textEl.setWidth(iwidth-this.inner.getPadding("lr"));
6060         this.pnode.setWidth(width);
6061     },
6062
6063     /**
6064      * Show or hide the tab
6065      * @param {Boolean} hidden True to hide or false to show.
6066      */
6067     setHidden : function(hidden){
6068         this.hidden = hidden;
6069         this.pnode.setStyle("display", hidden ? "none" : "");
6070     },
6071
6072     /**
6073      * Returns true if this tab is "hidden"
6074      * @return {Boolean}
6075      */
6076     isHidden : function(){
6077         return this.hidden;
6078     },
6079
6080     /**
6081      * Returns the text for this tab
6082      * @return {String}
6083      */
6084     getText : function(){
6085         return this.text;
6086     },
6087
6088     autoSize : function(){
6089         //this.el.beginMeasure();
6090         this.textEl.setWidth(1);
6091         /*
6092          *  #2804 [new] Tabs in Roojs
6093          *  increase the width by 2-4 pixels to prevent the ellipssis showing in chrome
6094          */
6095         this.setWidth(this.textEl.dom.scrollWidth+this.pnode.getPadding("lr")+this.inner.getPadding("lr") + 2);
6096         //this.el.endMeasure();
6097     },
6098
6099     /**
6100      * Sets the text for the tab (Note: this also sets the tooltip text)
6101      * @param {String} text The tab's text and tooltip
6102      */
6103     setText : function(text){
6104         this.text = text;
6105         this.textEl.update(text);
6106         this.setTooltip(text);
6107         if(!this.tabPanel.resizeTabs){
6108             this.autoSize();
6109         }
6110     },
6111     /**
6112      * Activates this TabPanelItem -- this <b>does</b> deactivate the currently active TabPanelItem.
6113      */
6114     activate : function(){
6115         this.tabPanel.activate(this.id);
6116     },
6117
6118     /**
6119      * Disables this TabPanelItem -- this does nothing if this is the active TabPanelItem.
6120      */
6121     disable : function(){
6122         if(this.tabPanel.active != this){
6123             this.disabled = true;
6124             this.pnode.addClass("disabled");
6125         }
6126     },
6127
6128     /**
6129      * Enables this TabPanelItem if it was previously disabled.
6130      */
6131     enable : function(){
6132         this.disabled = false;
6133         this.pnode.removeClass("disabled");
6134     },
6135
6136     /**
6137      * Sets the content for this TabPanelItem.
6138      * @param {String} content The content
6139      * @param {Boolean} loadScripts true to look for and load scripts
6140      */
6141     setContent : function(content, loadScripts){
6142         this.bodyEl.update(content, loadScripts);
6143     },
6144
6145     /**
6146      * Gets the {@link Roo.UpdateManager} for the body of this TabPanelItem. Enables you to perform Ajax updates.
6147      * @return {Roo.UpdateManager} The UpdateManager
6148      */
6149     getUpdateManager : function(){
6150         return this.bodyEl.getUpdateManager();
6151     },
6152
6153     /**
6154      * Set a URL to be used to load the content for this TabPanelItem.
6155      * @param {String/Function} url The URL to load the content from, or a function to call to get the URL
6156      * @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)
6157      * @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)
6158      * @return {Roo.UpdateManager} The UpdateManager
6159      */
6160     setUrl : function(url, params, loadOnce){
6161         if(this.refreshDelegate){
6162             this.un('activate', this.refreshDelegate);
6163         }
6164         this.refreshDelegate = this._handleRefresh.createDelegate(this, [url, params, loadOnce]);
6165         this.on("activate", this.refreshDelegate);
6166         return this.bodyEl.getUpdateManager();
6167     },
6168
6169     /** @private */
6170     _handleRefresh : function(url, params, loadOnce){
6171         if(!loadOnce || !this.loaded){
6172             var updater = this.bodyEl.getUpdateManager();
6173             updater.update(url, params, this._setLoaded.createDelegate(this));
6174         }
6175     },
6176
6177     /**
6178      *   Forces a content refresh from the URL specified in the {@link #setUrl} method.
6179      *   Will fail silently if the setUrl method has not been called.
6180      *   This does not activate the panel, just updates its content.
6181      */
6182     refresh : function(){
6183         if(this.refreshDelegate){
6184            this.loaded = false;
6185            this.refreshDelegate();
6186         }
6187     },
6188
6189     /** @private */
6190     _setLoaded : function(){
6191         this.loaded = true;
6192     },
6193
6194     /** @private */
6195     closeClick : function(e){
6196         var o = {};
6197         e.stopEvent();
6198         this.fireEvent("beforeclose", this, o);
6199         if(o.cancel !== true){
6200             this.tabPanel.removeTab(this.id);
6201         }
6202     },
6203     /**
6204      * The text displayed in the tooltip for the close icon.
6205      * @type String
6206      */
6207     closeText : "Close this tab"
6208 });
6209
6210 /** @private */
6211 Roo.TabPanel.prototype.createStrip = function(container){
6212     var strip = document.createElement("div");
6213     strip.className = "x-tabs-wrap";
6214     container.appendChild(strip);
6215     return strip;
6216 };
6217 /** @private */
6218 Roo.TabPanel.prototype.createStripList = function(strip){
6219     // div wrapper for retard IE
6220     // returns the "tr" element.
6221     strip.innerHTML = '<div class="x-tabs-strip-wrap">'+
6222         '<table class="x-tabs-strip" cellspacing="0" cellpadding="0" border="0"><tbody><tr>'+
6223         '<td class="x-tab-strip-toolbar"></td></tr></tbody></table></div>';
6224     return strip.firstChild.firstChild.firstChild.firstChild;
6225 };
6226 /** @private */
6227 Roo.TabPanel.prototype.createBody = function(container){
6228     var body = document.createElement("div");
6229     Roo.id(body, "tab-body");
6230     Roo.fly(body).addClass("x-tabs-body");
6231     container.appendChild(body);
6232     return body;
6233 };
6234 /** @private */
6235 Roo.TabPanel.prototype.createItemBody = function(bodyEl, id){
6236     var body = Roo.getDom(id);
6237     if(!body){
6238         body = document.createElement("div");
6239         body.id = id;
6240     }
6241     Roo.fly(body).addClass("x-tabs-item-body");
6242     bodyEl.insertBefore(body, bodyEl.firstChild);
6243     return body;
6244 };
6245 /** @private */
6246 Roo.TabPanel.prototype.createStripElements = function(stripEl, text, closable){
6247     var td = document.createElement("td");
6248     stripEl.insertBefore(td, stripEl.childNodes[stripEl.childNodes.length-1]);
6249     //stripEl.appendChild(td);
6250     if(closable){
6251         td.className = "x-tabs-closable";
6252         if(!this.closeTpl){
6253             this.closeTpl = new Roo.Template(
6254                '<a href="#" class="x-tabs-right"><span class="x-tabs-left"><em class="x-tabs-inner">' +
6255                '<span unselectable="on"' + (this.disableTooltips ? '' : ' title="{text}"') +' class="x-tabs-text">{text}</span>' +
6256                '<div unselectable="on" class="close-icon">&#160;</div></em></span></a>'
6257             );
6258         }
6259         var el = this.closeTpl.overwrite(td, {"text": text});
6260         var close = el.getElementsByTagName("div")[0];
6261         var inner = el.getElementsByTagName("em")[0];
6262         return {"el": el, "close": close, "inner": inner};
6263     } else {
6264         if(!this.tabTpl){
6265             this.tabTpl = new Roo.Template(
6266                '<a href="#" class="x-tabs-right"><span class="x-tabs-left"><em class="x-tabs-inner">' +
6267                '<span unselectable="on"' + (this.disableTooltips ? '' : ' title="{text}"') +' class="x-tabs-text">{text}</span></em></span></a>'
6268             );
6269         }
6270         var el = this.tabTpl.overwrite(td, {"text": text});
6271         var inner = el.getElementsByTagName("em")[0];
6272         return {"el": el, "inner": inner};
6273     }
6274 };/*
6275  * Based on:
6276  * Ext JS Library 1.1.1
6277  * Copyright(c) 2006-2007, Ext JS, LLC.
6278  *
6279  * Originally Released Under LGPL - original licence link has changed is not relivant.
6280  *
6281  * Fork - LGPL
6282  * <script type="text/javascript">
6283  */
6284
6285 /**
6286  * @class Roo.Button
6287  * @extends Roo.util.Observable
6288  * Simple Button class
6289  * @cfg {String} text The button text
6290  * @cfg {String} icon The path to an image to display in the button (the image will be set as the background-image
6291  * CSS property of the button by default, so if you want a mixed icon/text button, set cls:"x-btn-text-icon")
6292  * @cfg {Function} handler A function called when the button is clicked (can be used instead of click event)
6293  * @cfg {Object} scope The scope of the handler
6294  * @cfg {Number} minWidth The minimum width for this button (used to give a set of buttons a common width)
6295  * @cfg {String/Object} tooltip The tooltip for the button - can be a string or QuickTips config object
6296  * @cfg {Boolean} hidden True to start hidden (defaults to false)
6297  * @cfg {Boolean} disabled True to start disabled (defaults to false)
6298  * @cfg {Boolean} pressed True to start pressed (only if enableToggle = true)
6299  * @cfg {String} toggleGroup The group this toggle button is a member of (only 1 per group can be pressed, only
6300    applies if enableToggle = true)
6301  * @cfg {String/HTMLElement/Element} renderTo The element to append the button to
6302  * @cfg {Boolean/Object} repeat True to repeat fire the click event while the mouse is down. This can also be
6303   an {@link Roo.util.ClickRepeater} config object (defaults to false).
6304  * @constructor
6305  * Create a new button
6306  * @param {Object} config The config object
6307  */
6308 Roo.Button = function(renderTo, config)
6309 {
6310     if (!config) {
6311         config = renderTo;
6312         renderTo = config.renderTo || false;
6313     }
6314     
6315     Roo.apply(this, config);
6316     this.addEvents({
6317         /**
6318              * @event click
6319              * Fires when this button is clicked
6320              * @param {Button} this
6321              * @param {EventObject} e The click event
6322              */
6323             "click" : true,
6324         /**
6325              * @event toggle
6326              * Fires when the "pressed" state of this button changes (only if enableToggle = true)
6327              * @param {Button} this
6328              * @param {Boolean} pressed
6329              */
6330             "toggle" : true,
6331         /**
6332              * @event mouseover
6333              * Fires when the mouse hovers over the button
6334              * @param {Button} this
6335              * @param {Event} e The event object
6336              */
6337         'mouseover' : true,
6338         /**
6339              * @event mouseout
6340              * Fires when the mouse exits the button
6341              * @param {Button} this
6342              * @param {Event} e The event object
6343              */
6344         'mouseout': true,
6345          /**
6346              * @event render
6347              * Fires when the button is rendered
6348              * @param {Button} this
6349              */
6350         'render': true
6351     });
6352     if(this.menu){
6353         this.menu = Roo.menu.MenuMgr.get(this.menu);
6354     }
6355     // register listeners first!!  - so render can be captured..
6356     Roo.util.Observable.call(this);
6357     if(renderTo){
6358         this.render(renderTo);
6359     }
6360     
6361   
6362 };
6363
6364 Roo.extend(Roo.Button, Roo.util.Observable, {
6365     /**
6366      * 
6367      */
6368     
6369     /**
6370      * Read-only. True if this button is hidden
6371      * @type Boolean
6372      */
6373     hidden : false,
6374     /**
6375      * Read-only. True if this button is disabled
6376      * @type Boolean
6377      */
6378     disabled : false,
6379     /**
6380      * Read-only. True if this button is pressed (only if enableToggle = true)
6381      * @type Boolean
6382      */
6383     pressed : false,
6384
6385     /**
6386      * @cfg {Number} tabIndex 
6387      * The DOM tabIndex for this button (defaults to undefined)
6388      */
6389     tabIndex : undefined,
6390
6391     /**
6392      * @cfg {Boolean} enableToggle
6393      * True to enable pressed/not pressed toggling (defaults to false)
6394      */
6395     enableToggle: false,
6396     /**
6397      * @cfg {Roo.menu.Menu} menu
6398      * Standard menu attribute consisting of a reference to a menu object, a menu id or a menu config blob (defaults to undefined).
6399      */
6400     menu : undefined,
6401     /**
6402      * @cfg {String} menuAlign
6403      * The position to align the menu to (see {@link Roo.Element#alignTo} for more details, defaults to 'tl-bl?').
6404      */
6405     menuAlign : "tl-bl?",
6406
6407     /**
6408      * @cfg {String} iconCls
6409      * A css class which sets a background image to be used as the icon for this button (defaults to undefined).
6410      */
6411     iconCls : undefined,
6412     /**
6413      * @cfg {String} type
6414      * The button's type, corresponding to the DOM input element type attribute.  Either "submit," "reset" or "button" (default).
6415      */
6416     type : 'button',
6417
6418     // private
6419     menuClassTarget: 'tr',
6420
6421     /**
6422      * @cfg {String} clickEvent
6423      * The type of event to map to the button's event handler (defaults to 'click')
6424      */
6425     clickEvent : 'click',
6426
6427     /**
6428      * @cfg {Boolean} handleMouseEvents
6429      * False to disable visual cues on mouseover, mouseout and mousedown (defaults to true)
6430      */
6431     handleMouseEvents : true,
6432
6433     /**
6434      * @cfg {String} tooltipType
6435      * The type of tooltip to use. Either "qtip" (default) for QuickTips or "title" for title attribute.
6436      */
6437     tooltipType : 'qtip',
6438
6439     /**
6440      * @cfg {String} cls
6441      * A CSS class to apply to the button's main element.
6442      */
6443     
6444     /**
6445      * @cfg {Roo.Template} template (Optional)
6446      * An {@link Roo.Template} with which to create the Button's main element. This Template must
6447      * contain numeric substitution parameter 0 if it is to display the tRoo property. Changing the template could
6448      * require code modifications if required elements (e.g. a button) aren't present.
6449      */
6450
6451     // private
6452     render : function(renderTo){
6453         var btn;
6454         if(this.hideParent){
6455             this.parentEl = Roo.get(renderTo);
6456         }
6457         if(!this.dhconfig){
6458             if(!this.template){
6459                 if(!Roo.Button.buttonTemplate){
6460                     // hideous table template
6461                     Roo.Button.buttonTemplate = new Roo.Template(
6462                         '<table border="0" cellpadding="0" cellspacing="0" class="x-btn-wrap"><tbody><tr>',
6463                         '<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>',
6464                         "</tr></tbody></table>");
6465                 }
6466                 this.template = Roo.Button.buttonTemplate;
6467             }
6468             btn = this.template.append(renderTo, [this.text || '&#160;', this.type], true);
6469             var btnEl = btn.child("button:first");
6470             btnEl.on('focus', this.onFocus, this);
6471             btnEl.on('blur', this.onBlur, this);
6472             if(this.cls){
6473                 btn.addClass(this.cls);
6474             }
6475             if(this.icon){
6476                 btnEl.setStyle('background-image', 'url(' +this.icon +')');
6477             }
6478             if(this.iconCls){
6479                 btnEl.addClass(this.iconCls);
6480                 if(!this.cls){
6481                     btn.addClass(this.text ? 'x-btn-text-icon' : 'x-btn-icon');
6482                 }
6483             }
6484             if(this.tabIndex !== undefined){
6485                 btnEl.dom.tabIndex = this.tabIndex;
6486             }
6487             if(this.tooltip){
6488                 if(typeof this.tooltip == 'object'){
6489                     Roo.QuickTips.tips(Roo.apply({
6490                           target: btnEl.id
6491                     }, this.tooltip));
6492                 } else {
6493                     btnEl.dom[this.tooltipType] = this.tooltip;
6494                 }
6495             }
6496         }else{
6497             btn = Roo.DomHelper.append(Roo.get(renderTo).dom, this.dhconfig, true);
6498         }
6499         this.el = btn;
6500         if(this.id){
6501             this.el.dom.id = this.el.id = this.id;
6502         }
6503         if(this.menu){
6504             this.el.child(this.menuClassTarget).addClass("x-btn-with-menu");
6505             this.menu.on("show", this.onMenuShow, this);
6506             this.menu.on("hide", this.onMenuHide, this);
6507         }
6508         btn.addClass("x-btn");
6509         if(Roo.isIE && !Roo.isIE7){
6510             this.autoWidth.defer(1, this);
6511         }else{
6512             this.autoWidth();
6513         }
6514         if(this.handleMouseEvents){
6515             btn.on("mouseover", this.onMouseOver, this);
6516             btn.on("mouseout", this.onMouseOut, this);
6517             btn.on("mousedown", this.onMouseDown, this);
6518         }
6519         btn.on(this.clickEvent, this.onClick, this);
6520         //btn.on("mouseup", this.onMouseUp, this);
6521         if(this.hidden){
6522             this.hide();
6523         }
6524         if(this.disabled){
6525             this.disable();
6526         }
6527         Roo.ButtonToggleMgr.register(this);
6528         if(this.pressed){
6529             this.el.addClass("x-btn-pressed");
6530         }
6531         if(this.repeat){
6532             var repeater = new Roo.util.ClickRepeater(btn,
6533                 typeof this.repeat == "object" ? this.repeat : {}
6534             );
6535             repeater.on("click", this.onClick,  this);
6536         }
6537         
6538         this.fireEvent('render', this);
6539         
6540     },
6541     /**
6542      * Returns the button's underlying element
6543      * @return {Roo.Element} The element
6544      */
6545     getEl : function(){
6546         return this.el;  
6547     },
6548     
6549     /**
6550      * Destroys this Button and removes any listeners.
6551      */
6552     destroy : function(){
6553         Roo.ButtonToggleMgr.unregister(this);
6554         this.el.removeAllListeners();
6555         this.purgeListeners();
6556         this.el.remove();
6557     },
6558
6559     // private
6560     autoWidth : function(){
6561         if(this.el){
6562             this.el.setWidth("auto");
6563             if(Roo.isIE7 && Roo.isStrict){
6564                 var ib = this.el.child('button');
6565                 if(ib && ib.getWidth() > 20){
6566                     ib.clip();
6567                     ib.setWidth(Roo.util.TextMetrics.measure(ib, this.text).width+ib.getFrameWidth('lr'));
6568                 }
6569             }
6570             if(this.minWidth){
6571                 if(this.hidden){
6572                     this.el.beginMeasure();
6573                 }
6574                 if(this.el.getWidth() < this.minWidth){
6575                     this.el.setWidth(this.minWidth);
6576                 }
6577                 if(this.hidden){
6578                     this.el.endMeasure();
6579                 }
6580             }
6581         }
6582     },
6583
6584     /**
6585      * Assigns this button's click handler
6586      * @param {Function} handler The function to call when the button is clicked
6587      * @param {Object} scope (optional) Scope for the function passed in
6588      */
6589     setHandler : function(handler, scope){
6590         this.handler = handler;
6591         this.scope = scope;  
6592     },
6593     
6594     /**
6595      * Sets this button's text
6596      * @param {String} text The button text
6597      */
6598     setText : function(text){
6599         this.text = text;
6600         if(this.el){
6601             this.el.child("td.x-btn-center button.x-btn-text").update(text);
6602         }
6603         this.autoWidth();
6604     },
6605     
6606     /**
6607      * Gets the text for this button
6608      * @return {String} The button text
6609      */
6610     getText : function(){
6611         return this.text;  
6612     },
6613     
6614     /**
6615      * Show this button
6616      */
6617     show: function(){
6618         this.hidden = false;
6619         if(this.el){
6620             this[this.hideParent? 'parentEl' : 'el'].setStyle("display", "");
6621         }
6622     },
6623     
6624     /**
6625      * Hide this button
6626      */
6627     hide: function(){
6628         this.hidden = true;
6629         if(this.el){
6630             this[this.hideParent? 'parentEl' : 'el'].setStyle("display", "none");
6631         }
6632     },
6633     
6634     /**
6635      * Convenience function for boolean show/hide
6636      * @param {Boolean} visible True to show, false to hide
6637      */
6638     setVisible: function(visible){
6639         if(visible) {
6640             this.show();
6641         }else{
6642             this.hide();
6643         }
6644     },
6645     /**
6646          * Similar to toggle, but does not trigger event.
6647          * @param {Boolean} state [required] Force a particular state
6648          */
6649         setPressed : function(state)
6650         {
6651             if(state != this.pressed){
6652             if(state){
6653                 this.el.addClass("x-btn-pressed");
6654                 this.pressed = true;
6655             }else{
6656                 this.el.removeClass("x-btn-pressed");
6657                 this.pressed = false;
6658             }
6659         }
6660         },
6661         
6662     /**
6663      * If a state it passed, it becomes the pressed state otherwise the current state is toggled.
6664      * @param {Boolean} state (optional) Force a particular state
6665      */
6666     toggle : function(state){
6667         state = state === undefined ? !this.pressed : state;
6668         if(state != this.pressed){
6669             if(state){
6670                 this.el.addClass("x-btn-pressed");
6671                 this.pressed = true;
6672                 this.fireEvent("toggle", this, true);
6673             }else{
6674                 this.el.removeClass("x-btn-pressed");
6675                 this.pressed = false;
6676                 this.fireEvent("toggle", this, false);
6677             }
6678             if(this.toggleHandler){
6679                 this.toggleHandler.call(this.scope || this, this, state);
6680             }
6681         }
6682     },
6683     
6684         
6685         
6686     /**
6687      * Focus the button
6688      */
6689     focus : function(){
6690         this.el.child('button:first').focus();
6691     },
6692     
6693     /**
6694      * Disable this button
6695      */
6696     disable : function(){
6697         if(this.el){
6698             this.el.addClass("x-btn-disabled");
6699         }
6700         this.disabled = true;
6701     },
6702     
6703     /**
6704      * Enable this button
6705      */
6706     enable : function(){
6707         if(this.el){
6708             this.el.removeClass("x-btn-disabled");
6709         }
6710         this.disabled = false;
6711     },
6712
6713     /**
6714      * Convenience function for boolean enable/disable
6715      * @param {Boolean} enabled True to enable, false to disable
6716      */
6717     setDisabled : function(v){
6718         this[v !== true ? "enable" : "disable"]();
6719     },
6720
6721     // private
6722     onClick : function(e)
6723     {
6724         if(e){
6725             e.preventDefault();
6726         }
6727         if(e.button != 0){
6728             return;
6729         }
6730         if(!this.disabled){
6731             if(this.enableToggle){
6732                 this.toggle();
6733             }
6734             if(this.menu && !this.menu.isVisible()){
6735                 this.menu.show(this.el, this.menuAlign);
6736             }
6737             this.fireEvent("click", this, e);
6738             if(this.handler){
6739                 this.el.removeClass("x-btn-over");
6740                 this.handler.call(this.scope || this, this, e);
6741             }
6742         }
6743     },
6744     // private
6745     onMouseOver : function(e){
6746         if(!this.disabled){
6747             this.el.addClass("x-btn-over");
6748             this.fireEvent('mouseover', this, e);
6749         }
6750     },
6751     // private
6752     onMouseOut : function(e){
6753         if(!e.within(this.el,  true)){
6754             this.el.removeClass("x-btn-over");
6755             this.fireEvent('mouseout', this, e);
6756         }
6757     },
6758     // private
6759     onFocus : function(e){
6760         if(!this.disabled){
6761             this.el.addClass("x-btn-focus");
6762         }
6763     },
6764     // private
6765     onBlur : function(e){
6766         this.el.removeClass("x-btn-focus");
6767     },
6768     // private
6769     onMouseDown : function(e){
6770         if(!this.disabled && e.button == 0){
6771             this.el.addClass("x-btn-click");
6772             Roo.get(document).on('mouseup', this.onMouseUp, this);
6773         }
6774     },
6775     // private
6776     onMouseUp : function(e){
6777         if(e.button == 0){
6778             this.el.removeClass("x-btn-click");
6779             Roo.get(document).un('mouseup', this.onMouseUp, this);
6780         }
6781     },
6782     // private
6783     onMenuShow : function(e){
6784         this.el.addClass("x-btn-menu-active");
6785     },
6786     // private
6787     onMenuHide : function(e){
6788         this.el.removeClass("x-btn-menu-active");
6789     }   
6790 });
6791
6792 // Private utility class used by Button
6793 Roo.ButtonToggleMgr = function(){
6794    var groups = {};
6795    
6796    function toggleGroup(btn, state){
6797        if(state){
6798            var g = groups[btn.toggleGroup];
6799            for(var i = 0, l = g.length; i < l; i++){
6800                if(g[i] != btn){
6801                    g[i].toggle(false);
6802                }
6803            }
6804        }
6805    }
6806    
6807    return {
6808        register : function(btn){
6809            if(!btn.toggleGroup){
6810                return;
6811            }
6812            var g = groups[btn.toggleGroup];
6813            if(!g){
6814                g = groups[btn.toggleGroup] = [];
6815            }
6816            g.push(btn);
6817            btn.on("toggle", toggleGroup);
6818        },
6819        
6820        unregister : function(btn){
6821            if(!btn.toggleGroup){
6822                return;
6823            }
6824            var g = groups[btn.toggleGroup];
6825            if(g){
6826                g.remove(btn);
6827                btn.un("toggle", toggleGroup);
6828            }
6829        }
6830    };
6831 }();/*
6832  * Based on:
6833  * Ext JS Library 1.1.1
6834  * Copyright(c) 2006-2007, Ext JS, LLC.
6835  *
6836  * Originally Released Under LGPL - original licence link has changed is not relivant.
6837  *
6838  * Fork - LGPL
6839  * <script type="text/javascript">
6840  */
6841  
6842 /**
6843  * @class Roo.SplitButton
6844  * @extends Roo.Button
6845  * A split button that provides a built-in dropdown arrow that can fire an event separately from the default
6846  * click event of the button.  Typically this would be used to display a dropdown menu that provides additional
6847  * options to the primary button action, but any custom handler can provide the arrowclick implementation.
6848  * @cfg {Function} arrowHandler A function called when the arrow button is clicked (can be used instead of click event)
6849  * @cfg {String} arrowTooltip The title attribute of the arrow
6850  * @constructor
6851  * Create a new menu button
6852  * @param {String/HTMLElement/Element} renderTo The element to append the button to
6853  * @param {Object} config The config object
6854  */
6855 Roo.SplitButton = function(renderTo, config){
6856     Roo.SplitButton.superclass.constructor.call(this, renderTo, config);
6857     /**
6858      * @event arrowclick
6859      * Fires when this button's arrow is clicked
6860      * @param {SplitButton} this
6861      * @param {EventObject} e The click event
6862      */
6863     this.addEvents({"arrowclick":true});
6864 };
6865
6866 Roo.extend(Roo.SplitButton, Roo.Button, {
6867     render : function(renderTo){
6868         // this is one sweet looking template!
6869         var tpl = new Roo.Template(
6870             '<table cellspacing="0" class="x-btn-menu-wrap x-btn"><tr><td>',
6871             '<table cellspacing="0" class="x-btn-wrap x-btn-menu-text-wrap"><tbody>',
6872             '<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>',
6873             "</tbody></table></td><td>",
6874             '<table cellspacing="0" class="x-btn-wrap x-btn-menu-arrow-wrap"><tbody>',
6875             '<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>',
6876             "</tbody></table></td></tr></table>"
6877         );
6878         var btn = tpl.append(renderTo, [this.text, this.type], true);
6879         var btnEl = btn.child("button");
6880         if(this.cls){
6881             btn.addClass(this.cls);
6882         }
6883         if(this.icon){
6884             btnEl.setStyle('background-image', 'url(' +this.icon +')');
6885         }
6886         if(this.iconCls){
6887             btnEl.addClass(this.iconCls);
6888             if(!this.cls){
6889                 btn.addClass(this.text ? 'x-btn-text-icon' : 'x-btn-icon');
6890             }
6891         }
6892         this.el = btn;
6893         if(this.handleMouseEvents){
6894             btn.on("mouseover", this.onMouseOver, this);
6895             btn.on("mouseout", this.onMouseOut, this);
6896             btn.on("mousedown", this.onMouseDown, this);
6897             btn.on("mouseup", this.onMouseUp, this);
6898         }
6899         btn.on(this.clickEvent, this.onClick, this);
6900         if(this.tooltip){
6901             if(typeof this.tooltip == 'object'){
6902                 Roo.QuickTips.tips(Roo.apply({
6903                       target: btnEl.id
6904                 }, this.tooltip));
6905             } else {
6906                 btnEl.dom[this.tooltipType] = this.tooltip;
6907             }
6908         }
6909         if(this.arrowTooltip){
6910             btn.child("button:nth(2)").dom[this.tooltipType] = this.arrowTooltip;
6911         }
6912         if(this.hidden){
6913             this.hide();
6914         }
6915         if(this.disabled){
6916             this.disable();
6917         }
6918         if(this.pressed){
6919             this.el.addClass("x-btn-pressed");
6920         }
6921         if(Roo.isIE && !Roo.isIE7){
6922             this.autoWidth.defer(1, this);
6923         }else{
6924             this.autoWidth();
6925         }
6926         if(this.menu){
6927             this.menu.on("show", this.onMenuShow, this);
6928             this.menu.on("hide", this.onMenuHide, this);
6929         }
6930         this.fireEvent('render', this);
6931     },
6932
6933     // private
6934     autoWidth : function(){
6935         if(this.el){
6936             var tbl = this.el.child("table:first");
6937             var tbl2 = this.el.child("table:last");
6938             this.el.setWidth("auto");
6939             tbl.setWidth("auto");
6940             if(Roo.isIE7 && Roo.isStrict){
6941                 var ib = this.el.child('button:first');
6942                 if(ib && ib.getWidth() > 20){
6943                     ib.clip();
6944                     ib.setWidth(Roo.util.TextMetrics.measure(ib, this.text).width+ib.getFrameWidth('lr'));
6945                 }
6946             }
6947             if(this.minWidth){
6948                 if(this.hidden){
6949                     this.el.beginMeasure();
6950                 }
6951                 if((tbl.getWidth()+tbl2.getWidth()) < this.minWidth){
6952                     tbl.setWidth(this.minWidth-tbl2.getWidth());
6953                 }
6954                 if(this.hidden){
6955                     this.el.endMeasure();
6956                 }
6957             }
6958             this.el.setWidth(tbl.getWidth()+tbl2.getWidth());
6959         } 
6960     },
6961     /**
6962      * Sets this button's click handler
6963      * @param {Function} handler The function to call when the button is clicked
6964      * @param {Object} scope (optional) Scope for the function passed above
6965      */
6966     setHandler : function(handler, scope){
6967         this.handler = handler;
6968         this.scope = scope;  
6969     },
6970     
6971     /**
6972      * Sets this button's arrow click handler
6973      * @param {Function} handler The function to call when the arrow is clicked
6974      * @param {Object} scope (optional) Scope for the function passed above
6975      */
6976     setArrowHandler : function(handler, scope){
6977         this.arrowHandler = handler;
6978         this.scope = scope;  
6979     },
6980     
6981     /**
6982      * Focus the button
6983      */
6984     focus : function(){
6985         if(this.el){
6986             this.el.child("button:first").focus();
6987         }
6988     },
6989
6990     // private
6991     onClick : function(e){
6992         e.preventDefault();
6993         if(!this.disabled){
6994             if(e.getTarget(".x-btn-menu-arrow-wrap")){
6995                 if(this.menu && !this.menu.isVisible()){
6996                     this.menu.show(this.el, this.menuAlign);
6997                 }
6998                 this.fireEvent("arrowclick", this, e);
6999                 if(this.arrowHandler){
7000                     this.arrowHandler.call(this.scope || this, this, e);
7001                 }
7002             }else{
7003                 this.fireEvent("click", this, e);
7004                 if(this.handler){
7005                     this.handler.call(this.scope || this, this, e);
7006                 }
7007             }
7008         }
7009     },
7010     // private
7011     onMouseDown : function(e){
7012         if(!this.disabled){
7013             Roo.fly(e.getTarget("table")).addClass("x-btn-click");
7014         }
7015     },
7016     // private
7017     onMouseUp : function(e){
7018         Roo.fly(e.getTarget("table")).removeClass("x-btn-click");
7019     }   
7020 });
7021
7022
7023 // backwards compat
7024 Roo.MenuButton = Roo.SplitButton;/*
7025  * Based on:
7026  * Ext JS Library 1.1.1
7027  * Copyright(c) 2006-2007, Ext JS, LLC.
7028  *
7029  * Originally Released Under LGPL - original licence link has changed is not relivant.
7030  *
7031  * Fork - LGPL
7032  * <script type="text/javascript">
7033  */
7034
7035 /**
7036  * @class Roo.Toolbar
7037  * @children   Roo.Toolbar.Item Roo.Toolbar.Button Roo.Toolbar.SplitButton Roo.form.Field 
7038  * Basic Toolbar class.
7039  * @constructor
7040  * Creates a new Toolbar
7041  * @param {Object} container The config object
7042  */ 
7043 Roo.Toolbar = function(container, buttons, config)
7044 {
7045     /// old consturctor format still supported..
7046     if(container instanceof Array){ // omit the container for later rendering
7047         buttons = container;
7048         config = buttons;
7049         container = null;
7050     }
7051     if (typeof(container) == 'object' && container.xtype) {
7052         config = container;
7053         container = config.container;
7054         buttons = config.buttons || []; // not really - use items!!
7055     }
7056     var xitems = [];
7057     if (config && config.items) {
7058         xitems = config.items;
7059         delete config.items;
7060     }
7061     Roo.apply(this, config);
7062     this.buttons = buttons;
7063     
7064     if(container){
7065         this.render(container);
7066     }
7067     this.xitems = xitems;
7068     Roo.each(xitems, function(b) {
7069         this.add(b);
7070     }, this);
7071     
7072 };
7073
7074 Roo.Toolbar.prototype = {
7075     /**
7076      * @cfg {Array} items
7077      * array of button configs or elements to add (will be converted to a MixedCollection)
7078      */
7079     items: false,
7080     /**
7081      * @cfg {String/HTMLElement/Element} container
7082      * The id or element that will contain the toolbar
7083      */
7084     // private
7085     render : function(ct){
7086         this.el = Roo.get(ct);
7087         if(this.cls){
7088             this.el.addClass(this.cls);
7089         }
7090         // using a table allows for vertical alignment
7091         // 100% width is needed by Safari...
7092         this.el.update('<div class="x-toolbar x-small-editor"><table cellspacing="0"><tr></tr></table></div>');
7093         this.tr = this.el.child("tr", true);
7094         var autoId = 0;
7095         this.items = new Roo.util.MixedCollection(false, function(o){
7096             return o.id || ("item" + (++autoId));
7097         });
7098         if(this.buttons){
7099             this.add.apply(this, this.buttons);
7100             delete this.buttons;
7101         }
7102     },
7103
7104     /**
7105      * Adds element(s) to the toolbar -- this function takes a variable number of 
7106      * arguments of mixed type and adds them to the toolbar.
7107      * @param {Mixed} arg1 The following types of arguments are all valid:<br />
7108      * <ul>
7109      * <li>{@link Roo.Toolbar.Button} config: A valid button config object (equivalent to {@link #addButton})</li>
7110      * <li>HtmlElement: Any standard HTML element (equivalent to {@link #addElement})</li>
7111      * <li>Field: Any form field (equivalent to {@link #addField})</li>
7112      * <li>Item: Any subclass of {@link Roo.Toolbar.Item} (equivalent to {@link #addItem})</li>
7113      * <li>String: Any generic string (gets wrapped in a {@link Roo.Toolbar.TextItem}, equivalent to {@link #addText}).
7114      * Note that there are a few special strings that are treated differently as explained nRoo.</li>
7115      * <li>'separator' or '-': Creates a separator element (equivalent to {@link #addSeparator})</li>
7116      * <li>' ': Creates a spacer element (equivalent to {@link #addSpacer})</li>
7117      * <li>'->': Creates a fill element (equivalent to {@link #addFill})</li>
7118      * </ul>
7119      * @param {Mixed} arg2
7120      * @param {Mixed} etc.
7121      */
7122     add : function(){
7123         var a = arguments, l = a.length;
7124         for(var i = 0; i < l; i++){
7125             this._add(a[i]);
7126         }
7127     },
7128     // private..
7129     _add : function(el) {
7130         
7131         if (el.xtype) {
7132             el = Roo.factory(el, typeof(Roo.Toolbar[el.xtype]) == 'undefined' ? Roo.form : Roo.Toolbar);
7133         }
7134         
7135         if (el.applyTo){ // some kind of form field
7136             return this.addField(el);
7137         } 
7138         if (el.render){ // some kind of Toolbar.Item
7139             return this.addItem(el);
7140         }
7141         if (typeof el == "string"){ // string
7142             if(el == "separator" || el == "-"){
7143                 return this.addSeparator();
7144             }
7145             if (el == " "){
7146                 return this.addSpacer();
7147             }
7148             if(el == "->"){
7149                 return this.addFill();
7150             }
7151             return this.addText(el);
7152             
7153         }
7154         if(el.tagName){ // element
7155             return this.addElement(el);
7156         }
7157         if(typeof el == "object"){ // must be button config?
7158             return this.addButton(el);
7159         }
7160         // and now what?!?!
7161         return false;
7162         
7163     },
7164     
7165     /**
7166      * Add an Xtype element
7167      * @param {Object} xtype Xtype Object
7168      * @return {Object} created Object
7169      */
7170     addxtype : function(e){
7171         return this.add(e);  
7172     },
7173     
7174     /**
7175      * Returns the Element for this toolbar.
7176      * @return {Roo.Element}
7177      */
7178     getEl : function(){
7179         return this.el;  
7180     },
7181     
7182     /**
7183      * Adds a separator
7184      * @return {Roo.Toolbar.Item} The separator item
7185      */
7186     addSeparator : function(){
7187         return this.addItem(new Roo.Toolbar.Separator());
7188     },
7189
7190     /**
7191      * Adds a spacer element
7192      * @return {Roo.Toolbar.Spacer} The spacer item
7193      */
7194     addSpacer : function(){
7195         return this.addItem(new Roo.Toolbar.Spacer());
7196     },
7197
7198     /**
7199      * Adds a fill element that forces subsequent additions to the right side of the toolbar
7200      * @return {Roo.Toolbar.Fill} The fill item
7201      */
7202     addFill : function(){
7203         return this.addItem(new Roo.Toolbar.Fill());
7204     },
7205
7206     /**
7207      * Adds any standard HTML element to the toolbar
7208      * @param {String/HTMLElement/Element} el The element or id of the element to add
7209      * @return {Roo.Toolbar.Item} The element's item
7210      */
7211     addElement : function(el){
7212         return this.addItem(new Roo.Toolbar.Item(el));
7213     },
7214     /**
7215      * Collection of items on the toolbar.. (only Toolbar Items, so use fields to retrieve fields)
7216      * @type Roo.util.MixedCollection  
7217      */
7218     items : false,
7219      
7220     /**
7221      * Adds any Toolbar.Item or subclass
7222      * @param {Roo.Toolbar.Item} item
7223      * @return {Roo.Toolbar.Item} The item
7224      */
7225     addItem : function(item){
7226         var td = this.nextBlock();
7227         item.render(td);
7228         this.items.add(item);
7229         return item;
7230     },
7231     
7232     /**
7233      * Adds a button (or buttons). See {@link Roo.Toolbar.Button} for more info on the config.
7234      * @param {Object/Array} config A button config or array of configs
7235      * @return {Roo.Toolbar.Button/Array}
7236      */
7237     addButton : function(config){
7238         if(config instanceof Array){
7239             var buttons = [];
7240             for(var i = 0, len = config.length; i < len; i++) {
7241                 buttons.push(this.addButton(config[i]));
7242             }
7243             return buttons;
7244         }
7245         var b = config;
7246         if(!(config instanceof Roo.Toolbar.Button)){
7247             b = config.split ?
7248                 new Roo.Toolbar.SplitButton(config) :
7249                 new Roo.Toolbar.Button(config);
7250         }
7251         var td = this.nextBlock();
7252         b.render(td);
7253         this.items.add(b);
7254         return b;
7255     },
7256     
7257     /**
7258      * Adds text to the toolbar
7259      * @param {String} text The text to add
7260      * @return {Roo.Toolbar.Item} The element's item
7261      */
7262     addText : function(text){
7263         return this.addItem(new Roo.Toolbar.TextItem(text));
7264     },
7265     
7266     /**
7267      * Inserts any {@link Roo.Toolbar.Item}/{@link Roo.Toolbar.Button} at the specified index.
7268      * @param {Number} index The index where the item is to be inserted
7269      * @param {Object/Roo.Toolbar.Item/Roo.Toolbar.Button (may be Array)} item The button, or button config object to be inserted.
7270      * @return {Roo.Toolbar.Button/Item}
7271      */
7272     insertButton : function(index, item){
7273         if(item instanceof Array){
7274             var buttons = [];
7275             for(var i = 0, len = item.length; i < len; i++) {
7276                buttons.push(this.insertButton(index + i, item[i]));
7277             }
7278             return buttons;
7279         }
7280         if (!(item instanceof Roo.Toolbar.Button)){
7281            item = new Roo.Toolbar.Button(item);
7282         }
7283         var td = document.createElement("td");
7284         this.tr.insertBefore(td, this.tr.childNodes[index]);
7285         item.render(td);
7286         this.items.insert(index, item);
7287         return item;
7288     },
7289     
7290     /**
7291      * Adds a new element to the toolbar from the passed {@link Roo.DomHelper} config.
7292      * @param {Object} config
7293      * @return {Roo.Toolbar.Item} The element's item
7294      */
7295     addDom : function(config, returnEl){
7296         var td = this.nextBlock();
7297         Roo.DomHelper.overwrite(td, config);
7298         var ti = new Roo.Toolbar.Item(td.firstChild);
7299         ti.render(td);
7300         this.items.add(ti);
7301         return ti;
7302     },
7303
7304     /**
7305      * Collection of fields on the toolbar.. usefull for quering (value is false if there are no fields)
7306      * @type Roo.util.MixedCollection  
7307      */
7308     fields : false,
7309     
7310     /**
7311      * Adds a dynamically rendered Roo.form field (TextField, ComboBox, etc).
7312      * Note: the field should not have been rendered yet. For a field that has already been
7313      * rendered, use {@link #addElement}.
7314      * @param {Roo.form.Field} field
7315      * @return {Roo.ToolbarItem}
7316      */
7317      
7318       
7319     addField : function(field) {
7320         if (!this.fields) {
7321             var autoId = 0;
7322             this.fields = new Roo.util.MixedCollection(false, function(o){
7323                 return o.id || ("item" + (++autoId));
7324             });
7325
7326         }
7327         
7328         var td = this.nextBlock();
7329         field.render(td);
7330         var ti = new Roo.Toolbar.Item(td.firstChild);
7331         ti.render(td);
7332         this.items.add(ti);
7333         this.fields.add(field);
7334         return ti;
7335     },
7336     /**
7337      * Hide the toolbar
7338      * @method hide
7339      */
7340      
7341       
7342     hide : function()
7343     {
7344         this.el.child('div').setVisibilityMode(Roo.Element.DISPLAY);
7345         this.el.child('div').hide();
7346     },
7347     /**
7348      * Show the toolbar
7349      * @method show
7350      */
7351     show : function()
7352     {
7353         this.el.child('div').show();
7354     },
7355       
7356     // private
7357     nextBlock : function(){
7358         var td = document.createElement("td");
7359         this.tr.appendChild(td);
7360         return td;
7361     },
7362
7363     // private
7364     destroy : function(){
7365         if(this.items){ // rendered?
7366             Roo.destroy.apply(Roo, this.items.items);
7367         }
7368         if(this.fields){ // rendered?
7369             Roo.destroy.apply(Roo, this.fields.items);
7370         }
7371         Roo.Element.uncache(this.el, this.tr);
7372     }
7373 };
7374
7375 /**
7376  * @class Roo.Toolbar.Item
7377  * The base class that other classes should extend in order to get some basic common toolbar item functionality.
7378  * @constructor
7379  * Creates a new Item
7380  * @param {HTMLElement} el 
7381  */
7382 Roo.Toolbar.Item = function(el){
7383     var cfg = {};
7384     if (typeof (el.xtype) != 'undefined') {
7385         cfg = el;
7386         el = cfg.el;
7387     }
7388     
7389     this.el = Roo.getDom(el);
7390     this.id = Roo.id(this.el);
7391     this.hidden = false;
7392     
7393     this.addEvents({
7394          /**
7395              * @event render
7396              * Fires when the button is rendered
7397              * @param {Button} this
7398              */
7399         'render': true
7400     });
7401     Roo.Toolbar.Item.superclass.constructor.call(this,cfg);
7402 };
7403 Roo.extend(Roo.Toolbar.Item, Roo.util.Observable, {
7404 //Roo.Toolbar.Item.prototype = {
7405     
7406     /**
7407      * Get this item's HTML Element
7408      * @return {HTMLElement}
7409      */
7410     getEl : function(){
7411        return this.el;  
7412     },
7413
7414     // private
7415     render : function(td){
7416         
7417          this.td = td;
7418         td.appendChild(this.el);
7419         
7420         this.fireEvent('render', this);
7421     },
7422     
7423     /**
7424      * Removes and destroys this item.
7425      */
7426     destroy : function(){
7427         this.td.parentNode.removeChild(this.td);
7428     },
7429     
7430     /**
7431      * Shows this item.
7432      */
7433     show: function(){
7434         this.hidden = false;
7435         this.td.style.display = "";
7436     },
7437     
7438     /**
7439      * Hides this item.
7440      */
7441     hide: function(){
7442         this.hidden = true;
7443         this.td.style.display = "none";
7444     },
7445     
7446     /**
7447      * Convenience function for boolean show/hide.
7448      * @param {Boolean} visible true to show/false to hide
7449      */
7450     setVisible: function(visible){
7451         if(visible) {
7452             this.show();
7453         }else{
7454             this.hide();
7455         }
7456     },
7457     
7458     /**
7459      * Try to focus this item.
7460      */
7461     focus : function(){
7462         Roo.fly(this.el).focus();
7463     },
7464     
7465     /**
7466      * Disables this item.
7467      */
7468     disable : function(){
7469         Roo.fly(this.td).addClass("x-item-disabled");
7470         this.disabled = true;
7471         this.el.disabled = true;
7472     },
7473     
7474     /**
7475      * Enables this item.
7476      */
7477     enable : function(){
7478         Roo.fly(this.td).removeClass("x-item-disabled");
7479         this.disabled = false;
7480         this.el.disabled = false;
7481     }
7482 });
7483
7484
7485 /**
7486  * @class Roo.Toolbar.Separator
7487  * @extends Roo.Toolbar.Item
7488  * A simple toolbar separator class
7489  * @constructor
7490  * Creates a new Separator
7491  */
7492 Roo.Toolbar.Separator = function(cfg){
7493     
7494     var s = document.createElement("span");
7495     s.className = "ytb-sep";
7496     if (cfg) {
7497         cfg.el = s;
7498     }
7499     
7500     Roo.Toolbar.Separator.superclass.constructor.call(this, cfg || s);
7501 };
7502 Roo.extend(Roo.Toolbar.Separator, Roo.Toolbar.Item, {
7503     enable:Roo.emptyFn,
7504     disable:Roo.emptyFn,
7505     focus:Roo.emptyFn
7506 });
7507
7508 /**
7509  * @class Roo.Toolbar.Spacer
7510  * @extends Roo.Toolbar.Item
7511  * A simple element that adds extra horizontal space to a toolbar.
7512  * @constructor
7513  * Creates a new Spacer
7514  */
7515 Roo.Toolbar.Spacer = function(cfg){
7516     var s = document.createElement("div");
7517     s.className = "ytb-spacer";
7518     if (cfg) {
7519         cfg.el = s;
7520     }
7521     Roo.Toolbar.Spacer.superclass.constructor.call(this, cfg || s);
7522 };
7523 Roo.extend(Roo.Toolbar.Spacer, Roo.Toolbar.Item, {
7524     enable:Roo.emptyFn,
7525     disable:Roo.emptyFn,
7526     focus:Roo.emptyFn
7527 });
7528
7529 /**
7530  * @class Roo.Toolbar.Fill
7531  * @extends Roo.Toolbar.Spacer
7532  * A simple element that adds a greedy (100% width) horizontal space to a toolbar.
7533  * @constructor
7534  * Creates a new Spacer
7535  */
7536 Roo.Toolbar.Fill = Roo.extend(Roo.Toolbar.Spacer, {
7537     // private
7538     render : function(td){
7539         td.style.width = '100%';
7540         Roo.Toolbar.Fill.superclass.render.call(this, td);
7541     }
7542 });
7543
7544 /**
7545  * @class Roo.Toolbar.TextItem
7546  * @extends Roo.Toolbar.Item
7547  * A simple class that renders text directly into a toolbar.
7548  * @constructor
7549  * Creates a new TextItem
7550  * @cfg {string} text 
7551  */
7552 Roo.Toolbar.TextItem = function(cfg){
7553     var  text = cfg || "";
7554     if (typeof(cfg) == 'object') {
7555         text = cfg.text || "";
7556     }  else {
7557         cfg = null;
7558     }
7559     var s = document.createElement("span");
7560     s.className = "ytb-text";
7561     s.innerHTML = text;
7562     if (cfg) {
7563         cfg.el  = s;
7564     }
7565     
7566     Roo.Toolbar.TextItem.superclass.constructor.call(this, cfg ||  s);
7567 };
7568 Roo.extend(Roo.Toolbar.TextItem, Roo.Toolbar.Item, {
7569     
7570      
7571     enable:Roo.emptyFn,
7572     disable:Roo.emptyFn,
7573     focus:Roo.emptyFn,
7574      /**
7575      * Shows this button
7576      */
7577     show: function(){
7578         this.hidden = false;
7579         this.el.style.display = "";
7580     },
7581     
7582     /**
7583      * Hides this button
7584      */
7585     hide: function(){
7586         this.hidden = true;
7587         this.el.style.display = "none";
7588     }
7589     
7590 });
7591
7592 /**
7593  * @class Roo.Toolbar.Button
7594  * @extends Roo.Button
7595  * A button that renders into a toolbar.
7596  * @constructor
7597  * Creates a new Button
7598  * @param {Object} config A standard {@link Roo.Button} config object
7599  */
7600 Roo.Toolbar.Button = function(config){
7601     Roo.Toolbar.Button.superclass.constructor.call(this, null, config);
7602 };
7603 Roo.extend(Roo.Toolbar.Button, Roo.Button,
7604 {
7605     
7606     
7607     render : function(td){
7608         this.td = td;
7609         Roo.Toolbar.Button.superclass.render.call(this, td);
7610     },
7611     
7612     /**
7613      * Removes and destroys this button
7614      */
7615     destroy : function(){
7616         Roo.Toolbar.Button.superclass.destroy.call(this);
7617         this.td.parentNode.removeChild(this.td);
7618     },
7619     
7620     /**
7621      * Shows this button
7622      */
7623     show: function(){
7624         this.hidden = false;
7625         this.td.style.display = "";
7626     },
7627     
7628     /**
7629      * Hides this button
7630      */
7631     hide: function(){
7632         this.hidden = true;
7633         this.td.style.display = "none";
7634     },
7635
7636     /**
7637      * Disables this item
7638      */
7639     disable : function(){
7640         Roo.fly(this.td).addClass("x-item-disabled");
7641         this.disabled = true;
7642     },
7643
7644     /**
7645      * Enables this item
7646      */
7647     enable : function(){
7648         Roo.fly(this.td).removeClass("x-item-disabled");
7649         this.disabled = false;
7650     }
7651 });
7652 // backwards compat
7653 Roo.ToolbarButton = Roo.Toolbar.Button;
7654
7655 /**
7656  * @class Roo.Toolbar.SplitButton
7657  * @extends Roo.SplitButton
7658  * A menu button that renders into a toolbar.
7659  * @constructor
7660  * Creates a new SplitButton
7661  * @param {Object} config A standard {@link Roo.SplitButton} config object
7662  */
7663 Roo.Toolbar.SplitButton = function(config){
7664     Roo.Toolbar.SplitButton.superclass.constructor.call(this, null, config);
7665 };
7666 Roo.extend(Roo.Toolbar.SplitButton, Roo.SplitButton, {
7667     render : function(td){
7668         this.td = td;
7669         Roo.Toolbar.SplitButton.superclass.render.call(this, td);
7670     },
7671     
7672     /**
7673      * Removes and destroys this button
7674      */
7675     destroy : function(){
7676         Roo.Toolbar.SplitButton.superclass.destroy.call(this);
7677         this.td.parentNode.removeChild(this.td);
7678     },
7679     
7680     /**
7681      * Shows this button
7682      */
7683     show: function(){
7684         this.hidden = false;
7685         this.td.style.display = "";
7686     },
7687     
7688     /**
7689      * Hides this button
7690      */
7691     hide: function(){
7692         this.hidden = true;
7693         this.td.style.display = "none";
7694     }
7695 });
7696
7697 // backwards compat
7698 Roo.Toolbar.MenuButton = Roo.Toolbar.SplitButton;/*
7699  * Based on:
7700  * Ext JS Library 1.1.1
7701  * Copyright(c) 2006-2007, Ext JS, LLC.
7702  *
7703  * Originally Released Under LGPL - original licence link has changed is not relivant.
7704  *
7705  * Fork - LGPL
7706  * <script type="text/javascript">
7707  */
7708  
7709 /**
7710  * @class Roo.PagingToolbar
7711  * @extends Roo.Toolbar
7712  * @children   Roo.Toolbar.Item Roo.Toolbar.Button Roo.Toolbar.SplitButton Roo.form.Field
7713  * A specialized toolbar that is bound to a {@link Roo.data.Store} and provides automatic paging controls.
7714  * @constructor
7715  * Create a new PagingToolbar
7716  * @param {Object} config The config object
7717  */
7718 Roo.PagingToolbar = function(el, ds, config)
7719 {
7720     // old args format still supported... - xtype is prefered..
7721     if (typeof(el) == 'object' && el.xtype) {
7722         // created from xtype...
7723         config = el;
7724         ds = el.dataSource;
7725         el = config.container;
7726     }
7727     var items = [];
7728     if (config.items) {
7729         items = config.items;
7730         config.items = [];
7731     }
7732     
7733     Roo.PagingToolbar.superclass.constructor.call(this, el, null, config);
7734     this.ds = ds;
7735     this.cursor = 0;
7736     this.renderButtons(this.el);
7737     this.bind(ds);
7738     
7739     // supprot items array.
7740    
7741     Roo.each(items, function(e) {
7742         this.add(Roo.factory(e));
7743     },this);
7744     
7745 };
7746
7747 Roo.extend(Roo.PagingToolbar, Roo.Toolbar, {
7748    
7749     /**
7750      * @cfg {String/HTMLElement/Element} container
7751      * container The id or element that will contain the toolbar
7752      */
7753     /**
7754      * @cfg {Boolean} displayInfo
7755      * True to display the displayMsg (defaults to false)
7756      */
7757     
7758     
7759     /**
7760      * @cfg {Number} pageSize
7761      * The number of records to display per page (defaults to 20)
7762      */
7763     pageSize: 20,
7764     /**
7765      * @cfg {String} displayMsg
7766      * The paging status message to display (defaults to "Displaying {start} - {end} of {total}")
7767      */
7768     displayMsg : 'Displaying {0} - {1} of {2}',
7769     /**
7770      * @cfg {String} emptyMsg
7771      * The message to display when no records are found (defaults to "No data to display")
7772      */
7773     emptyMsg : 'No data to display',
7774     /**
7775      * Customizable piece of the default paging text (defaults to "Page")
7776      * @type String
7777      */
7778     beforePageText : "Page",
7779     /**
7780      * Customizable piece of the default paging text (defaults to "of %0")
7781      * @type String
7782      */
7783     afterPageText : "of {0}",
7784     /**
7785      * Customizable piece of the default paging text (defaults to "First Page")
7786      * @type String
7787      */
7788     firstText : "First Page",
7789     /**
7790      * Customizable piece of the default paging text (defaults to "Previous Page")
7791      * @type String
7792      */
7793     prevText : "Previous Page",
7794     /**
7795      * Customizable piece of the default paging text (defaults to "Next Page")
7796      * @type String
7797      */
7798     nextText : "Next Page",
7799     /**
7800      * Customizable piece of the default paging text (defaults to "Last Page")
7801      * @type String
7802      */
7803     lastText : "Last Page",
7804     /**
7805      * Customizable piece of the default paging text (defaults to "Refresh")
7806      * @type String
7807      */
7808     refreshText : "Refresh",
7809
7810     // private
7811     renderButtons : function(el){
7812         Roo.PagingToolbar.superclass.render.call(this, el);
7813         this.first = this.addButton({
7814             tooltip: this.firstText,
7815             cls: "x-btn-icon x-grid-page-first",
7816             disabled: true,
7817             handler: this.onClick.createDelegate(this, ["first"])
7818         });
7819         this.prev = this.addButton({
7820             tooltip: this.prevText,
7821             cls: "x-btn-icon x-grid-page-prev",
7822             disabled: true,
7823             handler: this.onClick.createDelegate(this, ["prev"])
7824         });
7825         //this.addSeparator();
7826         this.add(this.beforePageText);
7827         this.field = Roo.get(this.addDom({
7828            tag: "input",
7829            type: "text",
7830            size: "3",
7831            value: "1",
7832            cls: "x-grid-page-number"
7833         }).el);
7834         this.field.on("keydown", this.onPagingKeydown, this);
7835         this.field.on("focus", function(){this.dom.select();});
7836         this.afterTextEl = this.addText(String.format(this.afterPageText, 1));
7837         this.field.setHeight(18);
7838         //this.addSeparator();
7839         this.next = this.addButton({
7840             tooltip: this.nextText,
7841             cls: "x-btn-icon x-grid-page-next",
7842             disabled: true,
7843             handler: this.onClick.createDelegate(this, ["next"])
7844         });
7845         this.last = this.addButton({
7846             tooltip: this.lastText,
7847             cls: "x-btn-icon x-grid-page-last",
7848             disabled: true,
7849             handler: this.onClick.createDelegate(this, ["last"])
7850         });
7851         //this.addSeparator();
7852         this.loading = this.addButton({
7853             tooltip: this.refreshText,
7854             cls: "x-btn-icon x-grid-loading",
7855             handler: this.onClick.createDelegate(this, ["refresh"])
7856         });
7857
7858         if(this.displayInfo){
7859             this.displayEl = Roo.fly(this.el.dom.firstChild).createChild({cls:'x-paging-info'});
7860         }
7861     },
7862
7863     // private
7864     updateInfo : function(){
7865         if(this.displayEl){
7866             var count = this.ds.getCount();
7867             var msg = count == 0 ?
7868                 this.emptyMsg :
7869                 String.format(
7870                     this.displayMsg,
7871                     this.cursor+1, this.cursor+count, this.ds.getTotalCount()    
7872                 );
7873             this.displayEl.update(msg);
7874         }
7875     },
7876
7877     // private
7878     onLoad : function(ds, r, o){
7879        this.cursor = o.params ? o.params.start : 0;
7880        var d = this.getPageData(), ap = d.activePage, ps = d.pages;
7881
7882        this.afterTextEl.el.innerHTML = String.format(this.afterPageText, d.pages);
7883        this.field.dom.value = ap;
7884        this.first.setDisabled(ap == 1);
7885        this.prev.setDisabled(ap == 1);
7886        this.next.setDisabled(ap == ps);
7887        this.last.setDisabled(ap == ps);
7888        this.loading.enable();
7889        this.updateInfo();
7890     },
7891
7892     // private
7893     getPageData : function(){
7894         var total = this.ds.getTotalCount();
7895         return {
7896             total : total,
7897             activePage : Math.ceil((this.cursor+this.pageSize)/this.pageSize),
7898             pages :  total < this.pageSize ? 1 : Math.ceil(total/this.pageSize)
7899         };
7900     },
7901
7902     // private
7903     onLoadError : function(){
7904         this.loading.enable();
7905     },
7906
7907     // private
7908     onPagingKeydown : function(e){
7909         var k = e.getKey();
7910         var d = this.getPageData();
7911         if(k == e.RETURN){
7912             var v = this.field.dom.value, pageNum;
7913             if(!v || isNaN(pageNum = parseInt(v, 10))){
7914                 this.field.dom.value = d.activePage;
7915                 return;
7916             }
7917             pageNum = Math.min(Math.max(1, pageNum), d.pages) - 1;
7918             this.ds.load({params:{start: pageNum * this.pageSize, limit: this.pageSize}});
7919             e.stopEvent();
7920         }
7921         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))
7922         {
7923           var pageNum = (k == e.HOME || (k == e.DOWN && e.ctrlKey) || (k == e.LEFT && e.ctrlKey) || (k == e.PAGEDOWN && e.ctrlKey)) ? 1 : d.pages;
7924           this.field.dom.value = pageNum;
7925           this.ds.load({params:{start: (pageNum - 1) * this.pageSize, limit: this.pageSize}});
7926           e.stopEvent();
7927         }
7928         else if(k == e.UP || k == e.RIGHT || k == e.PAGEUP || k == e.DOWN || k == e.LEFT || k == e.PAGEDOWN)
7929         {
7930           var v = this.field.dom.value, pageNum; 
7931           var increment = (e.shiftKey) ? 10 : 1;
7932           if(k == e.DOWN || k == e.LEFT || k == e.PAGEDOWN) {
7933             increment *= -1;
7934           }
7935           if(!v || isNaN(pageNum = parseInt(v, 10))) {
7936             this.field.dom.value = d.activePage;
7937             return;
7938           }
7939           else if(parseInt(v, 10) + increment >= 1 & parseInt(v, 10) + increment <= d.pages)
7940           {
7941             this.field.dom.value = parseInt(v, 10) + increment;
7942             pageNum = Math.min(Math.max(1, pageNum + increment), d.pages) - 1;
7943             this.ds.load({params:{start: pageNum * this.pageSize, limit: this.pageSize}});
7944           }
7945           e.stopEvent();
7946         }
7947     },
7948
7949     // private
7950     beforeLoad : function(){
7951         if(this.loading){
7952             this.loading.disable();
7953         }
7954     },
7955     /**
7956      * event that occurs when you click on the navigation buttons - can be used to trigger load of a grid.
7957      * @param {String} which (first|prev|next|last|refresh)  which button to press.
7958      *
7959      */
7960     // private
7961     onClick : function(which){
7962         var ds = this.ds;
7963         switch(which){
7964             case "first":
7965                 ds.load({params:{start: 0, limit: this.pageSize}});
7966             break;
7967             case "prev":
7968                 ds.load({params:{start: Math.max(0, this.cursor-this.pageSize), limit: this.pageSize}});
7969             break;
7970             case "next":
7971                 ds.load({params:{start: this.cursor+this.pageSize, limit: this.pageSize}});
7972             break;
7973             case "last":
7974                 var total = ds.getTotalCount();
7975                 var extra = total % this.pageSize;
7976                 var lastStart = extra ? (total - extra) : total-this.pageSize;
7977                 ds.load({params:{start: lastStart, limit: this.pageSize}});
7978             break;
7979             case "refresh":
7980                 ds.load({params:{start: this.cursor, limit: this.pageSize}});
7981             break;
7982         }
7983     },
7984
7985     /**
7986      * Unbinds the paging toolbar from the specified {@link Roo.data.Store}
7987      * @param {Roo.data.Store} store The data store to unbind
7988      */
7989     unbind : function(ds){
7990         ds.un("beforeload", this.beforeLoad, this);
7991         ds.un("load", this.onLoad, this);
7992         ds.un("loadexception", this.onLoadError, this);
7993         ds.un("remove", this.updateInfo, this);
7994         ds.un("add", this.updateInfo, this);
7995         this.ds = undefined;
7996     },
7997
7998     /**
7999      * Binds the paging toolbar to the specified {@link Roo.data.Store}
8000      * @param {Roo.data.Store} store The data store to bind
8001      */
8002     bind : function(ds){
8003         ds.on("beforeload", this.beforeLoad, this);
8004         ds.on("load", this.onLoad, this);
8005         ds.on("loadexception", this.onLoadError, this);
8006         ds.on("remove", this.updateInfo, this);
8007         ds.on("add", this.updateInfo, this);
8008         this.ds = ds;
8009     }
8010 });/*
8011  * Based on:
8012  * Ext JS Library 1.1.1
8013  * Copyright(c) 2006-2007, Ext JS, LLC.
8014  *
8015  * Originally Released Under LGPL - original licence link has changed is not relivant.
8016  *
8017  * Fork - LGPL
8018  * <script type="text/javascript">
8019  */
8020
8021 /**
8022  * @class Roo.Resizable
8023  * @extends Roo.util.Observable
8024  * <p>Applies drag handles to an element to make it resizable. The drag handles are inserted into the element
8025  * and positioned absolute. Some elements, such as a textarea or image, don't support this. To overcome that, you can wrap
8026  * 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
8027  * the element will be wrapped for you automatically.</p>
8028  * <p>Here is the list of valid resize handles:</p>
8029  * <pre>
8030 Value   Description
8031 ------  -------------------
8032  'n'     north
8033  's'     south
8034  'e'     east
8035  'w'     west
8036  'nw'    northwest
8037  'sw'    southwest
8038  'se'    southeast
8039  'ne'    northeast
8040  'hd'    horizontal drag
8041  'all'   all
8042 </pre>
8043  * <p>Here's an example showing the creation of a typical Resizable:</p>
8044  * <pre><code>
8045 var resizer = new Roo.Resizable("element-id", {
8046     handles: 'all',
8047     minWidth: 200,
8048     minHeight: 100,
8049     maxWidth: 500,
8050     maxHeight: 400,
8051     pinned: true
8052 });
8053 resizer.on("resize", myHandler);
8054 </code></pre>
8055  * <p>To hide a particular handle, set its display to none in CSS, or through script:<br>
8056  * resizer.east.setDisplayed(false);</p>
8057  * @cfg {Boolean/String/Element} resizeChild True to resize the first child, or id/element to resize (defaults to false)
8058  * @cfg {Array/String} adjustments String "auto" or an array [width, height] with values to be <b>added</b> to the
8059  * resize operation's new size (defaults to [0, 0])
8060  * @cfg {Number} minWidth The minimum width for the element (defaults to 5)
8061  * @cfg {Number} minHeight The minimum height for the element (defaults to 5)
8062  * @cfg {Number} maxWidth The maximum width for the element (defaults to 10000)
8063  * @cfg {Number} maxHeight The maximum height for the element (defaults to 10000)
8064  * @cfg {Boolean} enabled False to disable resizing (defaults to true)
8065  * @cfg {Boolean} wrap True to wrap an element with a div if needed (required for textareas and images, defaults to false)
8066  * @cfg {Number} width The width of the element in pixels (defaults to null)
8067  * @cfg {Number} height The height of the element in pixels (defaults to null)
8068  * @cfg {Boolean} animate True to animate the resize (not compatible with dynamic sizing, defaults to false)
8069  * @cfg {Number} duration Animation duration if animate = true (defaults to .35)
8070  * @cfg {Boolean} dynamic True to resize the element while dragging instead of using a proxy (defaults to false)
8071  * @cfg {String} handles String consisting of the resize handles to display (defaults to undefined)
8072  * @cfg {Boolean} multiDirectional <b>Deprecated</b>.  The old style of adding multi-direction resize handles, deprecated
8073  * in favor of the handles config option (defaults to false)
8074  * @cfg {Boolean} disableTrackOver True to disable mouse tracking. This is only applied at config time. (defaults to false)
8075  * @cfg {String} easing Animation easing if animate = true (defaults to 'easingOutStrong')
8076  * @cfg {Number} widthIncrement The increment to snap the width resize in pixels (dynamic must be true, defaults to 0)
8077  * @cfg {Number} heightIncrement The increment to snap the height resize in pixels (dynamic must be true, defaults to 0)
8078  * @cfg {Boolean} pinned True to ensure that the resize handles are always visible, false to display them only when the
8079  * user mouses over the resizable borders. This is only applied at config time. (defaults to false)
8080  * @cfg {Boolean} preserveRatio True to preserve the original ratio between height and width during resize (defaults to false)
8081  * @cfg {Boolean} transparent True for transparent handles. This is only applied at config time. (defaults to false)
8082  * @cfg {Number} minX The minimum allowed page X for the element (only used for west resizing, defaults to 0)
8083  * @cfg {Number} minY The minimum allowed page Y for the element (only used for north resizing, defaults to 0)
8084  * @cfg {Boolean} draggable Convenience to initialize drag drop (defaults to false)
8085  * @constructor
8086  * Create a new resizable component
8087  * @param {String/HTMLElement/Roo.Element} el The id or element to resize
8088  * @param {Object} config configuration options
8089   */
8090 Roo.Resizable = function(el, config)
8091 {
8092     this.el = Roo.get(el);
8093
8094     if(config && config.wrap){
8095         config.resizeChild = this.el;
8096         this.el = this.el.wrap(typeof config.wrap == "object" ? config.wrap : {cls:"xresizable-wrap"});
8097         this.el.id = this.el.dom.id = config.resizeChild.id + "-rzwrap";
8098         this.el.setStyle("overflow", "hidden");
8099         this.el.setPositioning(config.resizeChild.getPositioning());
8100         config.resizeChild.clearPositioning();
8101         if(!config.width || !config.height){
8102             var csize = config.resizeChild.getSize();
8103             this.el.setSize(csize.width, csize.height);
8104         }
8105         if(config.pinned && !config.adjustments){
8106             config.adjustments = "auto";
8107         }
8108     }
8109
8110     this.proxy = this.el.createProxy({tag: "div", cls: "x-resizable-proxy", id: this.el.id + "-rzproxy"});
8111     this.proxy.unselectable();
8112     this.proxy.enableDisplayMode('block');
8113
8114     Roo.apply(this, config);
8115
8116     if(this.pinned){
8117         this.disableTrackOver = true;
8118         this.el.addClass("x-resizable-pinned");
8119     }
8120     // if the element isn't positioned, make it relative
8121     var position = this.el.getStyle("position");
8122     if(position != "absolute" && position != "fixed"){
8123         this.el.setStyle("position", "relative");
8124     }
8125     if(!this.handles){ // no handles passed, must be legacy style
8126         this.handles = 's,e,se';
8127         if(this.multiDirectional){
8128             this.handles += ',n,w';
8129         }
8130     }
8131     if(this.handles == "all"){
8132         this.handles = "n s e w ne nw se sw";
8133     }
8134     var hs = this.handles.split(/\s*?[,;]\s*?| /);
8135     var ps = Roo.Resizable.positions;
8136     for(var i = 0, len = hs.length; i < len; i++){
8137         if(hs[i] && ps[hs[i]]){
8138             var pos = ps[hs[i]];
8139             this[pos] = new Roo.Resizable.Handle(this, pos, this.disableTrackOver, this.transparent);
8140         }
8141     }
8142     // legacy
8143     this.corner = this.southeast;
8144     
8145     // updateBox = the box can move..
8146     if(this.handles.indexOf("n") != -1 || this.handles.indexOf("w") != -1 || this.handles.indexOf("hd") != -1) {
8147         this.updateBox = true;
8148     }
8149
8150     this.activeHandle = null;
8151
8152     if(this.resizeChild){
8153         if(typeof this.resizeChild == "boolean"){
8154             this.resizeChild = Roo.get(this.el.dom.firstChild, true);
8155         }else{
8156             this.resizeChild = Roo.get(this.resizeChild, true);
8157         }
8158     }
8159     
8160     if(this.adjustments == "auto"){
8161         var rc = this.resizeChild;
8162         var hw = this.west, he = this.east, hn = this.north, hs = this.south;
8163         if(rc && (hw || hn)){
8164             rc.position("relative");
8165             rc.setLeft(hw ? hw.el.getWidth() : 0);
8166             rc.setTop(hn ? hn.el.getHeight() : 0);
8167         }
8168         this.adjustments = [
8169             (he ? -he.el.getWidth() : 0) + (hw ? -hw.el.getWidth() : 0),
8170             (hn ? -hn.el.getHeight() : 0) + (hs ? -hs.el.getHeight() : 0) -1
8171         ];
8172     }
8173
8174     if(this.draggable){
8175         this.dd = this.dynamic ?
8176             this.el.initDD(null) : this.el.initDDProxy(null, {dragElId: this.proxy.id});
8177         this.dd.setHandleElId(this.resizeChild ? this.resizeChild.id : this.el.id);
8178     }
8179
8180     // public events
8181     this.addEvents({
8182         /**
8183          * @event beforeresize
8184          * Fired before resize is allowed. Set enabled to false to cancel resize.
8185          * @param {Roo.Resizable} this
8186          * @param {Roo.EventObject} e The mousedown event
8187          */
8188         "beforeresize" : true,
8189         /**
8190          * @event resizing
8191          * Fired a resizing.
8192          * @param {Roo.Resizable} this
8193          * @param {Number} x The new x position
8194          * @param {Number} y The new y position
8195          * @param {Number} w The new w width
8196          * @param {Number} h The new h hight
8197          * @param {Roo.EventObject} e The mouseup event
8198          */
8199         "resizing" : true,
8200         /**
8201          * @event resize
8202          * Fired after a resize.
8203          * @param {Roo.Resizable} this
8204          * @param {Number} width The new width
8205          * @param {Number} height The new height
8206          * @param {Roo.EventObject} e The mouseup event
8207          */
8208         "resize" : true
8209     });
8210
8211     if(this.width !== null && this.height !== null){
8212         this.resizeTo(this.width, this.height);
8213     }else{
8214         this.updateChildSize();
8215     }
8216     if(Roo.isIE){
8217         this.el.dom.style.zoom = 1;
8218     }
8219     Roo.Resizable.superclass.constructor.call(this);
8220 };
8221
8222 Roo.extend(Roo.Resizable, Roo.util.Observable, {
8223         resizeChild : false,
8224         adjustments : [0, 0],
8225         minWidth : 5,
8226         minHeight : 5,
8227         maxWidth : 10000,
8228         maxHeight : 10000,
8229         enabled : true,
8230         animate : false,
8231         duration : .35,
8232         dynamic : false,
8233         handles : false,
8234         multiDirectional : false,
8235         disableTrackOver : false,
8236         easing : 'easeOutStrong',
8237         widthIncrement : 0,
8238         heightIncrement : 0,
8239         pinned : false,
8240         width : null,
8241         height : null,
8242         preserveRatio : false,
8243         transparent: false,
8244         minX: 0,
8245         minY: 0,
8246         draggable: false,
8247
8248         /**
8249          * @cfg {String/HTMLElement/Element} constrainTo Constrain the resize to a particular element
8250          */
8251         constrainTo: undefined,
8252         /**
8253          * @cfg {Roo.lib.Region} resizeRegion Constrain the resize to a particular region
8254          */
8255         resizeRegion: undefined,
8256
8257
8258     /**
8259      * Perform a manual resize
8260      * @param {Number} width
8261      * @param {Number} height
8262      */
8263     resizeTo : function(width, height){
8264         this.el.setSize(width, height);
8265         this.updateChildSize();
8266         this.fireEvent("resize", this, width, height, null);
8267     },
8268
8269     // private
8270     startSizing : function(e, handle){
8271         this.fireEvent("beforeresize", this, e);
8272         if(this.enabled){ // 2nd enabled check in case disabled before beforeresize handler
8273
8274             if(!this.overlay){
8275                 this.overlay = this.el.createProxy({tag: "div", cls: "x-resizable-overlay", html: "&#160;"});
8276                 this.overlay.unselectable();
8277                 this.overlay.enableDisplayMode("block");
8278                 this.overlay.on("mousemove", this.onMouseMove, this);
8279                 this.overlay.on("mouseup", this.onMouseUp, this);
8280             }
8281             this.overlay.setStyle("cursor", handle.el.getStyle("cursor"));
8282
8283             this.resizing = true;
8284             this.startBox = this.el.getBox();
8285             this.startPoint = e.getXY();
8286             this.offsets = [(this.startBox.x + this.startBox.width) - this.startPoint[0],
8287                             (this.startBox.y + this.startBox.height) - this.startPoint[1]];
8288
8289             this.overlay.setSize(Roo.lib.Dom.getViewWidth(true), Roo.lib.Dom.getViewHeight(true));
8290             this.overlay.show();
8291
8292             if(this.constrainTo) {
8293                 var ct = Roo.get(this.constrainTo);
8294                 this.resizeRegion = ct.getRegion().adjust(
8295                     ct.getFrameWidth('t'),
8296                     ct.getFrameWidth('l'),
8297                     -ct.getFrameWidth('b'),
8298                     -ct.getFrameWidth('r')
8299                 );
8300             }
8301
8302             this.proxy.setStyle('visibility', 'hidden'); // workaround display none
8303             this.proxy.show();
8304             this.proxy.setBox(this.startBox);
8305             if(!this.dynamic){
8306                 this.proxy.setStyle('visibility', 'visible');
8307             }
8308         }
8309     },
8310
8311     // private
8312     onMouseDown : function(handle, e){
8313         if(this.enabled){
8314             e.stopEvent();
8315             this.activeHandle = handle;
8316             this.startSizing(e, handle);
8317         }
8318     },
8319
8320     // private
8321     onMouseUp : function(e){
8322         var size = this.resizeElement();
8323         this.resizing = false;
8324         this.handleOut();
8325         this.overlay.hide();
8326         this.proxy.hide();
8327         this.fireEvent("resize", this, size.width, size.height, e);
8328     },
8329
8330     // private
8331     updateChildSize : function(){
8332         
8333         if(this.resizeChild){
8334             var el = this.el;
8335             var child = this.resizeChild;
8336             var adj = this.adjustments;
8337             if(el.dom.offsetWidth){
8338                 var b = el.getSize(true);
8339                 child.setSize(b.width+adj[0], b.height+adj[1]);
8340             }
8341             // Second call here for IE
8342             // The first call enables instant resizing and
8343             // the second call corrects scroll bars if they
8344             // exist
8345             if(Roo.isIE){
8346                 setTimeout(function(){
8347                     if(el.dom.offsetWidth){
8348                         var b = el.getSize(true);
8349                         child.setSize(b.width+adj[0], b.height+adj[1]);
8350                     }
8351                 }, 10);
8352             }
8353         }
8354     },
8355
8356     // private
8357     snap : function(value, inc, min){
8358         if(!inc || !value) {
8359             return value;
8360         }
8361         var newValue = value;
8362         var m = value % inc;
8363         if(m > 0){
8364             if(m > (inc/2)){
8365                 newValue = value + (inc-m);
8366             }else{
8367                 newValue = value - m;
8368             }
8369         }
8370         return Math.max(min, newValue);
8371     },
8372
8373     // private
8374     resizeElement : function(){
8375         var box = this.proxy.getBox();
8376         if(this.updateBox){
8377             this.el.setBox(box, false, this.animate, this.duration, null, this.easing);
8378         }else{
8379             this.el.setSize(box.width, box.height, this.animate, this.duration, null, this.easing);
8380         }
8381         this.updateChildSize();
8382         if(!this.dynamic){
8383             this.proxy.hide();
8384         }
8385         return box;
8386     },
8387
8388     // private
8389     constrain : function(v, diff, m, mx){
8390         if(v - diff < m){
8391             diff = v - m;
8392         }else if(v - diff > mx){
8393             diff = mx - v;
8394         }
8395         return diff;
8396     },
8397
8398     // private
8399     onMouseMove : function(e){
8400         
8401         if(this.enabled){
8402             try{// try catch so if something goes wrong the user doesn't get hung
8403
8404             if(this.resizeRegion && !this.resizeRegion.contains(e.getPoint())) {
8405                 return;
8406             }
8407
8408             //var curXY = this.startPoint;
8409             var curSize = this.curSize || this.startBox;
8410             var x = this.startBox.x, y = this.startBox.y;
8411             var ox = x, oy = y;
8412             var w = curSize.width, h = curSize.height;
8413             var ow = w, oh = h;
8414             var mw = this.minWidth, mh = this.minHeight;
8415             var mxw = this.maxWidth, mxh = this.maxHeight;
8416             var wi = this.widthIncrement;
8417             var hi = this.heightIncrement;
8418
8419             var eventXY = e.getXY();
8420             var diffX = -(this.startPoint[0] - Math.max(this.minX, eventXY[0]));
8421             var diffY = -(this.startPoint[1] - Math.max(this.minY, eventXY[1]));
8422
8423             var pos = this.activeHandle.position;
8424
8425             switch(pos){
8426                 case "east":
8427                     w += diffX;
8428                     w = Math.min(Math.max(mw, w), mxw);
8429                     break;
8430              
8431                 case "south":
8432                     h += diffY;
8433                     h = Math.min(Math.max(mh, h), mxh);
8434                     break;
8435                 case "southeast":
8436                     w += diffX;
8437                     h += diffY;
8438                     w = Math.min(Math.max(mw, w), mxw);
8439                     h = Math.min(Math.max(mh, h), mxh);
8440                     break;
8441                 case "north":
8442                     diffY = this.constrain(h, diffY, mh, mxh);
8443                     y += diffY;
8444                     h -= diffY;
8445                     break;
8446                 case "hdrag":
8447                     
8448                     if (wi) {
8449                         var adiffX = Math.abs(diffX);
8450                         var sub = (adiffX % wi); // how much 
8451                         if (sub > (wi/2)) { // far enough to snap
8452                             diffX = (diffX > 0) ? diffX-sub + wi : diffX+sub - wi;
8453                         } else {
8454                             // remove difference.. 
8455                             diffX = (diffX > 0) ? diffX-sub : diffX+sub;
8456                         }
8457                     }
8458                     x += diffX;
8459                     x = Math.max(this.minX, x);
8460                     break;
8461                 case "west":
8462                     diffX = this.constrain(w, diffX, mw, mxw);
8463                     x += diffX;
8464                     w -= diffX;
8465                     break;
8466                 case "northeast":
8467                     w += diffX;
8468                     w = Math.min(Math.max(mw, w), mxw);
8469                     diffY = this.constrain(h, diffY, mh, mxh);
8470                     y += diffY;
8471                     h -= diffY;
8472                     break;
8473                 case "northwest":
8474                     diffX = this.constrain(w, diffX, mw, mxw);
8475                     diffY = this.constrain(h, diffY, mh, mxh);
8476                     y += diffY;
8477                     h -= diffY;
8478                     x += diffX;
8479                     w -= diffX;
8480                     break;
8481                case "southwest":
8482                     diffX = this.constrain(w, diffX, mw, mxw);
8483                     h += diffY;
8484                     h = Math.min(Math.max(mh, h), mxh);
8485                     x += diffX;
8486                     w -= diffX;
8487                     break;
8488             }
8489
8490             var sw = this.snap(w, wi, mw);
8491             var sh = this.snap(h, hi, mh);
8492             if(sw != w || sh != h){
8493                 switch(pos){
8494                     case "northeast":
8495                         y -= sh - h;
8496                     break;
8497                     case "north":
8498                         y -= sh - h;
8499                         break;
8500                     case "southwest":
8501                         x -= sw - w;
8502                     break;
8503                     case "west":
8504                         x -= sw - w;
8505                         break;
8506                     case "northwest":
8507                         x -= sw - w;
8508                         y -= sh - h;
8509                     break;
8510                 }
8511                 w = sw;
8512                 h = sh;
8513             }
8514
8515             if(this.preserveRatio){
8516                 switch(pos){
8517                     case "southeast":
8518                     case "east":
8519                         h = oh * (w/ow);
8520                         h = Math.min(Math.max(mh, h), mxh);
8521                         w = ow * (h/oh);
8522                        break;
8523                     case "south":
8524                         w = ow * (h/oh);
8525                         w = Math.min(Math.max(mw, w), mxw);
8526                         h = oh * (w/ow);
8527                         break;
8528                     case "northeast":
8529                         w = ow * (h/oh);
8530                         w = Math.min(Math.max(mw, w), mxw);
8531                         h = oh * (w/ow);
8532                     break;
8533                     case "north":
8534                         var tw = w;
8535                         w = ow * (h/oh);
8536                         w = Math.min(Math.max(mw, w), mxw);
8537                         h = oh * (w/ow);
8538                         x += (tw - w) / 2;
8539                         break;
8540                     case "southwest":
8541                         h = oh * (w/ow);
8542                         h = Math.min(Math.max(mh, h), mxh);
8543                         var tw = w;
8544                         w = ow * (h/oh);
8545                         x += tw - w;
8546                         break;
8547                     case "west":
8548                         var th = h;
8549                         h = oh * (w/ow);
8550                         h = Math.min(Math.max(mh, h), mxh);
8551                         y += (th - h) / 2;
8552                         var tw = w;
8553                         w = ow * (h/oh);
8554                         x += tw - w;
8555                        break;
8556                     case "northwest":
8557                         var tw = w;
8558                         var th = h;
8559                         h = oh * (w/ow);
8560                         h = Math.min(Math.max(mh, h), mxh);
8561                         w = ow * (h/oh);
8562                         y += th - h;
8563                         x += tw - w;
8564                        break;
8565
8566                 }
8567             }
8568             if (pos == 'hdrag') {
8569                 w = ow;
8570             }
8571             this.proxy.setBounds(x, y, w, h);
8572             if(this.dynamic){
8573                 this.resizeElement();
8574             }
8575             }catch(e){}
8576         }
8577         this.fireEvent("resizing", this, x, y, w, h, e);
8578     },
8579
8580     // private
8581     handleOver : function(){
8582         if(this.enabled){
8583             this.el.addClass("x-resizable-over");
8584         }
8585     },
8586
8587     // private
8588     handleOut : function(){
8589         if(!this.resizing){
8590             this.el.removeClass("x-resizable-over");
8591         }
8592     },
8593
8594     /**
8595      * Returns the element this component is bound to.
8596      * @return {Roo.Element}
8597      */
8598     getEl : function(){
8599         return this.el;
8600     },
8601
8602     /**
8603      * Returns the resizeChild element (or null).
8604      * @return {Roo.Element}
8605      */
8606     getResizeChild : function(){
8607         return this.resizeChild;
8608     },
8609     groupHandler : function()
8610     {
8611         
8612     },
8613     /**
8614      * Destroys this resizable. If the element was wrapped and
8615      * removeEl is not true then the element remains.
8616      * @param {Boolean} removeEl (optional) true to remove the element from the DOM
8617      */
8618     destroy : function(removeEl){
8619         this.proxy.remove();
8620         if(this.overlay){
8621             this.overlay.removeAllListeners();
8622             this.overlay.remove();
8623         }
8624         var ps = Roo.Resizable.positions;
8625         for(var k in ps){
8626             if(typeof ps[k] != "function" && this[ps[k]]){
8627                 var h = this[ps[k]];
8628                 h.el.removeAllListeners();
8629                 h.el.remove();
8630             }
8631         }
8632         if(removeEl){
8633             this.el.update("");
8634             this.el.remove();
8635         }
8636     }
8637 });
8638
8639 // private
8640 // hash to map config positions to true positions
8641 Roo.Resizable.positions = {
8642     n: "north", s: "south", e: "east", w: "west", se: "southeast", sw: "southwest", nw: "northwest", ne: "northeast", 
8643     hd: "hdrag"
8644 };
8645
8646 // private
8647 Roo.Resizable.Handle = function(rz, pos, disableTrackOver, transparent){
8648     if(!this.tpl){
8649         // only initialize the template if resizable is used
8650         var tpl = Roo.DomHelper.createTemplate(
8651             {tag: "div", cls: "x-resizable-handle x-resizable-handle-{0}"}
8652         );
8653         tpl.compile();
8654         Roo.Resizable.Handle.prototype.tpl = tpl;
8655     }
8656     this.position = pos;
8657     this.rz = rz;
8658     // show north drag fro topdra
8659     var handlepos = pos == 'hdrag' ? 'north' : pos;
8660     
8661     this.el = this.tpl.append(rz.el.dom, [handlepos], true);
8662     if (pos == 'hdrag') {
8663         this.el.setStyle('cursor', 'pointer');
8664     }
8665     this.el.unselectable();
8666     if(transparent){
8667         this.el.setOpacity(0);
8668     }
8669     this.el.on("mousedown", this.onMouseDown, this);
8670     if(!disableTrackOver){
8671         this.el.on("mouseover", this.onMouseOver, this);
8672         this.el.on("mouseout", this.onMouseOut, this);
8673     }
8674 };
8675
8676 // private
8677 Roo.Resizable.Handle.prototype = {
8678     afterResize : function(rz){
8679         Roo.log('after?');
8680         // do nothing
8681     },
8682     // private
8683     onMouseDown : function(e){
8684         this.rz.onMouseDown(this, e);
8685     },
8686     // private
8687     onMouseOver : function(e){
8688         this.rz.handleOver(this, e);
8689     },
8690     // private
8691     onMouseOut : function(e){
8692         this.rz.handleOut(this, e);
8693     }
8694 };/*
8695  * Based on:
8696  * Ext JS Library 1.1.1
8697  * Copyright(c) 2006-2007, Ext JS, LLC.
8698  *
8699  * Originally Released Under LGPL - original licence link has changed is not relivant.
8700  *
8701  * Fork - LGPL
8702  * <script type="text/javascript">
8703  */
8704
8705 /**
8706  * @class Roo.Editor
8707  * @extends Roo.Component
8708  * A base editor field that handles displaying/hiding on demand and has some built-in sizing and event handling logic.
8709  * @constructor
8710  * Create a new Editor
8711  * @param {Roo.form.Field} field The Field object (or descendant)
8712  * @param {Object} config The config object
8713  */
8714 Roo.Editor = function(field, config){
8715     Roo.Editor.superclass.constructor.call(this, config);
8716     this.field = field;
8717     this.addEvents({
8718         /**
8719              * @event beforestartedit
8720              * Fires when editing is initiated, but before the value changes.  Editing can be canceled by returning
8721              * false from the handler of this event.
8722              * @param {Editor} this
8723              * @param {Roo.Element} boundEl The underlying element bound to this editor
8724              * @param {Mixed} value The field value being set
8725              */
8726         "beforestartedit" : true,
8727         /**
8728              * @event startedit
8729              * Fires when this editor is displayed
8730              * @param {Roo.Element} boundEl The underlying element bound to this editor
8731              * @param {Mixed} value The starting field value
8732              */
8733         "startedit" : true,
8734         /**
8735              * @event beforecomplete
8736              * Fires after a change has been made to the field, but before the change is reflected in the underlying
8737              * field.  Saving the change to the field can be canceled by returning false from the handler of this event.
8738              * Note that if the value has not changed and ignoreNoChange = true, the editing will still end but this
8739              * event will not fire since no edit actually occurred.
8740              * @param {Editor} this
8741              * @param {Mixed} value The current field value
8742              * @param {Mixed} startValue The original field value
8743              */
8744         "beforecomplete" : true,
8745         /**
8746              * @event complete
8747              * Fires after editing is complete and any changed value has been written to the underlying field.
8748              * @param {Editor} this
8749              * @param {Mixed} value The current field value
8750              * @param {Mixed} startValue The original field value
8751              */
8752         "complete" : true,
8753         /**
8754          * @event specialkey
8755          * Fires when any key related to navigation (arrows, tab, enter, esc, etc.) is pressed.  You can check
8756          * {@link Roo.EventObject#getKey} to determine which key was pressed.
8757          * @param {Roo.form.Field} this
8758          * @param {Roo.EventObject} e The event object
8759          */
8760         "specialkey" : true
8761     });
8762 };
8763
8764 Roo.extend(Roo.Editor, Roo.Component, {
8765     /**
8766      * @cfg {Boolean/String} autosize
8767      * True for the editor to automatically adopt the size of the underlying field, "width" to adopt the width only,
8768      * or "height" to adopt the height only (defaults to false)
8769      */
8770     /**
8771      * @cfg {Boolean} revertInvalid
8772      * True to automatically revert the field value and cancel the edit when the user completes an edit and the field
8773      * validation fails (defaults to true)
8774      */
8775     /**
8776      * @cfg {Boolean} ignoreNoChange
8777      * True to skip the the edit completion process (no save, no events fired) if the user completes an edit and
8778      * the value has not changed (defaults to false).  Applies only to string values - edits for other data types
8779      * will never be ignored.
8780      */
8781     /**
8782      * @cfg {Boolean} hideEl
8783      * False to keep the bound element visible while the editor is displayed (defaults to true)
8784      */
8785     /**
8786      * @cfg {Mixed} value
8787      * The data value of the underlying field (defaults to "")
8788      */
8789     value : "",
8790     /**
8791      * @cfg {String} alignment
8792      * The position to align to (see {@link Roo.Element#alignTo} for more details, defaults to "c-c?").
8793      */
8794     alignment: "c-c?",
8795     /**
8796      * @cfg {Boolean/String} shadow "sides" for sides/bottom only, "frame" for 4-way shadow, and "drop"
8797      * for bottom-right shadow (defaults to "frame")
8798      */
8799     shadow : "frame",
8800     /**
8801      * @cfg {Boolean} constrain True to constrain the editor to the viewport
8802      */
8803     constrain : false,
8804     /**
8805      * @cfg {Boolean} completeOnEnter True to complete the edit when the enter key is pressed (defaults to false)
8806      */
8807     completeOnEnter : false,
8808     /**
8809      * @cfg {Boolean} cancelOnEsc True to cancel the edit when the escape key is pressed (defaults to false)
8810      */
8811     cancelOnEsc : false,
8812     /**
8813      * @cfg {Boolean} updateEl True to update the innerHTML of the bound element when the update completes (defaults to false)
8814      */
8815     updateEl : false,
8816
8817     // private
8818     onRender : function(ct, position){
8819         this.el = new Roo.Layer({
8820             shadow: this.shadow,
8821             cls: "x-editor",
8822             parentEl : ct,
8823             shim : this.shim,
8824             shadowOffset:4,
8825             id: this.id,
8826             constrain: this.constrain
8827         });
8828         this.el.setStyle("overflow", Roo.isGecko ? "auto" : "hidden");
8829         if(this.field.msgTarget != 'title'){
8830             this.field.msgTarget = 'qtip';
8831         }
8832         this.field.render(this.el);
8833         if(Roo.isGecko){
8834             this.field.el.dom.setAttribute('autocomplete', 'off');
8835         }
8836         this.field.on("specialkey", this.onSpecialKey, this);
8837         if(this.swallowKeys){
8838             this.field.el.swallowEvent(['keydown','keypress']);
8839         }
8840         this.field.show();
8841         this.field.on("blur", this.onBlur, this);
8842         if(this.field.grow){
8843             this.field.on("autosize", this.el.sync,  this.el, {delay:1});
8844         }
8845     },
8846
8847     onSpecialKey : function(field, e)
8848     {
8849         //Roo.log('editor onSpecialKey');
8850         if(this.completeOnEnter && e.getKey() == e.ENTER){
8851             e.stopEvent();
8852             this.completeEdit();
8853             return;
8854         }
8855         // do not fire special key otherwise it might hide close the editor...
8856         if(e.getKey() == e.ENTER){    
8857             return;
8858         }
8859         if(this.cancelOnEsc && e.getKey() == e.ESC){
8860             this.cancelEdit();
8861             return;
8862         } 
8863         this.fireEvent('specialkey', field, e);
8864     
8865     },
8866
8867     /**
8868      * Starts the editing process and shows the editor.
8869      * @param {String/HTMLElement/Element} el The element to edit
8870      * @param {String} value (optional) A value to initialize the editor with. If a value is not provided, it defaults
8871       * to the innerHTML of el.
8872      */
8873     startEdit : function(el, value){
8874         if(this.editing){
8875             this.completeEdit();
8876         }
8877         this.boundEl = Roo.get(el);
8878         var v = value !== undefined ? value : this.boundEl.dom.innerHTML;
8879         if(!this.rendered){
8880             this.render(this.parentEl || document.body);
8881         }
8882         if(this.fireEvent("beforestartedit", this, this.boundEl, v) === false){
8883             return;
8884         }
8885         this.startValue = v;
8886         this.field.setValue(v);
8887         if(this.autoSize){
8888             var sz = this.boundEl.getSize();
8889             switch(this.autoSize){
8890                 case "width":
8891                 this.setSize(sz.width,  "");
8892                 break;
8893                 case "height":
8894                 this.setSize("",  sz.height);
8895                 break;
8896                 default:
8897                 this.setSize(sz.width,  sz.height);
8898             }
8899         }
8900         this.el.alignTo(this.boundEl, this.alignment);
8901         this.editing = true;
8902         if(Roo.QuickTips){
8903             Roo.QuickTips.disable();
8904         }
8905         this.show();
8906     },
8907
8908     /**
8909      * Sets the height and width of this editor.
8910      * @param {Number} width The new width
8911      * @param {Number} height The new height
8912      */
8913     setSize : function(w, h){
8914         this.field.setSize(w, h);
8915         if(this.el){
8916             this.el.sync();
8917         }
8918     },
8919
8920     /**
8921      * Realigns the editor to the bound field based on the current alignment config value.
8922      */
8923     realign : function(){
8924         this.el.alignTo(this.boundEl, this.alignment);
8925     },
8926
8927     /**
8928      * Ends the editing process, persists the changed value to the underlying field, and hides the editor.
8929      * @param {Boolean} remainVisible Override the default behavior and keep the editor visible after edit (defaults to false)
8930      */
8931     completeEdit : function(remainVisible){
8932         if(!this.editing){
8933             return;
8934         }
8935         var v = this.getValue();
8936         if(this.revertInvalid !== false && !this.field.isValid()){
8937             v = this.startValue;
8938             this.cancelEdit(true);
8939         }
8940         if(String(v) === String(this.startValue) && this.ignoreNoChange){
8941             this.editing = false;
8942             this.hide();
8943             return;
8944         }
8945         if(this.fireEvent("beforecomplete", this, v, this.startValue) !== false){
8946             this.editing = false;
8947             if(this.updateEl && this.boundEl){
8948                 this.boundEl.update(v);
8949             }
8950             if(remainVisible !== true){
8951                 this.hide();
8952             }
8953             this.fireEvent("complete", this, v, this.startValue);
8954         }
8955     },
8956
8957     // private
8958     onShow : function(){
8959         this.el.show();
8960         if(this.hideEl !== false){
8961             this.boundEl.hide();
8962         }
8963         this.field.show();
8964         if(Roo.isIE && !this.fixIEFocus){ // IE has problems with focusing the first time
8965             this.fixIEFocus = true;
8966             this.deferredFocus.defer(50, this);
8967         }else{
8968             this.field.focus();
8969         }
8970         this.fireEvent("startedit", this.boundEl, this.startValue);
8971     },
8972
8973     deferredFocus : function(){
8974         if(this.editing){
8975             this.field.focus();
8976         }
8977     },
8978
8979     /**
8980      * Cancels the editing process and hides the editor without persisting any changes.  The field value will be
8981      * reverted to the original starting value.
8982      * @param {Boolean} remainVisible Override the default behavior and keep the editor visible after
8983      * cancel (defaults to false)
8984      */
8985     cancelEdit : function(remainVisible){
8986         if(this.editing){
8987             this.setValue(this.startValue);
8988             if(remainVisible !== true){
8989                 this.hide();
8990             }
8991         }
8992     },
8993
8994     // private
8995     onBlur : function(){
8996         if(this.allowBlur !== true && this.editing){
8997             this.completeEdit();
8998         }
8999     },
9000
9001     // private
9002     onHide : function(){
9003         if(this.editing){
9004             this.completeEdit();
9005             return;
9006         }
9007         this.field.blur();
9008         if(this.field.collapse){
9009             this.field.collapse();
9010         }
9011         this.el.hide();
9012         if(this.hideEl !== false){
9013             this.boundEl.show();
9014         }
9015         if(Roo.QuickTips){
9016             Roo.QuickTips.enable();
9017         }
9018     },
9019
9020     /**
9021      * Sets the data value of the editor
9022      * @param {Mixed} value Any valid value supported by the underlying field
9023      */
9024     setValue : function(v){
9025         this.field.setValue(v);
9026     },
9027
9028     /**
9029      * Gets the data value of the editor
9030      * @return {Mixed} The data value
9031      */
9032     getValue : function(){
9033         return this.field.getValue();
9034     }
9035 });/*
9036  * Based on:
9037  * Ext JS Library 1.1.1
9038  * Copyright(c) 2006-2007, Ext JS, LLC.
9039  *
9040  * Originally Released Under LGPL - original licence link has changed is not relivant.
9041  *
9042  * Fork - LGPL
9043  * <script type="text/javascript">
9044  */
9045  
9046 /**
9047  * @class Roo.BasicDialog
9048  * @extends Roo.util.Observable
9049  * @parent none builder
9050  * Lightweight Dialog Class.  The code below shows the creation of a typical dialog using existing HTML markup:
9051  * <pre><code>
9052 var dlg = new Roo.BasicDialog("my-dlg", {
9053     height: 200,
9054     width: 300,
9055     minHeight: 100,
9056     minWidth: 150,
9057     modal: true,
9058     proxyDrag: true,
9059     shadow: true
9060 });
9061 dlg.addKeyListener(27, dlg.hide, dlg); // ESC can also close the dialog
9062 dlg.addButton('OK', dlg.hide, dlg);    // Could call a save function instead of hiding
9063 dlg.addButton('Cancel', dlg.hide, dlg);
9064 dlg.show();
9065 </code></pre>
9066   <b>A Dialog should always be a direct child of the body element.</b>
9067  * @cfg {Boolean/DomHelper} autoCreate True to auto create from scratch, or using a DomHelper Object (defaults to false)
9068  * @cfg {String} title Default text to display in the title bar (defaults to null)
9069  * @cfg {Number} width Width of the dialog in pixels (can also be set via CSS).  Determined by browser if unspecified.
9070  * @cfg {Number} height Height of the dialog in pixels (can also be set via CSS).  Determined by browser if unspecified.
9071  * @cfg {Number} x The default left page coordinate of the dialog (defaults to center screen)
9072  * @cfg {Number} y The default top page coordinate of the dialog (defaults to center screen)
9073  * @cfg {String/Element} animateTarget Id or element from which the dialog should animate while opening
9074  * (defaults to null with no animation)
9075  * @cfg {Boolean} resizable False to disable manual dialog resizing (defaults to true)
9076  * @cfg {String} resizeHandles Which resize handles to display - see the {@link Roo.Resizable} handles config
9077  * property for valid values (defaults to 'all')
9078  * @cfg {Number} minHeight The minimum allowable height for a resizable dialog (defaults to 80)
9079  * @cfg {Number} minWidth The minimum allowable width for a resizable dialog (defaults to 200)
9080  * @cfg {Boolean} modal True to show the dialog modally, preventing user interaction with the rest of the page (defaults to false)
9081  * @cfg {Boolean} autoScroll True to allow the dialog body contents to overflow and display scrollbars (defaults to false)
9082  * @cfg {Boolean} closable False to remove the built-in top-right corner close button (defaults to true)
9083  * @cfg {Boolean} collapsible False to remove the built-in top-right corner collapse button (defaults to true)
9084  * @cfg {Boolean} constraintoviewport True to keep the dialog constrained within the visible viewport boundaries (defaults to true)
9085  * @cfg {Boolean} syncHeightBeforeShow True to cause the dimensions to be recalculated before the dialog is shown (defaults to false)
9086  * @cfg {Boolean} draggable False to disable dragging of the dialog within the viewport (defaults to true)
9087  * @cfg {Boolean} autoTabs If true, all elements with class 'x-dlg-tab' will get automatically converted to tabs (defaults to false)
9088  * @cfg {String} tabTag The tag name of tab elements, used when autoTabs = true (defaults to 'div')
9089  * @cfg {Boolean} proxyDrag True to drag a lightweight proxy element rather than the dialog itself, used when
9090  * draggable = true (defaults to false)
9091  * @cfg {Boolean} fixedcenter True to ensure that anytime the dialog is shown or resized it gets centered (defaults to false)
9092  * @cfg {Boolean/String} shadow True or "sides" for the default effect, "frame" for 4-way shadow, and "drop" for bottom-right
9093  * shadow (defaults to false)
9094  * @cfg {Number} shadowOffset The number of pixels to offset the shadow if displayed (defaults to 5)
9095  * @cfg {String} buttonAlign Valid values are "left," "center" and "right" (defaults to "right")
9096  * @cfg {Number} minButtonWidth Minimum width of all dialog buttons (defaults to 75)
9097  * @cfg {Array} buttons Array of buttons
9098  * @cfg {Boolean} shim True to create an iframe shim that prevents selects from showing through (defaults to false)
9099  * @constructor
9100  * Create a new BasicDialog.
9101  * @param {String/HTMLElement/Roo.Element} el The container element or DOM node, or its id
9102  * @param {Object} config Configuration options
9103  */
9104 Roo.BasicDialog = function(el, config){
9105     this.el = Roo.get(el);
9106     var dh = Roo.DomHelper;
9107     if(!this.el && config && config.autoCreate){
9108         if(typeof config.autoCreate == "object"){
9109             if(!config.autoCreate.id){
9110                 config.autoCreate.id = el;
9111             }
9112             this.el = dh.append(document.body,
9113                         config.autoCreate, true);
9114         }else{
9115             this.el = dh.append(document.body,
9116                         {tag: "div", id: el, style:'visibility:hidden;'}, true);
9117         }
9118     }
9119     el = this.el;
9120     el.setDisplayed(true);
9121     el.hide = this.hideAction;
9122     this.id = el.id;
9123     el.addClass("x-dlg");
9124
9125     Roo.apply(this, config);
9126
9127     this.proxy = el.createProxy("x-dlg-proxy");
9128     this.proxy.hide = this.hideAction;
9129     this.proxy.setOpacity(.5);
9130     this.proxy.hide();
9131
9132     if(config.width){
9133         el.setWidth(config.width);
9134     }
9135     if(config.height){
9136         el.setHeight(config.height);
9137     }
9138     this.size = el.getSize();
9139     if(typeof config.x != "undefined" && typeof config.y != "undefined"){
9140         this.xy = [config.x,config.y];
9141     }else{
9142         this.xy = el.getCenterXY(true);
9143     }
9144     /** The header element @type Roo.Element */
9145     this.header = el.child("> .x-dlg-hd");
9146     /** The body element @type Roo.Element */
9147     this.body = el.child("> .x-dlg-bd");
9148     /** The footer element @type Roo.Element */
9149     this.footer = el.child("> .x-dlg-ft");
9150
9151     if(!this.header){
9152         this.header = el.createChild({tag: "div", cls:"x-dlg-hd", html: "&#160;"}, this.body ? this.body.dom : null);
9153     }
9154     if(!this.body){
9155         this.body = el.createChild({tag: "div", cls:"x-dlg-bd"});
9156     }
9157
9158     this.header.unselectable();
9159     if(this.title){
9160         this.header.update(this.title);
9161     }
9162     // this element allows the dialog to be focused for keyboard event
9163     this.focusEl = el.createChild({tag: "a", href:"#", cls:"x-dlg-focus", tabIndex:"-1"});
9164     this.focusEl.swallowEvent("click", true);
9165
9166     this.header.wrap({cls:"x-dlg-hd-right"}).wrap({cls:"x-dlg-hd-left"}, true);
9167
9168     // wrap the body and footer for special rendering
9169     this.bwrap = this.body.wrap({tag: "div", cls:"x-dlg-dlg-body"});
9170     if(this.footer){
9171         this.bwrap.dom.appendChild(this.footer.dom);
9172     }
9173
9174     this.bg = this.el.createChild({
9175         tag: "div", cls:"x-dlg-bg",
9176         html: '<div class="x-dlg-bg-left"><div class="x-dlg-bg-right"><div class="x-dlg-bg-center">&#160;</div></div></div>'
9177     });
9178     this.centerBg = this.bg.child("div.x-dlg-bg-center");
9179
9180
9181     if(this.autoScroll !== false && !this.autoTabs){
9182         this.body.setStyle("overflow", "auto");
9183     }
9184
9185     this.toolbox = this.el.createChild({cls: "x-dlg-toolbox"});
9186
9187     if(this.closable !== false){
9188         this.el.addClass("x-dlg-closable");
9189         this.close = this.toolbox.createChild({cls:"x-dlg-close"});
9190         this.close.on("click", this.closeClick, this);
9191         this.close.addClassOnOver("x-dlg-close-over");
9192     }
9193     if(this.collapsible !== false){
9194         this.collapseBtn = this.toolbox.createChild({cls:"x-dlg-collapse"});
9195         this.collapseBtn.on("click", this.collapseClick, this);
9196         this.collapseBtn.addClassOnOver("x-dlg-collapse-over");
9197         this.header.on("dblclick", this.collapseClick, this);
9198     }
9199     if(this.resizable !== false){
9200         this.el.addClass("x-dlg-resizable");
9201         this.resizer = new Roo.Resizable(el, {
9202             minWidth: this.minWidth || 80,
9203             minHeight:this.minHeight || 80,
9204             handles: this.resizeHandles || "all",
9205             pinned: true
9206         });
9207         this.resizer.on("beforeresize", this.beforeResize, this);
9208         this.resizer.on("resize", this.onResize, this);
9209     }
9210     if(this.draggable !== false){
9211         el.addClass("x-dlg-draggable");
9212         if (!this.proxyDrag) {
9213             var dd = new Roo.dd.DD(el.dom.id, "WindowDrag");
9214         }
9215         else {
9216             var dd = new Roo.dd.DDProxy(el.dom.id, "WindowDrag", {dragElId: this.proxy.id});
9217         }
9218         dd.setHandleElId(this.header.id);
9219         dd.endDrag = this.endMove.createDelegate(this);
9220         dd.startDrag = this.startMove.createDelegate(this);
9221         dd.onDrag = this.onDrag.createDelegate(this);
9222         dd.scroll = false;
9223         this.dd = dd;
9224     }
9225     if(this.modal){
9226         this.mask = dh.append(document.body, {tag: "div", cls:"x-dlg-mask"}, true);
9227         this.mask.enableDisplayMode("block");
9228         this.mask.hide();
9229         this.el.addClass("x-dlg-modal");
9230     }
9231     if(this.shadow){
9232         this.shadow = new Roo.Shadow({
9233             mode : typeof this.shadow == "string" ? this.shadow : "sides",
9234             offset : this.shadowOffset
9235         });
9236     }else{
9237         this.shadowOffset = 0;
9238     }
9239     if(Roo.useShims && this.shim !== false){
9240         this.shim = this.el.createShim();
9241         this.shim.hide = this.hideAction;
9242         this.shim.hide();
9243     }else{
9244         this.shim = false;
9245     }
9246     if(this.autoTabs){
9247         this.initTabs();
9248     }
9249     if (this.buttons) { 
9250         var bts= this.buttons;
9251         this.buttons = [];
9252         Roo.each(bts, function(b) {
9253             this.addButton(b);
9254         }, this);
9255     }
9256     
9257     
9258     this.addEvents({
9259         /**
9260          * @event keydown
9261          * Fires when a key is pressed
9262          * @param {Roo.BasicDialog} this
9263          * @param {Roo.EventObject} e
9264          */
9265         "keydown" : true,
9266         /**
9267          * @event move
9268          * Fires when this dialog is moved by the user.
9269          * @param {Roo.BasicDialog} this
9270          * @param {Number} x The new page X
9271          * @param {Number} y The new page Y
9272          */
9273         "move" : true,
9274         /**
9275          * @event resize
9276          * Fires when this dialog is resized by the user.
9277          * @param {Roo.BasicDialog} this
9278          * @param {Number} width The new width
9279          * @param {Number} height The new height
9280          */
9281         "resize" : true,
9282         /**
9283          * @event beforehide
9284          * Fires before this dialog is hidden.
9285          * @param {Roo.BasicDialog} this
9286          */
9287         "beforehide" : true,
9288         /**
9289          * @event hide
9290          * Fires when this dialog is hidden.
9291          * @param {Roo.BasicDialog} this
9292          */
9293         "hide" : true,
9294         /**
9295          * @event beforeshow
9296          * Fires before this dialog is shown.
9297          * @param {Roo.BasicDialog} this
9298          */
9299         "beforeshow" : true,
9300         /**
9301          * @event show
9302          * Fires when this dialog is shown.
9303          * @param {Roo.BasicDialog} this
9304          */
9305         "show" : true
9306     });
9307     el.on("keydown", this.onKeyDown, this);
9308     el.on("mousedown", this.toFront, this);
9309     Roo.EventManager.onWindowResize(this.adjustViewport, this, true);
9310     this.el.hide();
9311     Roo.DialogManager.register(this);
9312     Roo.BasicDialog.superclass.constructor.call(this);
9313 };
9314
9315 Roo.extend(Roo.BasicDialog, Roo.util.Observable, {
9316     shadowOffset: Roo.isIE ? 6 : 5,
9317     minHeight: 80,
9318     minWidth: 200,
9319     minButtonWidth: 75,
9320     defaultButton: null,
9321     buttonAlign: "right",
9322     tabTag: 'div',
9323     firstShow: true,
9324
9325     /**
9326      * Sets the dialog title text
9327      * @param {String} text The title text to display
9328      * @return {Roo.BasicDialog} this
9329      */
9330     setTitle : function(text){
9331         this.header.update(text);
9332         return this;
9333     },
9334
9335     // private
9336     closeClick : function(){
9337         this.hide();
9338     },
9339
9340     // private
9341     collapseClick : function(){
9342         this[this.collapsed ? "expand" : "collapse"]();
9343     },
9344
9345     /**
9346      * Collapses the dialog to its minimized state (only the title bar is visible).
9347      * Equivalent to the user clicking the collapse dialog button.
9348      */
9349     collapse : function(){
9350         if(!this.collapsed){
9351             this.collapsed = true;
9352             this.el.addClass("x-dlg-collapsed");
9353             this.restoreHeight = this.el.getHeight();
9354             this.resizeTo(this.el.getWidth(), this.header.getHeight());
9355         }
9356     },
9357
9358     /**
9359      * Expands a collapsed dialog back to its normal state.  Equivalent to the user
9360      * clicking the expand dialog button.
9361      */
9362     expand : function(){
9363         if(this.collapsed){
9364             this.collapsed = false;
9365             this.el.removeClass("x-dlg-collapsed");
9366             this.resizeTo(this.el.getWidth(), this.restoreHeight);
9367         }
9368     },
9369
9370     /**
9371      * Reinitializes the tabs component, clearing out old tabs and finding new ones.
9372      * @return {Roo.TabPanel} The tabs component
9373      */
9374     initTabs : function(){
9375         var tabs = this.getTabs();
9376         while(tabs.getTab(0)){
9377             tabs.removeTab(0);
9378         }
9379         this.el.select(this.tabTag+'.x-dlg-tab').each(function(el){
9380             var dom = el.dom;
9381             tabs.addTab(Roo.id(dom), dom.title);
9382             dom.title = "";
9383         });
9384         tabs.activate(0);
9385         return tabs;
9386     },
9387
9388     // private
9389     beforeResize : function(){
9390         this.resizer.minHeight = Math.max(this.minHeight, this.getHeaderFooterHeight(true)+40);
9391     },
9392
9393     // private
9394     onResize : function(){
9395         this.refreshSize();
9396         this.syncBodyHeight();
9397         this.adjustAssets();
9398         this.focus();
9399         this.fireEvent("resize", this, this.size.width, this.size.height);
9400     },
9401
9402     // private
9403     onKeyDown : function(e){
9404         if(this.isVisible()){
9405             this.fireEvent("keydown", this, e);
9406         }
9407     },
9408
9409     /**
9410      * Resizes the dialog.
9411      * @param {Number} width
9412      * @param {Number} height
9413      * @return {Roo.BasicDialog} this
9414      */
9415     resizeTo : function(width, height){
9416         this.el.setSize(width, height);
9417         this.size = {width: width, height: height};
9418         this.syncBodyHeight();
9419         if(this.fixedcenter){
9420             this.center();
9421         }
9422         if(this.isVisible()){
9423             this.constrainXY();
9424             this.adjustAssets();
9425         }
9426         this.fireEvent("resize", this, width, height);
9427         return this;
9428     },
9429
9430
9431     /**
9432      * Resizes the dialog to fit the specified content size.
9433      * @param {Number} width
9434      * @param {Number} height
9435      * @return {Roo.BasicDialog} this
9436      */
9437     setContentSize : function(w, h){
9438         h += this.getHeaderFooterHeight() + this.body.getMargins("tb");
9439         w += this.body.getMargins("lr") + this.bwrap.getMargins("lr") + this.centerBg.getPadding("lr");
9440         //if(!this.el.isBorderBox()){
9441             h +=  this.body.getPadding("tb") + this.bwrap.getBorderWidth("tb") + this.body.getBorderWidth("tb") + this.el.getBorderWidth("tb");
9442             w += this.body.getPadding("lr") + this.bwrap.getBorderWidth("lr") + this.body.getBorderWidth("lr") + this.bwrap.getPadding("lr") + this.el.getBorderWidth("lr");
9443         //}
9444         if(this.tabs){
9445             h += this.tabs.stripWrap.getHeight() + this.tabs.bodyEl.getMargins("tb") + this.tabs.bodyEl.getPadding("tb");
9446             w += this.tabs.bodyEl.getMargins("lr") + this.tabs.bodyEl.getPadding("lr");
9447         }
9448         this.resizeTo(w, h);
9449         return this;
9450     },
9451
9452     /**
9453      * Adds a key listener for when this dialog is displayed.  This allows you to hook in a function that will be
9454      * executed in response to a particular key being pressed while the dialog is active.
9455      * @param {Number/Array/Object} key Either the numeric key code, array of key codes or an object with the following options:
9456      *                                  {key: (number or array), shift: (true/false), ctrl: (true/false), alt: (true/false)}
9457      * @param {Function} fn The function to call
9458      * @param {Object} scope (optional) The scope of the function
9459      * @return {Roo.BasicDialog} this
9460      */
9461     addKeyListener : function(key, fn, scope){
9462         var keyCode, shift, ctrl, alt;
9463         if(typeof key == "object" && !(key instanceof Array)){
9464             keyCode = key["key"];
9465             shift = key["shift"];
9466             ctrl = key["ctrl"];
9467             alt = key["alt"];
9468         }else{
9469             keyCode = key;
9470         }
9471         var handler = function(dlg, e){
9472             if((!shift || e.shiftKey) && (!ctrl || e.ctrlKey) &&  (!alt || e.altKey)){
9473                 var k = e.getKey();
9474                 if(keyCode instanceof Array){
9475                     for(var i = 0, len = keyCode.length; i < len; i++){
9476                         if(keyCode[i] == k){
9477                           fn.call(scope || window, dlg, k, e);
9478                           return;
9479                         }
9480                     }
9481                 }else{
9482                     if(k == keyCode){
9483                         fn.call(scope || window, dlg, k, e);
9484                     }
9485                 }
9486             }
9487         };
9488         this.on("keydown", handler);
9489         return this;
9490     },
9491
9492     /**
9493      * Returns the TabPanel component (creates it if it doesn't exist).
9494      * Note: If you wish to simply check for the existence of tabs without creating them,
9495      * check for a null 'tabs' property.
9496      * @return {Roo.TabPanel} The tabs component
9497      */
9498     getTabs : function(){
9499         if(!this.tabs){
9500             this.el.addClass("x-dlg-auto-tabs");
9501             this.body.addClass(this.tabPosition == "bottom" ? "x-tabs-bottom" : "x-tabs-top");
9502             this.tabs = new Roo.TabPanel(this.body.dom, this.tabPosition == "bottom");
9503         }
9504         return this.tabs;
9505     },
9506
9507     /**
9508      * Adds a button to the footer section of the dialog.
9509      * @param {String/Object} config A string becomes the button text, an object can either be a Button config
9510      * object or a valid Roo.DomHelper element config
9511      * @param {Function} handler The function called when the button is clicked
9512      * @param {Object} scope (optional) The scope of the handler function (accepts position as a property)
9513      * @return {Roo.Button} The new button
9514      */
9515     addButton : function(config, handler, scope){
9516         var dh = Roo.DomHelper;
9517         if(!this.footer){
9518             this.footer = dh.append(this.bwrap, {tag: "div", cls:"x-dlg-ft"}, true);
9519         }
9520         if(!this.btnContainer){
9521             var tb = this.footer.createChild({
9522
9523                 cls:"x-dlg-btns x-dlg-btns-"+this.buttonAlign,
9524                 html:'<table cellspacing="0"><tbody><tr></tr></tbody></table><div class="x-clear"></div>'
9525             }, null, true);
9526             this.btnContainer = tb.firstChild.firstChild.firstChild;
9527         }
9528         var bconfig = {
9529             handler: handler,
9530             scope: scope,
9531             minWidth: this.minButtonWidth,
9532             hideParent:true
9533         };
9534         if(typeof config == "string"){
9535             bconfig.text = config;
9536         }else{
9537             if(config.tag){
9538                 bconfig.dhconfig = config;
9539             }else{
9540                 Roo.apply(bconfig, config);
9541             }
9542         }
9543         var fc = false;
9544         if ((typeof(bconfig.position) != 'undefined') && bconfig.position < this.btnContainer.childNodes.length-1) {
9545             bconfig.position = Math.max(0, bconfig.position);
9546             fc = this.btnContainer.childNodes[bconfig.position];
9547         }
9548          
9549         var btn = new Roo.Button(
9550             fc ? 
9551                 this.btnContainer.insertBefore(document.createElement("td"),fc)
9552                 : this.btnContainer.appendChild(document.createElement("td")),
9553             //Roo.get(this.btnContainer).createChild( { tag: 'td'},  fc ),
9554             bconfig
9555         );
9556         this.syncBodyHeight();
9557         if(!this.buttons){
9558             /**
9559              * Array of all the buttons that have been added to this dialog via addButton
9560              * @type Array
9561              */
9562             this.buttons = [];
9563         }
9564         this.buttons.push(btn);
9565         return btn;
9566     },
9567
9568     /**
9569      * Sets the default button to be focused when the dialog is displayed.
9570      * @param {Roo.BasicDialog.Button} btn The button object returned by {@link #addButton}
9571      * @return {Roo.BasicDialog} this
9572      */
9573     setDefaultButton : function(btn){
9574         this.defaultButton = btn;
9575         return this;
9576     },
9577
9578     // private
9579     getHeaderFooterHeight : function(safe){
9580         var height = 0;
9581         if(this.header){
9582            height += this.header.getHeight();
9583         }
9584         if(this.footer){
9585            var fm = this.footer.getMargins();
9586             height += (this.footer.getHeight()+fm.top+fm.bottom);
9587         }
9588         height += this.bwrap.getPadding("tb")+this.bwrap.getBorderWidth("tb");
9589         height += this.centerBg.getPadding("tb");
9590         return height;
9591     },
9592
9593     // private
9594     syncBodyHeight : function()
9595     {
9596         var bd = this.body, // the text
9597             cb = this.centerBg, // wrapper around bottom.. but does not seem to be used..
9598             bw = this.bwrap;
9599         var height = this.size.height - this.getHeaderFooterHeight(false);
9600         bd.setHeight(height-bd.getMargins("tb"));
9601         var hh = this.header.getHeight();
9602         var h = this.size.height-hh;
9603         cb.setHeight(h);
9604         
9605         bw.setLeftTop(cb.getPadding("l"), hh+cb.getPadding("t"));
9606         bw.setHeight(h-cb.getPadding("tb"));
9607         
9608         bw.setWidth(this.el.getWidth(true)-cb.getPadding("lr"));
9609         bd.setWidth(bw.getWidth(true));
9610         if(this.tabs){
9611             this.tabs.syncHeight();
9612             if(Roo.isIE){
9613                 this.tabs.el.repaint();
9614             }
9615         }
9616     },
9617
9618     /**
9619      * Restores the previous state of the dialog if Roo.state is configured.
9620      * @return {Roo.BasicDialog} this
9621      */
9622     restoreState : function(){
9623         var box = Roo.state.Manager.get(this.stateId || (this.el.id + "-state"));
9624         if(box && box.width){
9625             this.xy = [box.x, box.y];
9626             this.resizeTo(box.width, box.height);
9627         }
9628         return this;
9629     },
9630
9631     // private
9632     beforeShow : function(){
9633         this.expand();
9634         if(this.fixedcenter){
9635             this.xy = this.el.getCenterXY(true);
9636         }
9637         if(this.modal){
9638             Roo.get(document.body).addClass("x-body-masked");
9639             this.mask.setSize(Roo.lib.Dom.getViewWidth(true), Roo.lib.Dom.getViewHeight(true));
9640             this.mask.show();
9641         }
9642         this.constrainXY();
9643     },
9644
9645     // private
9646     animShow : function(){
9647         var b = Roo.get(this.animateTarget).getBox();
9648         this.proxy.setSize(b.width, b.height);
9649         this.proxy.setLocation(b.x, b.y);
9650         this.proxy.show();
9651         this.proxy.setBounds(this.xy[0], this.xy[1], this.size.width, this.size.height,
9652                     true, .35, this.showEl.createDelegate(this));
9653     },
9654
9655     /**
9656      * Shows the dialog.
9657      * @param {String/HTMLElement/Roo.Element} animateTarget (optional) Reset the animation target
9658      * @return {Roo.BasicDialog} this
9659      */
9660     show : function(animateTarget){
9661         if (this.fireEvent("beforeshow", this) === false){
9662             return;
9663         }
9664         if(this.syncHeightBeforeShow){
9665             this.syncBodyHeight();
9666         }else if(this.firstShow){
9667             this.firstShow = false;
9668             this.syncBodyHeight(); // sync the height on the first show instead of in the constructor
9669         }
9670         this.animateTarget = animateTarget || this.animateTarget;
9671         if(!this.el.isVisible()){
9672             this.beforeShow();
9673             if(this.animateTarget && Roo.get(this.animateTarget)){
9674                 this.animShow();
9675             }else{
9676                 this.showEl();
9677             }
9678         }
9679         return this;
9680     },
9681
9682     // private
9683     showEl : function(){
9684         this.proxy.hide();
9685         this.el.setXY(this.xy);
9686         this.el.show();
9687         this.adjustAssets(true);
9688         this.toFront();
9689         this.focus();
9690         // IE peekaboo bug - fix found by Dave Fenwick
9691         if(Roo.isIE){
9692             this.el.repaint();
9693         }
9694         this.fireEvent("show", this);
9695     },
9696
9697     /**
9698      * Focuses the dialog.  If a defaultButton is set, it will receive focus, otherwise the
9699      * dialog itself will receive focus.
9700      */
9701     focus : function(){
9702         if(this.defaultButton){
9703             this.defaultButton.focus();
9704         }else{
9705             this.focusEl.focus();
9706         }
9707     },
9708
9709     // private
9710     constrainXY : function(){
9711         if(this.constraintoviewport !== false){
9712             if(!this.viewSize){
9713                 if(this.container){
9714                     var s = this.container.getSize();
9715                     this.viewSize = [s.width, s.height];
9716                 }else{
9717                     this.viewSize = [Roo.lib.Dom.getViewWidth(),Roo.lib.Dom.getViewHeight()];
9718                 }
9719             }
9720             var s = Roo.get(this.container||document).getScroll();
9721
9722             var x = this.xy[0], y = this.xy[1];
9723             var w = this.size.width, h = this.size.height;
9724             var vw = this.viewSize[0], vh = this.viewSize[1];
9725             // only move it if it needs it
9726             var moved = false;
9727             // first validate right/bottom
9728             if(x + w > vw+s.left){
9729                 x = vw - w;
9730                 moved = true;
9731             }
9732             if(y + h > vh+s.top){
9733                 y = vh - h;
9734                 moved = true;
9735             }
9736             // then make sure top/left isn't negative
9737             if(x < s.left){
9738                 x = s.left;
9739                 moved = true;
9740             }
9741             if(y < s.top){
9742                 y = s.top;
9743                 moved = true;
9744             }
9745             if(moved){
9746                 // cache xy
9747                 this.xy = [x, y];
9748                 if(this.isVisible()){
9749                     this.el.setLocation(x, y);
9750                     this.adjustAssets();
9751                 }
9752             }
9753         }
9754     },
9755
9756     // private
9757     onDrag : function(){
9758         if(!this.proxyDrag){
9759             this.xy = this.el.getXY();
9760             this.adjustAssets();
9761         }
9762     },
9763
9764     // private
9765     adjustAssets : function(doShow){
9766         var x = this.xy[0], y = this.xy[1];
9767         var w = this.size.width, h = this.size.height;
9768         if(doShow === true){
9769             if(this.shadow){
9770                 this.shadow.show(this.el);
9771             }
9772             if(this.shim){
9773                 this.shim.show();
9774             }
9775         }
9776         if(this.shadow && this.shadow.isVisible()){
9777             this.shadow.show(this.el);
9778         }
9779         if(this.shim && this.shim.isVisible()){
9780             this.shim.setBounds(x, y, w, h);
9781         }
9782     },
9783
9784     // private
9785     adjustViewport : function(w, h){
9786         if(!w || !h){
9787             w = Roo.lib.Dom.getViewWidth();
9788             h = Roo.lib.Dom.getViewHeight();
9789         }
9790         // cache the size
9791         this.viewSize = [w, h];
9792         if(this.modal && this.mask.isVisible()){
9793             this.mask.setSize(w, h); // first make sure the mask isn't causing overflow
9794             this.mask.setSize(Roo.lib.Dom.getViewWidth(true), Roo.lib.Dom.getViewHeight(true));
9795         }
9796         if(this.isVisible()){
9797             this.constrainXY();
9798         }
9799     },
9800
9801     /**
9802      * Destroys this dialog and all its supporting elements (including any tabs, shim,
9803      * shadow, proxy, mask, etc.)  Also removes all event listeners.
9804      * @param {Boolean} removeEl (optional) true to remove the element from the DOM
9805      */
9806     destroy : function(removeEl){
9807         if(this.isVisible()){
9808             this.animateTarget = null;
9809             this.hide();
9810         }
9811         Roo.EventManager.removeResizeListener(this.adjustViewport, this);
9812         if(this.tabs){
9813             this.tabs.destroy(removeEl);
9814         }
9815         Roo.destroy(
9816              this.shim,
9817              this.proxy,
9818              this.resizer,
9819              this.close,
9820              this.mask
9821         );
9822         if(this.dd){
9823             this.dd.unreg();
9824         }
9825         if(this.buttons){
9826            for(var i = 0, len = this.buttons.length; i < len; i++){
9827                this.buttons[i].destroy();
9828            }
9829         }
9830         this.el.removeAllListeners();
9831         if(removeEl === true){
9832             this.el.update("");
9833             this.el.remove();
9834         }
9835         Roo.DialogManager.unregister(this);
9836     },
9837
9838     // private
9839     startMove : function(){
9840         if(this.proxyDrag){
9841             this.proxy.show();
9842         }
9843         if(this.constraintoviewport !== false){
9844             this.dd.constrainTo(document.body, {right: this.shadowOffset, bottom: this.shadowOffset});
9845         }
9846     },
9847
9848     // private
9849     endMove : function(){
9850         if(!this.proxyDrag){
9851             Roo.dd.DD.prototype.endDrag.apply(this.dd, arguments);
9852         }else{
9853             Roo.dd.DDProxy.prototype.endDrag.apply(this.dd, arguments);
9854             this.proxy.hide();
9855         }
9856         this.refreshSize();
9857         this.adjustAssets();
9858         this.focus();
9859         this.fireEvent("move", this, this.xy[0], this.xy[1]);
9860     },
9861
9862     /**
9863      * Brings this dialog to the front of any other visible dialogs
9864      * @return {Roo.BasicDialog} this
9865      */
9866     toFront : function(){
9867         Roo.DialogManager.bringToFront(this);
9868         return this;
9869     },
9870
9871     /**
9872      * Sends this dialog to the back (under) of any other visible dialogs
9873      * @return {Roo.BasicDialog} this
9874      */
9875     toBack : function(){
9876         Roo.DialogManager.sendToBack(this);
9877         return this;
9878     },
9879
9880     /**
9881      * Centers this dialog in the viewport
9882      * @return {Roo.BasicDialog} this
9883      */
9884     center : function(){
9885         var xy = this.el.getCenterXY(true);
9886         this.moveTo(xy[0], xy[1]);
9887         return this;
9888     },
9889
9890     /**
9891      * Moves the dialog's top-left corner to the specified point
9892      * @param {Number} x
9893      * @param {Number} y
9894      * @return {Roo.BasicDialog} this
9895      */
9896     moveTo : function(x, y){
9897         this.xy = [x,y];
9898         if(this.isVisible()){
9899             this.el.setXY(this.xy);
9900             this.adjustAssets();
9901         }
9902         return this;
9903     },
9904
9905     /**
9906      * Aligns the dialog to the specified element
9907      * @param {String/HTMLElement/Roo.Element} element The element to align to.
9908      * @param {String} position The position to align to (see {@link Roo.Element#alignTo} for more details).
9909      * @param {Array} offsets (optional) Offset the positioning by [x, y]
9910      * @return {Roo.BasicDialog} this
9911      */
9912     alignTo : function(element, position, offsets){
9913         this.xy = this.el.getAlignToXY(element, position, offsets);
9914         if(this.isVisible()){
9915             this.el.setXY(this.xy);
9916             this.adjustAssets();
9917         }
9918         return this;
9919     },
9920
9921     /**
9922      * Anchors an element to another element and realigns it when the window is resized.
9923      * @param {String/HTMLElement/Roo.Element} element The element to align to.
9924      * @param {String} position The position to align to (see {@link Roo.Element#alignTo} for more details)
9925      * @param {Array} offsets (optional) Offset the positioning by [x, y]
9926      * @param {Boolean/Number} monitorScroll (optional) true to monitor body scroll and reposition. If this parameter
9927      * is a number, it is used as the buffer delay (defaults to 50ms).
9928      * @return {Roo.BasicDialog} this
9929      */
9930     anchorTo : function(el, alignment, offsets, monitorScroll){
9931         var action = function(){
9932             this.alignTo(el, alignment, offsets);
9933         };
9934         Roo.EventManager.onWindowResize(action, this);
9935         var tm = typeof monitorScroll;
9936         if(tm != 'undefined'){
9937             Roo.EventManager.on(window, 'scroll', action, this,
9938                 {buffer: tm == 'number' ? monitorScroll : 50});
9939         }
9940         action.call(this);
9941         return this;
9942     },
9943
9944     /**
9945      * Returns true if the dialog is visible
9946      * @return {Boolean}
9947      */
9948     isVisible : function(){
9949         return this.el.isVisible();
9950     },
9951
9952     // private
9953     animHide : function(callback){
9954         var b = Roo.get(this.animateTarget).getBox();
9955         this.proxy.show();
9956         this.proxy.setBounds(this.xy[0], this.xy[1], this.size.width, this.size.height);
9957         this.el.hide();
9958         this.proxy.setBounds(b.x, b.y, b.width, b.height, true, .35,
9959                     this.hideEl.createDelegate(this, [callback]));
9960     },
9961
9962     /**
9963      * Hides the dialog.
9964      * @param {Function} callback (optional) Function to call when the dialog is hidden
9965      * @return {Roo.BasicDialog} this
9966      */
9967     hide : function(callback){
9968         if (this.fireEvent("beforehide", this) === false){
9969             return;
9970         }
9971         if(this.shadow){
9972             this.shadow.hide();
9973         }
9974         if(this.shim) {
9975           this.shim.hide();
9976         }
9977         // sometimes animateTarget seems to get set.. causing problems...
9978         // this just double checks..
9979         if(this.animateTarget && Roo.get(this.animateTarget)) {
9980            this.animHide(callback);
9981         }else{
9982             this.el.hide();
9983             this.hideEl(callback);
9984         }
9985         return this;
9986     },
9987
9988     // private
9989     hideEl : function(callback){
9990         this.proxy.hide();
9991         if(this.modal){
9992             this.mask.hide();
9993             Roo.get(document.body).removeClass("x-body-masked");
9994         }
9995         this.fireEvent("hide", this);
9996         if(typeof callback == "function"){
9997             callback();
9998         }
9999     },
10000
10001     // private
10002     hideAction : function(){
10003         this.setLeft("-10000px");
10004         this.setTop("-10000px");
10005         this.setStyle("visibility", "hidden");
10006     },
10007
10008     // private
10009     refreshSize : function(){
10010         this.size = this.el.getSize();
10011         this.xy = this.el.getXY();
10012         Roo.state.Manager.set(this.stateId || this.el.id + "-state", this.el.getBox());
10013     },
10014
10015     // private
10016     // z-index is managed by the DialogManager and may be overwritten at any time
10017     setZIndex : function(index){
10018         if(this.modal){
10019             this.mask.setStyle("z-index", index);
10020         }
10021         if(this.shim){
10022             this.shim.setStyle("z-index", ++index);
10023         }
10024         if(this.shadow){
10025             this.shadow.setZIndex(++index);
10026         }
10027         this.el.setStyle("z-index", ++index);
10028         if(this.proxy){
10029             this.proxy.setStyle("z-index", ++index);
10030         }
10031         if(this.resizer){
10032             this.resizer.proxy.setStyle("z-index", ++index);
10033         }
10034
10035         this.lastZIndex = index;
10036     },
10037
10038     /**
10039      * Returns the element for this dialog
10040      * @return {Roo.Element} The underlying dialog Element
10041      */
10042     getEl : function(){
10043         return this.el;
10044     }
10045 });
10046
10047 /**
10048  * @class Roo.DialogManager
10049  * Provides global access to BasicDialogs that have been created and
10050  * support for z-indexing (layering) multiple open dialogs.
10051  */
10052 Roo.DialogManager = function(){
10053     var list = {};
10054     var accessList = [];
10055     var front = null;
10056
10057     // private
10058     var sortDialogs = function(d1, d2){
10059         return (!d1._lastAccess || d1._lastAccess < d2._lastAccess) ? -1 : 1;
10060     };
10061
10062     // private
10063     var orderDialogs = function(){
10064         accessList.sort(sortDialogs);
10065         var seed = Roo.DialogManager.zseed;
10066         for(var i = 0, len = accessList.length; i < len; i++){
10067             var dlg = accessList[i];
10068             if(dlg){
10069                 dlg.setZIndex(seed + (i*10));
10070             }
10071         }
10072     };
10073
10074     return {
10075         /**
10076          * The starting z-index for BasicDialogs (defaults to 9000)
10077          * @type Number The z-index value
10078          */
10079         zseed : 9000,
10080
10081         // private
10082         register : function(dlg){
10083             list[dlg.id] = dlg;
10084             accessList.push(dlg);
10085         },
10086
10087         // private
10088         unregister : function(dlg){
10089             delete list[dlg.id];
10090             var i=0;
10091             var len=0;
10092             if(!accessList.indexOf){
10093                 for(  i = 0, len = accessList.length; i < len; i++){
10094                     if(accessList[i] == dlg){
10095                         accessList.splice(i, 1);
10096                         return;
10097                     }
10098                 }
10099             }else{
10100                  i = accessList.indexOf(dlg);
10101                 if(i != -1){
10102                     accessList.splice(i, 1);
10103                 }
10104             }
10105         },
10106
10107         /**
10108          * Gets a registered dialog by id
10109          * @param {String/Object} id The id of the dialog or a dialog
10110          * @return {Roo.BasicDialog} this
10111          */
10112         get : function(id){
10113             return typeof id == "object" ? id : list[id];
10114         },
10115
10116         /**
10117          * Brings the specified dialog to the front
10118          * @param {String/Object} dlg The id of the dialog or a dialog
10119          * @return {Roo.BasicDialog} this
10120          */
10121         bringToFront : function(dlg){
10122             dlg = this.get(dlg);
10123             if(dlg != front){
10124                 front = dlg;
10125                 dlg._lastAccess = new Date().getTime();
10126                 orderDialogs();
10127             }
10128             return dlg;
10129         },
10130
10131         /**
10132          * Sends the specified dialog to the back
10133          * @param {String/Object} dlg The id of the dialog or a dialog
10134          * @return {Roo.BasicDialog} this
10135          */
10136         sendToBack : function(dlg){
10137             dlg = this.get(dlg);
10138             dlg._lastAccess = -(new Date().getTime());
10139             orderDialogs();
10140             return dlg;
10141         },
10142
10143         /**
10144          * Hides all dialogs
10145          */
10146         hideAll : function(){
10147             for(var id in list){
10148                 if(list[id] && typeof list[id] != "function" && list[id].isVisible()){
10149                     list[id].hide();
10150                 }
10151             }
10152         }
10153     };
10154 }();
10155
10156 /**
10157  * @class Roo.LayoutDialog
10158  * @extends Roo.BasicDialog
10159  * @children Roo.ContentPanel
10160  * @parent builder none
10161  * Dialog which provides adjustments for working with a layout in a Dialog.
10162  * Add your necessary layout config options to the dialog's config.<br>
10163  * Example usage (including a nested layout):
10164  * <pre><code>
10165 if(!dialog){
10166     dialog = new Roo.LayoutDialog("download-dlg", {
10167         modal: true,
10168         width:600,
10169         height:450,
10170         shadow:true,
10171         minWidth:500,
10172         minHeight:350,
10173         autoTabs:true,
10174         proxyDrag:true,
10175         // layout config merges with the dialog config
10176         center:{
10177             tabPosition: "top",
10178             alwaysShowTabs: true
10179         }
10180     });
10181     dialog.addKeyListener(27, dialog.hide, dialog);
10182     dialog.setDefaultButton(dialog.addButton("Close", dialog.hide, dialog));
10183     dialog.addButton("Build It!", this.getDownload, this);
10184
10185     // we can even add nested layouts
10186     var innerLayout = new Roo.BorderLayout("dl-inner", {
10187         east: {
10188             initialSize: 200,
10189             autoScroll:true,
10190             split:true
10191         },
10192         center: {
10193             autoScroll:true
10194         }
10195     });
10196     innerLayout.beginUpdate();
10197     innerLayout.add("east", new Roo.ContentPanel("dl-details"));
10198     innerLayout.add("center", new Roo.ContentPanel("selection-panel"));
10199     innerLayout.endUpdate(true);
10200
10201     var layout = dialog.getLayout();
10202     layout.beginUpdate();
10203     layout.add("center", new Roo.ContentPanel("standard-panel",
10204                         {title: "Download the Source", fitToFrame:true}));
10205     layout.add("center", new Roo.NestedLayoutPanel(innerLayout,
10206                {title: "Build your own roo.js"}));
10207     layout.getRegion("center").showPanel(sp);
10208     layout.endUpdate();
10209 }
10210 </code></pre>
10211     * @constructor
10212     * @param {String/HTMLElement/Roo.Element} el The id of or container element, or config
10213     * @param {Object} config configuration options
10214   */
10215 Roo.LayoutDialog = function(el, cfg){
10216     
10217     var config=  cfg;
10218     if (typeof(cfg) == 'undefined') {
10219         config = Roo.apply({}, el);
10220         // not sure why we use documentElement here.. - it should always be body.
10221         // IE7 borks horribly if we use documentElement.
10222         // webkit also does not like documentElement - it creates a body element...
10223         el = Roo.get( document.body || document.documentElement ).createChild();
10224         //config.autoCreate = true;
10225     }
10226     
10227     
10228     config.autoTabs = false;
10229     Roo.LayoutDialog.superclass.constructor.call(this, el, config);
10230     this.body.setStyle({overflow:"hidden", position:"relative"});
10231     this.layout = new Roo.BorderLayout(this.body.dom, config);
10232     this.layout.monitorWindowResize = false;
10233     this.el.addClass("x-dlg-auto-layout");
10234     // fix case when center region overwrites center function
10235     this.center = Roo.BasicDialog.prototype.center;
10236     this.on("show", this.layout.layout, this.layout, true);
10237     if (config.items) {
10238         var xitems = config.items;
10239         delete config.items;
10240         Roo.each(xitems, this.addxtype, this);
10241     }
10242     
10243     
10244 };
10245 Roo.extend(Roo.LayoutDialog, Roo.BasicDialog, {
10246     
10247     
10248     /**
10249      * @cfg {Roo.LayoutRegion} east  
10250      */
10251     /**
10252      * @cfg {Roo.LayoutRegion} west
10253      */
10254     /**
10255      * @cfg {Roo.LayoutRegion} south
10256      */
10257     /**
10258      * @cfg {Roo.LayoutRegion} north
10259      */
10260     /**
10261      * @cfg {Roo.LayoutRegion} center
10262      */
10263     /**
10264      * @cfg {Roo.Button} buttons[]  Bottom buttons..
10265      */
10266     
10267     
10268     /**
10269      * Ends update of the layout <strike>and resets display to none</strike>. Use standard beginUpdate/endUpdate on the layout.
10270      * @deprecated
10271      */
10272     endUpdate : function(){
10273         this.layout.endUpdate();
10274     },
10275
10276     /**
10277      * Begins an update of the layout <strike>and sets display to block and visibility to hidden</strike>. Use standard beginUpdate/endUpdate on the layout.
10278      *  @deprecated
10279      */
10280     beginUpdate : function(){
10281         this.layout.beginUpdate();
10282     },
10283
10284     /**
10285      * Get the BorderLayout for this dialog
10286      * @return {Roo.BorderLayout}
10287      */
10288     getLayout : function(){
10289         return this.layout;
10290     },
10291
10292     showEl : function(){
10293         Roo.LayoutDialog.superclass.showEl.apply(this, arguments);
10294         if(Roo.isIE7){
10295             this.layout.layout();
10296         }
10297     },
10298
10299     // private
10300     // Use the syncHeightBeforeShow config option to control this automatically
10301     syncBodyHeight : function(){
10302         Roo.LayoutDialog.superclass.syncBodyHeight.call(this);
10303         if(this.layout){this.layout.layout();}
10304     },
10305     
10306       /**
10307      * Add an xtype element (actually adds to the layout.)
10308      * @return {Object} xdata xtype object data.
10309      */
10310     
10311     addxtype : function(c) {
10312         return this.layout.addxtype(c);
10313     }
10314 });/*
10315  * Based on:
10316  * Ext JS Library 1.1.1
10317  * Copyright(c) 2006-2007, Ext JS, LLC.
10318  *
10319  * Originally Released Under LGPL - original licence link has changed is not relivant.
10320  *
10321  * Fork - LGPL
10322  * <script type="text/javascript">
10323  */
10324  
10325 /**
10326  * @class Roo.MessageBox
10327  * @static
10328  * Utility class for generating different styles of message boxes.  The alias Roo.Msg can also be used.
10329  * Example usage:
10330  *<pre><code>
10331 // Basic alert:
10332 Roo.Msg.alert('Status', 'Changes saved successfully.');
10333
10334 // Prompt for user data:
10335 Roo.Msg.prompt('Name', 'Please enter your name:', function(btn, text){
10336     if (btn == 'ok'){
10337         // process text value...
10338     }
10339 });
10340
10341 // Show a dialog using config options:
10342 Roo.Msg.show({
10343    title:'Save Changes?',
10344    msg: 'Your are closing a tab that has unsaved changes. Would you like to save your changes?',
10345    buttons: Roo.Msg.YESNOCANCEL,
10346    fn: processResult,
10347    animEl: 'elId'
10348 });
10349 </code></pre>
10350  * @static
10351  */
10352 Roo.MessageBox = function(){
10353     var dlg, opt, mask, waitTimer;
10354     var bodyEl, msgEl, textboxEl, textareaEl, progressEl, pp;
10355     var buttons, activeTextEl, bwidth;
10356
10357     // private
10358     var handleButton = function(button){
10359         dlg.hide();
10360         Roo.callback(opt.fn, opt.scope||window, [button, activeTextEl.dom.value], 1);
10361     };
10362
10363     // private
10364     var handleHide = function(){
10365         if(opt && opt.cls){
10366             dlg.el.removeClass(opt.cls);
10367         }
10368         if(waitTimer){
10369             Roo.TaskMgr.stop(waitTimer);
10370             waitTimer = null;
10371         }
10372     };
10373
10374     // private
10375     var updateButtons = function(b){
10376         var width = 0;
10377         if(!b){
10378             buttons["ok"].hide();
10379             buttons["cancel"].hide();
10380             buttons["yes"].hide();
10381             buttons["no"].hide();
10382             dlg.footer.dom.style.display = 'none';
10383             return width;
10384         }
10385         dlg.footer.dom.style.display = '';
10386         for(var k in buttons){
10387             if(typeof buttons[k] != "function"){
10388                 if(b[k]){
10389                     buttons[k].show();
10390                     buttons[k].setText(typeof b[k] == "string" ? b[k] : Roo.MessageBox.buttonText[k]);
10391                     width += buttons[k].el.getWidth()+15;
10392                 }else{
10393                     buttons[k].hide();
10394                 }
10395             }
10396         }
10397         return width;
10398     };
10399
10400     // private
10401     var handleEsc = function(d, k, e){
10402         if(opt && opt.closable !== false){
10403             dlg.hide();
10404         }
10405         if(e){
10406             e.stopEvent();
10407         }
10408     };
10409
10410     return {
10411         /**
10412          * Returns a reference to the underlying {@link Roo.BasicDialog} element
10413          * @return {Roo.BasicDialog} The BasicDialog element
10414          */
10415         getDialog : function(){
10416            if(!dlg){
10417                 dlg = new Roo.BasicDialog("x-msg-box", {
10418                     autoCreate : true,
10419                     shadow: true,
10420                     draggable: true,
10421                     resizable:false,
10422                     constraintoviewport:false,
10423                     fixedcenter:true,
10424                     collapsible : false,
10425                     shim:true,
10426                     modal: true,
10427                     width:400, height:100,
10428                     buttonAlign:"center",
10429                     closeClick : function(){
10430                         if(opt && opt.buttons && opt.buttons.no && !opt.buttons.cancel){
10431                             handleButton("no");
10432                         }else{
10433                             handleButton("cancel");
10434                         }
10435                     }
10436                 });
10437               
10438                 dlg.on("hide", handleHide);
10439                 mask = dlg.mask;
10440                 dlg.addKeyListener(27, handleEsc);
10441                 buttons = {};
10442                 var bt = this.buttonText;
10443                 buttons["ok"] = dlg.addButton(bt["ok"], handleButton.createCallback("ok"));
10444                 buttons["yes"] = dlg.addButton(bt["yes"], handleButton.createCallback("yes"));
10445                 buttons["no"] = dlg.addButton(bt["no"], handleButton.createCallback("no"));
10446                 buttons["cancel"] = dlg.addButton(bt["cancel"], handleButton.createCallback("cancel"));
10447                 bodyEl = dlg.body.createChild({
10448
10449                     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>'
10450                 });
10451                 msgEl = bodyEl.dom.firstChild;
10452                 textboxEl = Roo.get(bodyEl.dom.childNodes[2]);
10453                 textboxEl.enableDisplayMode();
10454                 textboxEl.addKeyListener([10,13], function(){
10455                     if(dlg.isVisible() && opt && opt.buttons){
10456                         if(opt.buttons.ok){
10457                             handleButton("ok");
10458                         }else if(opt.buttons.yes){
10459                             handleButton("yes");
10460                         }
10461                     }
10462                 });
10463                 textareaEl = Roo.get(bodyEl.dom.childNodes[3]);
10464                 textareaEl.enableDisplayMode();
10465                 progressEl = Roo.get(bodyEl.dom.childNodes[4]);
10466                 progressEl.enableDisplayMode();
10467                 var pf = progressEl.dom.firstChild;
10468                 if (pf) {
10469                     pp = Roo.get(pf.firstChild);
10470                     pp.setHeight(pf.offsetHeight);
10471                 }
10472                 
10473             }
10474             return dlg;
10475         },
10476
10477         /**
10478          * Updates the message box body text
10479          * @param {String} text (optional) Replaces the message box element's innerHTML with the specified string (defaults to
10480          * the XHTML-compliant non-breaking space character '&amp;#160;')
10481          * @return {Roo.MessageBox} This message box
10482          */
10483         updateText : function(text){
10484             if(!dlg.isVisible() && !opt.width){
10485                 dlg.resizeTo(this.maxWidth, 100); // resize first so content is never clipped from previous shows
10486             }
10487             msgEl.innerHTML = text || '&#160;';
10488       
10489             var cw =  Math.max(msgEl.offsetWidth, msgEl.parentNode.scrollWidth);
10490             //Roo.log("guesed size: " + JSON.stringify([cw,msgEl.offsetWidth, msgEl.parentNode.scrollWidth]));
10491             var w = Math.max(
10492                     Math.min(opt.width || cw , this.maxWidth), 
10493                     Math.max(opt.minWidth || this.minWidth, bwidth)
10494             );
10495             if(opt.prompt){
10496                 activeTextEl.setWidth(w);
10497             }
10498             if(dlg.isVisible()){
10499                 dlg.fixedcenter = false;
10500             }
10501             // to big, make it scroll. = But as usual stupid IE does not support
10502             // !important..
10503             
10504             if ( bodyEl.getHeight() > (Roo.lib.Dom.getViewHeight() - 100)) {
10505                 bodyEl.setHeight ( Roo.lib.Dom.getViewHeight() - 100 );
10506                 bodyEl.dom.style.overflowY = 'auto' + ( Roo.isIE ? '' : ' !important');
10507             } else {
10508                 bodyEl.dom.style.height = '';
10509                 bodyEl.dom.style.overflowY = '';
10510             }
10511             if (cw > w) {
10512                 bodyEl.dom.style.get = 'auto' + ( Roo.isIE ? '' : ' !important');
10513             } else {
10514                 bodyEl.dom.style.overflowX = '';
10515             }
10516             
10517             dlg.setContentSize(w, bodyEl.getHeight());
10518             if(dlg.isVisible()){
10519                 dlg.fixedcenter = true;
10520             }
10521             return this;
10522         },
10523
10524         /**
10525          * Updates a progress-style message box's text and progress bar.  Only relevant on message boxes
10526          * initiated via {@link Roo.MessageBox#progress} or by calling {@link Roo.MessageBox#show} with progress: true.
10527          * @param {Number} value Any number between 0 and 1 (e.g., .5)
10528          * @param {String} text (optional) If defined, the message box's body text is replaced with the specified string (defaults to undefined)
10529          * @return {Roo.MessageBox} This message box
10530          */
10531         updateProgress : function(value, text){
10532             if(text){
10533                 this.updateText(text);
10534             }
10535             if (pp) { // weird bug on my firefox - for some reason this is not defined
10536                 pp.setWidth(Math.floor(value*progressEl.dom.firstChild.offsetWidth));
10537             }
10538             return this;
10539         },        
10540
10541         /**
10542          * Returns true if the message box is currently displayed
10543          * @return {Boolean} True if the message box is visible, else false
10544          */
10545         isVisible : function(){
10546             return dlg && dlg.isVisible();  
10547         },
10548
10549         /**
10550          * Hides the message box if it is displayed
10551          */
10552         hide : function(){
10553             if(this.isVisible()){
10554                 dlg.hide();
10555             }  
10556         },
10557
10558         /**
10559          * Displays a new message box, or reinitializes an existing message box, based on the config options
10560          * passed in. All functions (e.g. prompt, alert, etc) on MessageBox call this function internally.
10561          * The following config object properties are supported:
10562          * <pre>
10563 Property    Type             Description
10564 ----------  ---------------  ------------------------------------------------------------------------------------
10565 animEl            String/Element   An id or Element from which the message box should animate as it opens and
10566                                    closes (defaults to undefined)
10567 buttons           Object/Boolean   A button config object (e.g., Roo.MessageBox.OKCANCEL or {ok:'Foo',
10568                                    cancel:'Bar'}), or false to not show any buttons (defaults to false)
10569 closable          Boolean          False to hide the top-right close button (defaults to true).  Note that
10570                                    progress and wait dialogs will ignore this property and always hide the
10571                                    close button as they can only be closed programmatically.
10572 cls               String           A custom CSS class to apply to the message box element
10573 defaultTextHeight Number           The default height in pixels of the message box's multiline textarea if
10574                                    displayed (defaults to 75)
10575 fn                Function         A callback function to execute after closing the dialog.  The arguments to the
10576                                    function will be btn (the name of the button that was clicked, if applicable,
10577                                    e.g. "ok"), and text (the value of the active text field, if applicable).
10578                                    Progress and wait dialogs will ignore this option since they do not respond to
10579                                    user actions and can only be closed programmatically, so any required function
10580                                    should be called by the same code after it closes the dialog.
10581 icon              String           A CSS class that provides a background image to be used as an icon for
10582                                    the dialog (e.g., Roo.MessageBox.WARNING or 'custom-class', defaults to '')
10583 maxWidth          Number           The maximum width in pixels of the message box (defaults to 600)
10584 minWidth          Number           The minimum width in pixels of the message box (defaults to 100)
10585 modal             Boolean          False to allow user interaction with the page while the message box is
10586                                    displayed (defaults to true)
10587 msg               String           A string that will replace the existing message box body text (defaults
10588                                    to the XHTML-compliant non-breaking space character '&#160;')
10589 multiline         Boolean          True to prompt the user to enter multi-line text (defaults to false)
10590 progress          Boolean          True to display a progress bar (defaults to false)
10591 progressText      String           The text to display inside the progress bar if progress = true (defaults to '')
10592 prompt            Boolean          True to prompt the user to enter single-line text (defaults to false)
10593 proxyDrag         Boolean          True to display a lightweight proxy while dragging (defaults to false)
10594 title             String           The title text
10595 value             String           The string value to set into the active textbox element if displayed
10596 wait              Boolean          True to display a progress bar (defaults to false)
10597 width             Number           The width of the dialog in pixels
10598 </pre>
10599          *
10600          * Example usage:
10601          * <pre><code>
10602 Roo.Msg.show({
10603    title: 'Address',
10604    msg: 'Please enter your address:',
10605    width: 300,
10606    buttons: Roo.MessageBox.OKCANCEL,
10607    multiline: true,
10608    fn: saveAddress,
10609    animEl: 'addAddressBtn'
10610 });
10611 </code></pre>
10612          * @param {Object} config Configuration options
10613          * @return {Roo.MessageBox} This message box
10614          */
10615         show : function(options)
10616         {
10617             
10618             // this causes nightmares if you show one dialog after another
10619             // especially on callbacks..
10620              
10621             if(this.isVisible()){
10622                 
10623                 this.hide();
10624                 Roo.log("[Roo.Messagebox] Show called while message displayed:" );
10625                 Roo.log("Old Dialog Message:" +  msgEl.innerHTML );
10626                 Roo.log("New Dialog Message:" +  options.msg )
10627                 //this.alert("ERROR", "Multiple dialogs where displayed at the same time");
10628                 //throw "Roo.MessageBox ERROR : Multiple dialogs where displayed at the same time";
10629                 
10630             }
10631             var d = this.getDialog();
10632             opt = options;
10633             d.setTitle(opt.title || "&#160;");
10634             d.close.setDisplayed(opt.closable !== false);
10635             activeTextEl = textboxEl;
10636             opt.prompt = opt.prompt || (opt.multiline ? true : false);
10637             if(opt.prompt){
10638                 if(opt.multiline){
10639                     textboxEl.hide();
10640                     textareaEl.show();
10641                     textareaEl.setHeight(typeof opt.multiline == "number" ?
10642                         opt.multiline : this.defaultTextHeight);
10643                     activeTextEl = textareaEl;
10644                 }else{
10645                     textboxEl.show();
10646                     textareaEl.hide();
10647                 }
10648             }else{
10649                 textboxEl.hide();
10650                 textareaEl.hide();
10651             }
10652             progressEl.setDisplayed(opt.progress === true);
10653             this.updateProgress(0);
10654             activeTextEl.dom.value = opt.value || "";
10655             if(opt.prompt){
10656                 dlg.setDefaultButton(activeTextEl);
10657             }else{
10658                 var bs = opt.buttons;
10659                 var db = null;
10660                 if(bs && bs.ok){
10661                     db = buttons["ok"];
10662                 }else if(bs && bs.yes){
10663                     db = buttons["yes"];
10664                 }
10665                 dlg.setDefaultButton(db);
10666             }
10667             bwidth = updateButtons(opt.buttons);
10668             this.updateText(opt.msg);
10669             if(opt.cls){
10670                 d.el.addClass(opt.cls);
10671             }
10672             d.proxyDrag = opt.proxyDrag === true;
10673             d.modal = opt.modal !== false;
10674             d.mask = opt.modal !== false ? mask : false;
10675             if(!d.isVisible()){
10676                 // force it to the end of the z-index stack so it gets a cursor in FF
10677                 document.body.appendChild(dlg.el.dom);
10678                 d.animateTarget = null;
10679                 d.show(options.animEl);
10680             }
10681             dlg.toFront();
10682             return this;
10683         },
10684
10685         /**
10686          * Displays a message box with a progress bar.  This message box has no buttons and is not closeable by
10687          * the user.  You are responsible for updating the progress bar as needed via {@link Roo.MessageBox#updateProgress}
10688          * and closing the message box when the process is complete.
10689          * @param {String} title The title bar text
10690          * @param {String} msg The message box body text
10691          * @return {Roo.MessageBox} This message box
10692          */
10693         progress : function(title, msg){
10694             this.show({
10695                 title : title,
10696                 msg : msg,
10697                 buttons: false,
10698                 progress:true,
10699                 closable:false,
10700                 minWidth: this.minProgressWidth,
10701                 modal : true
10702             });
10703             return this;
10704         },
10705
10706         /**
10707          * Displays a standard read-only message box with an OK button (comparable to the basic JavaScript Window.alert).
10708          * If a callback function is passed it will be called after the user clicks the button, and the
10709          * id of the button that was clicked will be passed as the only parameter to the callback
10710          * (could also be the top-right close button).
10711          * @param {String} title The title bar text
10712          * @param {String} msg The message box body text
10713          * @param {Function} fn (optional) The callback function invoked after the message box is closed
10714          * @param {Object} scope (optional) The scope of the callback function
10715          * @return {Roo.MessageBox} This message box
10716          */
10717         alert : function(title, msg, fn, scope){
10718             this.show({
10719                 title : title,
10720                 msg : msg,
10721                 buttons: this.OK,
10722                 fn: fn,
10723                 scope : scope,
10724                 modal : true
10725             });
10726             return this;
10727         },
10728
10729         /**
10730          * Displays a message box with an infinitely auto-updating progress bar.  This can be used to block user
10731          * interaction while waiting for a long-running process to complete that does not have defined intervals.
10732          * You are responsible for closing the message box when the process is complete.
10733          * @param {String} msg The message box body text
10734          * @param {String} title (optional) The title bar text
10735          * @return {Roo.MessageBox} This message box
10736          */
10737         wait : function(msg, title){
10738             this.show({
10739                 title : title,
10740                 msg : msg,
10741                 buttons: false,
10742                 closable:false,
10743                 progress:true,
10744                 modal:true,
10745                 width:300,
10746                 wait:true
10747             });
10748             waitTimer = Roo.TaskMgr.start({
10749                 run: function(i){
10750                     Roo.MessageBox.updateProgress(((((i+20)%20)+1)*5)*.01);
10751                 },
10752                 interval: 1000
10753             });
10754             return this;
10755         },
10756
10757         /**
10758          * Displays a confirmation message box with Yes and No buttons (comparable to JavaScript's Window.confirm).
10759          * If a callback function is passed it will be called after the user clicks either button, and the id of the
10760          * button that was clicked will be passed as the only parameter to the callback (could also be the top-right close button).
10761          * @param {String} title The title bar text
10762          * @param {String} msg The message box body text
10763          * @param {Function} fn (optional) The callback function invoked after the message box is closed
10764          * @param {Object} scope (optional) The scope of the callback function
10765          * @return {Roo.MessageBox} This message box
10766          */
10767         confirm : function(title, msg, fn, scope){
10768             this.show({
10769                 title : title,
10770                 msg : msg,
10771                 buttons: this.YESNO,
10772                 fn: fn,
10773                 scope : scope,
10774                 modal : true
10775             });
10776             return this;
10777         },
10778
10779         /**
10780          * Displays a message box with OK and Cancel buttons prompting the user to enter some text (comparable to
10781          * JavaScript's Window.prompt).  The prompt can be a single-line or multi-line textbox.  If a callback function
10782          * is passed it will be called after the user clicks either button, and the id of the button that was clicked
10783          * (could also be the top-right close button) and the text that was entered will be passed as the two
10784          * parameters to the callback.
10785          * @param {String} title The title bar text
10786          * @param {String} msg The message box body text
10787          * @param {Function} fn (optional) The callback function invoked after the message box is closed
10788          * @param {Object} scope (optional) The scope of the callback function
10789          * @param {Boolean/Number} multiline (optional) True to create a multiline textbox using the defaultTextHeight
10790          * property, or the height in pixels to create the textbox (defaults to false / single-line)
10791          * @return {Roo.MessageBox} This message box
10792          */
10793         prompt : function(title, msg, fn, scope, multiline){
10794             this.show({
10795                 title : title,
10796                 msg : msg,
10797                 buttons: this.OKCANCEL,
10798                 fn: fn,
10799                 minWidth:250,
10800                 scope : scope,
10801                 prompt:true,
10802                 multiline: multiline,
10803                 modal : true
10804             });
10805             return this;
10806         },
10807
10808         /**
10809          * Button config that displays a single OK button
10810          * @type Object
10811          */
10812         OK : {ok:true},
10813         /**
10814          * Button config that displays Yes and No buttons
10815          * @type Object
10816          */
10817         YESNO : {yes:true, no:true},
10818         /**
10819          * Button config that displays OK and Cancel buttons
10820          * @type Object
10821          */
10822         OKCANCEL : {ok:true, cancel:true},
10823         /**
10824          * Button config that displays Yes, No and Cancel buttons
10825          * @type Object
10826          */
10827         YESNOCANCEL : {yes:true, no:true, cancel:true},
10828
10829         /**
10830          * The default height in pixels of the message box's multiline textarea if displayed (defaults to 75)
10831          * @type Number
10832          */
10833         defaultTextHeight : 75,
10834         /**
10835          * The maximum width in pixels of the message box (defaults to 600)
10836          * @type Number
10837          */
10838         maxWidth : 600,
10839         /**
10840          * The minimum width in pixels of the message box (defaults to 100)
10841          * @type Number
10842          */
10843         minWidth : 100,
10844         /**
10845          * The minimum width in pixels of the message box if it is a progress-style dialog.  This is useful
10846          * for setting a different minimum width than text-only dialogs may need (defaults to 250)
10847          * @type Number
10848          */
10849         minProgressWidth : 250,
10850         /**
10851          * An object containing the default button text strings that can be overriden for localized language support.
10852          * Supported properties are: ok, cancel, yes and no.
10853          * Customize the default text like so: Roo.MessageBox.buttonText.yes = "S?";
10854          * @type Object
10855          */
10856         buttonText : {
10857             ok : "OK",
10858             cancel : "Cancel",
10859             yes : "Yes",
10860             no : "No"
10861         }
10862     };
10863 }();
10864
10865 /**
10866  * Shorthand for {@link Roo.MessageBox}
10867  */
10868 Roo.Msg = Roo.MessageBox;/*
10869  * Based on:
10870  * Ext JS Library 1.1.1
10871  * Copyright(c) 2006-2007, Ext JS, LLC.
10872  *
10873  * Originally Released Under LGPL - original licence link has changed is not relivant.
10874  *
10875  * Fork - LGPL
10876  * <script type="text/javascript">
10877  */
10878 /**
10879  * @class Roo.QuickTips
10880  * Provides attractive and customizable tooltips for any element.
10881  * @static
10882  */
10883 Roo.QuickTips = function(){
10884     var el, tipBody, tipBodyText, tipTitle, tm, cfg, close, tagEls = {}, esc, removeCls = null, bdLeft, bdRight;
10885     var ce, bd, xy, dd;
10886     var visible = false, disabled = true, inited = false;
10887     var showProc = 1, hideProc = 1, dismissProc = 1, locks = [];
10888     
10889     var onOver = function(e){
10890         if(disabled){
10891             return;
10892         }
10893         var t = e.getTarget();
10894         if(!t || t.nodeType !== 1 || t == document || t == document.body){
10895             return;
10896         }
10897         if(ce && t == ce.el){
10898             clearTimeout(hideProc);
10899             return;
10900         }
10901         if(t && tagEls[t.id]){
10902             tagEls[t.id].el = t;
10903             showProc = show.defer(tm.showDelay, tm, [tagEls[t.id]]);
10904             return;
10905         }
10906         var ttp, et = Roo.fly(t);
10907         var ns = cfg.namespace;
10908         if(tm.interceptTitles && t.title){
10909             ttp = t.title;
10910             t.qtip = ttp;
10911             t.removeAttribute("title");
10912             e.preventDefault();
10913         }else{
10914             ttp = t.qtip || et.getAttributeNS(ns, cfg.attribute) || et.getAttributeNS(cfg.alt_namespace, cfg.attribute) ;
10915         }
10916         if(ttp){
10917             showProc = show.defer(tm.showDelay, tm, [{
10918                 el: t, 
10919                 text: ttp.replace(/\\n/g,'<br/>'),
10920                 width: et.getAttributeNS(ns, cfg.width),
10921                 autoHide: et.getAttributeNS(ns, cfg.hide) != "user",
10922                 title: et.getAttributeNS(ns, cfg.title),
10923                     cls: et.getAttributeNS(ns, cfg.cls)
10924             }]);
10925         }
10926     };
10927     
10928     var onOut = function(e){
10929         clearTimeout(showProc);
10930         var t = e.getTarget();
10931         if(t && ce && ce.el == t && (tm.autoHide && ce.autoHide !== false)){
10932             hideProc = setTimeout(hide, tm.hideDelay);
10933         }
10934     };
10935     
10936     var onMove = function(e){
10937         if(disabled){
10938             return;
10939         }
10940         xy = e.getXY();
10941         xy[1] += 18;
10942         if(tm.trackMouse && ce){
10943             el.setXY(xy);
10944         }
10945     };
10946     
10947     var onDown = function(e){
10948         clearTimeout(showProc);
10949         clearTimeout(hideProc);
10950         if(!e.within(el)){
10951             if(tm.hideOnClick){
10952                 hide();
10953                 tm.disable();
10954                 tm.enable.defer(100, tm);
10955             }
10956         }
10957     };
10958     
10959     var getPad = function(){
10960         return 2;//bdLeft.getPadding('l')+bdRight.getPadding('r');
10961     };
10962
10963     var show = function(o){
10964         if(disabled){
10965             return;
10966         }
10967         clearTimeout(dismissProc);
10968         ce = o;
10969         if(removeCls){ // in case manually hidden
10970             el.removeClass(removeCls);
10971             removeCls = null;
10972         }
10973         if(ce.cls){
10974             el.addClass(ce.cls);
10975             removeCls = ce.cls;
10976         }
10977         if(ce.title){
10978             tipTitle.update(ce.title);
10979             tipTitle.show();
10980         }else{
10981             tipTitle.update('');
10982             tipTitle.hide();
10983         }
10984         el.dom.style.width  = tm.maxWidth+'px';
10985         //tipBody.dom.style.width = '';
10986         tipBodyText.update(o.text);
10987         var p = getPad(), w = ce.width;
10988         if(!w){
10989             var td = tipBodyText.dom;
10990             var aw = Math.max(td.offsetWidth, td.clientWidth, td.scrollWidth);
10991             if(aw > tm.maxWidth){
10992                 w = tm.maxWidth;
10993             }else if(aw < tm.minWidth){
10994                 w = tm.minWidth;
10995             }else{
10996                 w = aw;
10997             }
10998         }
10999         //tipBody.setWidth(w);
11000         el.setWidth(parseInt(w, 10) + p);
11001         if(ce.autoHide === false){
11002             close.setDisplayed(true);
11003             if(dd){
11004                 dd.unlock();
11005             }
11006         }else{
11007             close.setDisplayed(false);
11008             if(dd){
11009                 dd.lock();
11010             }
11011         }
11012         if(xy){
11013             el.avoidY = xy[1]-18;
11014             el.setXY(xy);
11015         }
11016         if(tm.animate){
11017             el.setOpacity(.1);
11018             el.setStyle("visibility", "visible");
11019             el.fadeIn({callback: afterShow});
11020         }else{
11021             afterShow();
11022         }
11023     };
11024     
11025     var afterShow = function(){
11026         if(ce){
11027             el.show();
11028             esc.enable();
11029             if(tm.autoDismiss && ce.autoHide !== false){
11030                 dismissProc = setTimeout(hide, tm.autoDismissDelay);
11031             }
11032         }
11033     };
11034     
11035     var hide = function(noanim){
11036         clearTimeout(dismissProc);
11037         clearTimeout(hideProc);
11038         ce = null;
11039         if(el.isVisible()){
11040             esc.disable();
11041             if(noanim !== true && tm.animate){
11042                 el.fadeOut({callback: afterHide});
11043             }else{
11044                 afterHide();
11045             } 
11046         }
11047     };
11048     
11049     var afterHide = function(){
11050         el.hide();
11051         if(removeCls){
11052             el.removeClass(removeCls);
11053             removeCls = null;
11054         }
11055     };
11056     
11057     return {
11058         /**
11059         * @cfg {Number} minWidth
11060         * The minimum width of the quick tip (defaults to 40)
11061         */
11062        minWidth : 40,
11063         /**
11064         * @cfg {Number} maxWidth
11065         * The maximum width of the quick tip (defaults to 300)
11066         */
11067        maxWidth : 300,
11068         /**
11069         * @cfg {Boolean} interceptTitles
11070         * True to automatically use the element's DOM title value if available (defaults to false)
11071         */
11072        interceptTitles : false,
11073         /**
11074         * @cfg {Boolean} trackMouse
11075         * True to have the quick tip follow the mouse as it moves over the target element (defaults to false)
11076         */
11077        trackMouse : false,
11078         /**
11079         * @cfg {Boolean} hideOnClick
11080         * True to hide the quick tip if the user clicks anywhere in the document (defaults to true)
11081         */
11082        hideOnClick : true,
11083         /**
11084         * @cfg {Number} showDelay
11085         * Delay in milliseconds before the quick tip displays after the mouse enters the target element (defaults to 500)
11086         */
11087        showDelay : 500,
11088         /**
11089         * @cfg {Number} hideDelay
11090         * Delay in milliseconds before the quick tip hides when autoHide = true (defaults to 200)
11091         */
11092        hideDelay : 200,
11093         /**
11094         * @cfg {Boolean} autoHide
11095         * True to automatically hide the quick tip after the mouse exits the target element (defaults to true).
11096         * Used in conjunction with hideDelay.
11097         */
11098        autoHide : true,
11099         /**
11100         * @cfg {Boolean}
11101         * True to automatically hide the quick tip after a set period of time, regardless of the user's actions
11102         * (defaults to true).  Used in conjunction with autoDismissDelay.
11103         */
11104        autoDismiss : true,
11105         /**
11106         * @cfg {Number}
11107         * Delay in milliseconds before the quick tip hides when autoDismiss = true (defaults to 5000)
11108         */
11109        autoDismissDelay : 5000,
11110        /**
11111         * @cfg {Boolean} animate
11112         * True to turn on fade animation. Defaults to false (ClearType/scrollbar flicker issues in IE7).
11113         */
11114        animate : false,
11115
11116        /**
11117         * @cfg {String} title
11118         * Title text to display (defaults to '').  This can be any valid HTML markup.
11119         */
11120         title: '',
11121        /**
11122         * @cfg {String} text
11123         * Body text to display (defaults to '').  This can be any valid HTML markup.
11124         */
11125         text : '',
11126        /**
11127         * @cfg {String} cls
11128         * A CSS class to apply to the base quick tip element (defaults to '').
11129         */
11130         cls : '',
11131        /**
11132         * @cfg {Number} width
11133         * Width in pixels of the quick tip (defaults to auto).  Width will be ignored if it exceeds the bounds of
11134         * minWidth or maxWidth.
11135         */
11136         width : null,
11137
11138     /**
11139      * Initialize and enable QuickTips for first use.  This should be called once before the first attempt to access
11140      * or display QuickTips in a page.
11141      */
11142        init : function(){
11143           tm = Roo.QuickTips;
11144           cfg = tm.tagConfig;
11145           if(!inited){
11146               if(!Roo.isReady){ // allow calling of init() before onReady
11147                   Roo.onReady(Roo.QuickTips.init, Roo.QuickTips);
11148                   return;
11149               }
11150               el = new Roo.Layer({cls:"x-tip", shadow:"drop", shim: true, constrain:true, shadowOffset:4});
11151               el.fxDefaults = {stopFx: true};
11152               // maximum custom styling
11153               //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>');
11154               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>');              
11155               tipTitle = el.child('h3');
11156               tipTitle.enableDisplayMode("block");
11157               tipBody = el.child('div.x-tip-bd');
11158               tipBodyText = el.child('div.x-tip-bd-inner');
11159               //bdLeft = el.child('div.x-tip-bd-left');
11160               //bdRight = el.child('div.x-tip-bd-right');
11161               close = el.child('div.x-tip-close');
11162               close.enableDisplayMode("block");
11163               close.on("click", hide);
11164               var d = Roo.get(document);
11165               d.on("mousedown", onDown);
11166               d.on("mouseover", onOver);
11167               d.on("mouseout", onOut);
11168               d.on("mousemove", onMove);
11169               esc = d.addKeyListener(27, hide);
11170               esc.disable();
11171               if(Roo.dd.DD){
11172                   dd = el.initDD("default", null, {
11173                       onDrag : function(){
11174                           el.sync();  
11175                       }
11176                   });
11177                   dd.setHandleElId(tipTitle.id);
11178                   dd.lock();
11179               }
11180               inited = true;
11181           }
11182           this.enable(); 
11183        },
11184
11185     /**
11186      * Configures a new quick tip instance and assigns it to a target element.  The following config options
11187      * are supported:
11188      * <pre>
11189 Property    Type                   Description
11190 ----------  ---------------------  ------------------------------------------------------------------------
11191 target      Element/String/Array   An Element, id or array of ids that this quick tip should be tied to
11192      * </ul>
11193      * @param {Object} config The config object
11194      */
11195        register : function(config){
11196            var cs = config instanceof Array ? config : arguments;
11197            for(var i = 0, len = cs.length; i < len; i++) {
11198                var c = cs[i];
11199                var target = c.target;
11200                if(target){
11201                    if(target instanceof Array){
11202                        for(var j = 0, jlen = target.length; j < jlen; j++){
11203                            tagEls[target[j]] = c;
11204                        }
11205                    }else{
11206                        tagEls[typeof target == 'string' ? target : Roo.id(target)] = c;
11207                    }
11208                }
11209            }
11210        },
11211
11212     /**
11213      * Removes this quick tip from its element and destroys it.
11214      * @param {String/HTMLElement/Element} el The element from which the quick tip is to be removed.
11215      */
11216        unregister : function(el){
11217            delete tagEls[Roo.id(el)];
11218        },
11219
11220     /**
11221      * Enable this quick tip.
11222      */
11223        enable : function(){
11224            if(inited && disabled){
11225                locks.pop();
11226                if(locks.length < 1){
11227                    disabled = false;
11228                }
11229            }
11230        },
11231
11232     /**
11233      * Disable this quick tip.
11234      */
11235        disable : function(){
11236           disabled = true;
11237           clearTimeout(showProc);
11238           clearTimeout(hideProc);
11239           clearTimeout(dismissProc);
11240           if(ce){
11241               hide(true);
11242           }
11243           locks.push(1);
11244        },
11245
11246     /**
11247      * Returns true if the quick tip is enabled, else false.
11248      */
11249        isEnabled : function(){
11250             return !disabled;
11251        },
11252
11253         // private
11254        tagConfig : {
11255            namespace : "roo", // was ext?? this may break..
11256            alt_namespace : "ext",
11257            attribute : "qtip",
11258            width : "width",
11259            target : "target",
11260            title : "qtitle",
11261            hide : "hide",
11262            cls : "qclass"
11263        }
11264    };
11265 }();
11266
11267 // backwards compat
11268 Roo.QuickTips.tips = Roo.QuickTips.register;/*
11269  * Based on:
11270  * Ext JS Library 1.1.1
11271  * Copyright(c) 2006-2007, Ext JS, LLC.
11272  *
11273  * Originally Released Under LGPL - original licence link has changed is not relivant.
11274  *
11275  * Fork - LGPL
11276  * <script type="text/javascript">
11277  */
11278  
11279
11280 /**
11281  * @class Roo.tree.TreePanel
11282  * @extends Roo.data.Tree
11283  * @cfg {Roo.tree.TreeNode} root The root node
11284  * @cfg {Boolean} rootVisible false to hide the root node (defaults to true)
11285  * @cfg {Boolean} lines false to disable tree lines (defaults to true)
11286  * @cfg {Boolean} enableDD true to enable drag and drop
11287  * @cfg {Boolean} enableDrag true to enable just drag
11288  * @cfg {Boolean} enableDrop true to enable just drop
11289  * @cfg {Object} dragConfig Custom config to pass to the {@link Roo.tree.TreeDragZone} instance
11290  * @cfg {Object} dropConfig Custom config to pass to the {@link Roo.tree.TreeDropZone} instance
11291  * @cfg {String} ddGroup The DD group this TreePanel belongs to
11292  * @cfg {String} ddAppendOnly True if the tree should only allow append drops (use for trees which are sorted)
11293  * @cfg {Boolean} ddScroll true to enable YUI body scrolling
11294  * @cfg {Boolean} containerScroll true to register this container with ScrollManager
11295  * @cfg {Boolean} hlDrop false to disable node highlight on drop (defaults to the value of Roo.enableFx)
11296  * @cfg {String} hlColor The color of the node highlight (defaults to C3DAF9)
11297  * @cfg {Boolean} animate true to enable animated expand/collapse (defaults to the value of Roo.enableFx)
11298  * @cfg {Boolean} singleExpand true if only 1 node per branch may be expanded
11299  * @cfg {Boolean} selModel A tree selection model to use with this TreePanel (defaults to a {@link Roo.tree.DefaultSelectionModel})
11300  * @cfg {Roo.tree.TreeLoader} loader A TreeLoader for use with this TreePanel
11301  * @cfg {Roo.tree.TreeEditor} editor The TreeEditor to display when clicked.
11302  * @cfg {String} pathSeparator The token used to separate sub-paths in path strings (defaults to '/')
11303  * @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>
11304  * @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>
11305  * 
11306  * @constructor
11307  * @param {String/HTMLElement/Element} el The container element
11308  * @param {Object} config
11309  */
11310 Roo.tree.TreePanel = function(el, config){
11311     var root = false;
11312     var loader = false;
11313     if (config.root) {
11314         root = config.root;
11315         delete config.root;
11316     }
11317     if (config.loader) {
11318         loader = config.loader;
11319         delete config.loader;
11320     }
11321     
11322     Roo.apply(this, config);
11323     Roo.tree.TreePanel.superclass.constructor.call(this);
11324     this.el = Roo.get(el);
11325     this.el.addClass('x-tree');
11326     //console.log(root);
11327     if (root) {
11328         this.setRootNode( Roo.factory(root, Roo.tree));
11329     }
11330     if (loader) {
11331         this.loader = Roo.factory(loader, Roo.tree);
11332     }
11333    /**
11334     * Read-only. The id of the container element becomes this TreePanel's id.
11335     */
11336     this.id = this.el.id;
11337     this.addEvents({
11338         /**
11339         * @event beforeload
11340         * Fires before a node is loaded, return false to cancel
11341         * @param {Node} node The node being loaded
11342         */
11343         "beforeload" : true,
11344         /**
11345         * @event load
11346         * Fires when a node is loaded
11347         * @param {Node} node The node that was loaded
11348         */
11349         "load" : true,
11350         /**
11351         * @event textchange
11352         * Fires when the text for a node is changed
11353         * @param {Node} node The node
11354         * @param {String} text The new text
11355         * @param {String} oldText The old text
11356         */
11357         "textchange" : true,
11358         /**
11359         * @event beforeexpand
11360         * Fires before a node is expanded, return false to cancel.
11361         * @param {Node} node The node
11362         * @param {Boolean} deep
11363         * @param {Boolean} anim
11364         */
11365         "beforeexpand" : true,
11366         /**
11367         * @event beforecollapse
11368         * Fires before a node is collapsed, return false to cancel.
11369         * @param {Node} node The node
11370         * @param {Boolean} deep
11371         * @param {Boolean} anim
11372         */
11373         "beforecollapse" : true,
11374         /**
11375         * @event expand
11376         * Fires when a node is expanded
11377         * @param {Node} node The node
11378         */
11379         "expand" : true,
11380         /**
11381         * @event disabledchange
11382         * Fires when the disabled status of a node changes
11383         * @param {Node} node The node
11384         * @param {Boolean} disabled
11385         */
11386         "disabledchange" : true,
11387         /**
11388         * @event collapse
11389         * Fires when a node is collapsed
11390         * @param {Node} node The node
11391         */
11392         "collapse" : true,
11393         /**
11394         * @event beforeclick
11395         * Fires before click processing on a node. Return false to cancel the default action.
11396         * @param {Node} node The node
11397         * @param {Roo.EventObject} e The event object
11398         */
11399         "beforeclick":true,
11400         /**
11401         * @event checkchange
11402         * Fires when a node with a checkbox's checked property changes
11403         * @param {Node} this This node
11404         * @param {Boolean} checked
11405         */
11406         "checkchange":true,
11407         /**
11408         * @event click
11409         * Fires when a node is clicked
11410         * @param {Node} node The node
11411         * @param {Roo.EventObject} e The event object
11412         */
11413         "click":true,
11414         /**
11415         * @event dblclick
11416         * Fires when a node is double clicked
11417         * @param {Node} node The node
11418         * @param {Roo.EventObject} e The event object
11419         */
11420         "dblclick":true,
11421         /**
11422         * @event contextmenu
11423         * Fires when a node is right clicked
11424         * @param {Node} node The node
11425         * @param {Roo.EventObject} e The event object
11426         */
11427         "contextmenu":true,
11428         /**
11429         * @event beforechildrenrendered
11430         * Fires right before the child nodes for a node are rendered
11431         * @param {Node} node The node
11432         */
11433         "beforechildrenrendered":true,
11434         /**
11435         * @event startdrag
11436         * Fires when a node starts being dragged
11437         * @param {Roo.tree.TreePanel} this
11438         * @param {Roo.tree.TreeNode} node
11439         * @param {event} e The raw browser event
11440         */ 
11441        "startdrag" : true,
11442        /**
11443         * @event enddrag
11444         * Fires when a drag operation is complete
11445         * @param {Roo.tree.TreePanel} this
11446         * @param {Roo.tree.TreeNode} node
11447         * @param {event} e The raw browser event
11448         */
11449        "enddrag" : true,
11450        /**
11451         * @event dragdrop
11452         * Fires when a dragged node is dropped on a valid DD target
11453         * @param {Roo.tree.TreePanel} this
11454         * @param {Roo.tree.TreeNode} node
11455         * @param {DD} dd The dd it was dropped on
11456         * @param {event} e The raw browser event
11457         */
11458        "dragdrop" : true,
11459        /**
11460         * @event beforenodedrop
11461         * Fires when a DD object is dropped on a node in this tree for preprocessing. Return false to cancel the drop. The dropEvent
11462         * passed to handlers has the following properties:<br />
11463         * <ul style="padding:5px;padding-left:16px;">
11464         * <li>tree - The TreePanel</li>
11465         * <li>target - The node being targeted for the drop</li>
11466         * <li>data - The drag data from the drag source</li>
11467         * <li>point - The point of the drop - append, above or below</li>
11468         * <li>source - The drag source</li>
11469         * <li>rawEvent - Raw mouse event</li>
11470         * <li>dropNode - Drop node(s) provided by the source <b>OR</b> you can supply node(s)
11471         * to be inserted by setting them on this object.</li>
11472         * <li>cancel - Set this to true to cancel the drop.</li>
11473         * </ul>
11474         * @param {Object} dropEvent
11475         */
11476        "beforenodedrop" : true,
11477        /**
11478         * @event nodedrop
11479         * Fires after a DD object is dropped on a node in this tree. The dropEvent
11480         * passed to handlers has the following properties:<br />
11481         * <ul style="padding:5px;padding-left:16px;">
11482         * <li>tree - The TreePanel</li>
11483         * <li>target - The node being targeted for the drop</li>
11484         * <li>data - The drag data from the drag source</li>
11485         * <li>point - The point of the drop - append, above or below</li>
11486         * <li>source - The drag source</li>
11487         * <li>rawEvent - Raw mouse event</li>
11488         * <li>dropNode - Dropped node(s).</li>
11489         * </ul>
11490         * @param {Object} dropEvent
11491         */
11492        "nodedrop" : true,
11493         /**
11494         * @event nodedragover
11495         * Fires when a tree node is being targeted for a drag drop, return false to signal drop not allowed. The dragOverEvent
11496         * passed to handlers has the following properties:<br />
11497         * <ul style="padding:5px;padding-left:16px;">
11498         * <li>tree - The TreePanel</li>
11499         * <li>target - The node being targeted for the drop</li>
11500         * <li>data - The drag data from the drag source</li>
11501         * <li>point - The point of the drop - append, above or below</li>
11502         * <li>source - The drag source</li>
11503         * <li>rawEvent - Raw mouse event</li>
11504         * <li>dropNode - Drop node(s) provided by the source.</li>
11505         * <li>cancel - Set this to true to signal drop not allowed.</li>
11506         * </ul>
11507         * @param {Object} dragOverEvent
11508         */
11509        "nodedragover" : true,
11510        /**
11511         * @event appendnode
11512         * Fires when append node to the tree
11513         * @param {Roo.tree.TreePanel} this
11514         * @param {Roo.tree.TreeNode} node
11515         * @param {Number} index The index of the newly appended node
11516         */
11517        "appendnode" : true
11518         
11519     });
11520     if(this.singleExpand){
11521        this.on("beforeexpand", this.restrictExpand, this);
11522     }
11523     if (this.editor) {
11524         this.editor.tree = this;
11525         this.editor = Roo.factory(this.editor, Roo.tree);
11526     }
11527     
11528     if (this.selModel) {
11529         this.selModel = Roo.factory(this.selModel, Roo.tree);
11530     }
11531    
11532 };
11533 Roo.extend(Roo.tree.TreePanel, Roo.data.Tree, {
11534     rootVisible : true,
11535     animate: Roo.enableFx,
11536     lines : true,
11537     enableDD : false,
11538     hlDrop : Roo.enableFx,
11539   
11540     renderer: false,
11541     
11542     rendererTip: false,
11543     // private
11544     restrictExpand : function(node){
11545         var p = node.parentNode;
11546         if(p){
11547             if(p.expandedChild && p.expandedChild.parentNode == p){
11548                 p.expandedChild.collapse();
11549             }
11550             p.expandedChild = node;
11551         }
11552     },
11553
11554     // private override
11555     setRootNode : function(node){
11556         Roo.tree.TreePanel.superclass.setRootNode.call(this, node);
11557         if(!this.rootVisible){
11558             node.ui = new Roo.tree.RootTreeNodeUI(node);
11559         }
11560         return node;
11561     },
11562
11563     /**
11564      * Returns the container element for this TreePanel
11565      */
11566     getEl : function(){
11567         return this.el;
11568     },
11569
11570     /**
11571      * Returns the default TreeLoader for this TreePanel
11572      */
11573     getLoader : function(){
11574         return this.loader;
11575     },
11576
11577     /**
11578      * Expand all nodes
11579      */
11580     expandAll : function(){
11581         this.root.expand(true);
11582     },
11583
11584     /**
11585      * Collapse all nodes
11586      */
11587     collapseAll : function(){
11588         this.root.collapse(true);
11589     },
11590
11591     /**
11592      * Returns the selection model used by this TreePanel
11593      */
11594     getSelectionModel : function(){
11595         if(!this.selModel){
11596             this.selModel = new Roo.tree.DefaultSelectionModel();
11597         }
11598         return this.selModel;
11599     },
11600
11601     /**
11602      * Retrieve an array of checked nodes, or an array of a specific attribute of checked nodes (e.g. "id")
11603      * @param {String} attribute (optional) Defaults to null (return the actual nodes)
11604      * @param {TreeNode} startNode (optional) The node to start from, defaults to the root
11605      * @return {Array}
11606      */
11607     getChecked : function(a, startNode){
11608         startNode = startNode || this.root;
11609         var r = [];
11610         var f = function(){
11611             if(this.attributes.checked){
11612                 r.push(!a ? this : (a == 'id' ? this.id : this.attributes[a]));
11613             }
11614         }
11615         startNode.cascade(f);
11616         return r;
11617     },
11618
11619     /**
11620      * Expands a specified path in this TreePanel. A path can be retrieved from a node with {@link Roo.data.Node#getPath}
11621      * @param {String} path
11622      * @param {String} attr (optional) The attribute used in the path (see {@link Roo.data.Node#getPath} for more info)
11623      * @param {Function} callback (optional) The callback to call when the expand is complete. The callback will be called with
11624      * (bSuccess, oLastNode) where bSuccess is if the expand was successful and oLastNode is the last node that was expanded.
11625      */
11626     expandPath : function(path, attr, callback){
11627         attr = attr || "id";
11628         var keys = path.split(this.pathSeparator);
11629         var curNode = this.root;
11630         if(curNode.attributes[attr] != keys[1]){ // invalid root
11631             if(callback){
11632                 callback(false, null);
11633             }
11634             return;
11635         }
11636         var index = 1;
11637         var f = function(){
11638             if(++index == keys.length){
11639                 if(callback){
11640                     callback(true, curNode);
11641                 }
11642                 return;
11643             }
11644             var c = curNode.findChild(attr, keys[index]);
11645             if(!c){
11646                 if(callback){
11647                     callback(false, curNode);
11648                 }
11649                 return;
11650             }
11651             curNode = c;
11652             c.expand(false, false, f);
11653         };
11654         curNode.expand(false, false, f);
11655     },
11656
11657     /**
11658      * Selects the node in this tree at the specified path. A path can be retrieved from a node with {@link Roo.data.Node#getPath}
11659      * @param {String} path
11660      * @param {String} attr (optional) The attribute used in the path (see {@link Roo.data.Node#getPath} for more info)
11661      * @param {Function} callback (optional) The callback to call when the selection is complete. The callback will be called with
11662      * (bSuccess, oSelNode) where bSuccess is if the selection was successful and oSelNode is the selected node.
11663      */
11664     selectPath : function(path, attr, callback){
11665         attr = attr || "id";
11666         var keys = path.split(this.pathSeparator);
11667         var v = keys.pop();
11668         if(keys.length > 0){
11669             var f = function(success, node){
11670                 if(success && node){
11671                     var n = node.findChild(attr, v);
11672                     if(n){
11673                         n.select();
11674                         if(callback){
11675                             callback(true, n);
11676                         }
11677                     }else if(callback){
11678                         callback(false, n);
11679                     }
11680                 }else{
11681                     if(callback){
11682                         callback(false, n);
11683                     }
11684                 }
11685             };
11686             this.expandPath(keys.join(this.pathSeparator), attr, f);
11687         }else{
11688             this.root.select();
11689             if(callback){
11690                 callback(true, this.root);
11691             }
11692         }
11693     },
11694
11695     getTreeEl : function(){
11696         return this.el;
11697     },
11698
11699     /**
11700      * Trigger rendering of this TreePanel
11701      */
11702     render : function(){
11703         if (this.innerCt) {
11704             return this; // stop it rendering more than once!!
11705         }
11706         
11707         this.innerCt = this.el.createChild({tag:"ul",
11708                cls:"x-tree-root-ct " +
11709                (this.lines ? "x-tree-lines" : "x-tree-no-lines")});
11710
11711         if(this.containerScroll){
11712             Roo.dd.ScrollManager.register(this.el);
11713         }
11714         if((this.enableDD || this.enableDrop) && !this.dropZone){
11715            /**
11716             * The dropZone used by this tree if drop is enabled
11717             * @type Roo.tree.TreeDropZone
11718             */
11719              this.dropZone = new Roo.tree.TreeDropZone(this, this.dropConfig || {
11720                ddGroup: this.ddGroup || "TreeDD", appendOnly: this.ddAppendOnly === true
11721            });
11722         }
11723         if((this.enableDD || this.enableDrag) && !this.dragZone){
11724            /**
11725             * The dragZone used by this tree if drag is enabled
11726             * @type Roo.tree.TreeDragZone
11727             */
11728             this.dragZone = new Roo.tree.TreeDragZone(this, this.dragConfig || {
11729                ddGroup: this.ddGroup || "TreeDD",
11730                scroll: this.ddScroll
11731            });
11732         }
11733         this.getSelectionModel().init(this);
11734         if (!this.root) {
11735             Roo.log("ROOT not set in tree");
11736             return this;
11737         }
11738         this.root.render();
11739         if(!this.rootVisible){
11740             this.root.renderChildren();
11741         }
11742         return this;
11743     }
11744 });/*
11745  * Based on:
11746  * Ext JS Library 1.1.1
11747  * Copyright(c) 2006-2007, Ext JS, LLC.
11748  *
11749  * Originally Released Under LGPL - original licence link has changed is not relivant.
11750  *
11751  * Fork - LGPL
11752  * <script type="text/javascript">
11753  */
11754  
11755
11756 /**
11757  * @class Roo.tree.DefaultSelectionModel
11758  * @extends Roo.util.Observable
11759  * The default single selection for a TreePanel.
11760  * @param {Object} cfg Configuration
11761  */
11762 Roo.tree.DefaultSelectionModel = function(cfg){
11763    this.selNode = null;
11764    
11765    
11766    
11767    this.addEvents({
11768        /**
11769         * @event selectionchange
11770         * Fires when the selected node changes
11771         * @param {DefaultSelectionModel} this
11772         * @param {TreeNode} node the new selection
11773         */
11774        "selectionchange" : true,
11775
11776        /**
11777         * @event beforeselect
11778         * Fires before the selected node changes, return false to cancel the change
11779         * @param {DefaultSelectionModel} this
11780         * @param {TreeNode} node the new selection
11781         * @param {TreeNode} node the old selection
11782         */
11783        "beforeselect" : true
11784    });
11785    
11786     Roo.tree.DefaultSelectionModel.superclass.constructor.call(this,cfg);
11787 };
11788
11789 Roo.extend(Roo.tree.DefaultSelectionModel, Roo.util.Observable, {
11790     init : function(tree){
11791         this.tree = tree;
11792         tree.getTreeEl().on("keydown", this.onKeyDown, this);
11793         tree.on("click", this.onNodeClick, this);
11794     },
11795     
11796     onNodeClick : function(node, e){
11797         if (e.ctrlKey && this.selNode == node)  {
11798             this.unselect(node);
11799             return;
11800         }
11801         this.select(node);
11802     },
11803     
11804     /**
11805      * Select a node.
11806      * @param {TreeNode} node The node to select
11807      * @return {TreeNode} The selected node
11808      */
11809     select : function(node){
11810         var last = this.selNode;
11811         if(last != node && this.fireEvent('beforeselect', this, node, last) !== false){
11812             if(last){
11813                 last.ui.onSelectedChange(false);
11814             }
11815             this.selNode = node;
11816             node.ui.onSelectedChange(true);
11817             this.fireEvent("selectionchange", this, node, last);
11818         }
11819         return node;
11820     },
11821     
11822     /**
11823      * Deselect a node.
11824      * @param {TreeNode} node The node to unselect
11825      */
11826     unselect : function(node){
11827         if(this.selNode == node){
11828             this.clearSelections();
11829         }    
11830     },
11831     
11832     /**
11833      * Clear all selections
11834      */
11835     clearSelections : function(){
11836         var n = this.selNode;
11837         if(n){
11838             n.ui.onSelectedChange(false);
11839             this.selNode = null;
11840             this.fireEvent("selectionchange", this, null);
11841         }
11842         return n;
11843     },
11844     
11845     /**
11846      * Get the selected node
11847      * @return {TreeNode} The selected node
11848      */
11849     getSelectedNode : function(){
11850         return this.selNode;    
11851     },
11852     
11853     /**
11854      * Returns true if the node is selected
11855      * @param {TreeNode} node The node to check
11856      * @return {Boolean}
11857      */
11858     isSelected : function(node){
11859         return this.selNode == node;  
11860     },
11861
11862     /**
11863      * Selects the node above the selected node in the tree, intelligently walking the nodes
11864      * @return TreeNode The new selection
11865      */
11866     selectPrevious : function(){
11867         var s = this.selNode || this.lastSelNode;
11868         if(!s){
11869             return null;
11870         }
11871         var ps = s.previousSibling;
11872         if(ps){
11873             if(!ps.isExpanded() || ps.childNodes.length < 1){
11874                 return this.select(ps);
11875             } else{
11876                 var lc = ps.lastChild;
11877                 while(lc && lc.isExpanded() && lc.childNodes.length > 0){
11878                     lc = lc.lastChild;
11879                 }
11880                 return this.select(lc);
11881             }
11882         } else if(s.parentNode && (this.tree.rootVisible || !s.parentNode.isRoot)){
11883             return this.select(s.parentNode);
11884         }
11885         return null;
11886     },
11887
11888     /**
11889      * Selects the node above the selected node in the tree, intelligently walking the nodes
11890      * @return TreeNode The new selection
11891      */
11892     selectNext : function(){
11893         var s = this.selNode || this.lastSelNode;
11894         if(!s){
11895             return null;
11896         }
11897         if(s.firstChild && s.isExpanded()){
11898              return this.select(s.firstChild);
11899          }else if(s.nextSibling){
11900              return this.select(s.nextSibling);
11901          }else if(s.parentNode){
11902             var newS = null;
11903             s.parentNode.bubble(function(){
11904                 if(this.nextSibling){
11905                     newS = this.getOwnerTree().selModel.select(this.nextSibling);
11906                     return false;
11907                 }
11908             });
11909             return newS;
11910          }
11911         return null;
11912     },
11913
11914     onKeyDown : function(e){
11915         var s = this.selNode || this.lastSelNode;
11916         // undesirable, but required
11917         var sm = this;
11918         if(!s){
11919             return;
11920         }
11921         var k = e.getKey();
11922         switch(k){
11923              case e.DOWN:
11924                  e.stopEvent();
11925                  this.selectNext();
11926              break;
11927              case e.UP:
11928                  e.stopEvent();
11929                  this.selectPrevious();
11930              break;
11931              case e.RIGHT:
11932                  e.preventDefault();
11933                  if(s.hasChildNodes()){
11934                      if(!s.isExpanded()){
11935                          s.expand();
11936                      }else if(s.firstChild){
11937                          this.select(s.firstChild, e);
11938                      }
11939                  }
11940              break;
11941              case e.LEFT:
11942                  e.preventDefault();
11943                  if(s.hasChildNodes() && s.isExpanded()){
11944                      s.collapse();
11945                  }else if(s.parentNode && (this.tree.rootVisible || s.parentNode != this.tree.getRootNode())){
11946                      this.select(s.parentNode, e);
11947                  }
11948              break;
11949         };
11950     }
11951 });
11952
11953 /**
11954  * @class Roo.tree.MultiSelectionModel
11955  * @extends Roo.util.Observable
11956  * Multi selection for a TreePanel.
11957  * @param {Object} cfg Configuration
11958  */
11959 Roo.tree.MultiSelectionModel = function(){
11960    this.selNodes = [];
11961    this.selMap = {};
11962    this.addEvents({
11963        /**
11964         * @event selectionchange
11965         * Fires when the selected nodes change
11966         * @param {MultiSelectionModel} this
11967         * @param {Array} nodes Array of the selected nodes
11968         */
11969        "selectionchange" : true
11970    });
11971    Roo.tree.MultiSelectionModel.superclass.constructor.call(this,cfg);
11972    
11973 };
11974
11975 Roo.extend(Roo.tree.MultiSelectionModel, Roo.util.Observable, {
11976     init : function(tree){
11977         this.tree = tree;
11978         tree.getTreeEl().on("keydown", this.onKeyDown, this);
11979         tree.on("click", this.onNodeClick, this);
11980     },
11981     
11982     onNodeClick : function(node, e){
11983         this.select(node, e, e.ctrlKey);
11984     },
11985     
11986     /**
11987      * Select a node.
11988      * @param {TreeNode} node The node to select
11989      * @param {EventObject} e (optional) An event associated with the selection
11990      * @param {Boolean} keepExisting True to retain existing selections
11991      * @return {TreeNode} The selected node
11992      */
11993     select : function(node, e, keepExisting){
11994         if(keepExisting !== true){
11995             this.clearSelections(true);
11996         }
11997         if(this.isSelected(node)){
11998             this.lastSelNode = node;
11999             return node;
12000         }
12001         this.selNodes.push(node);
12002         this.selMap[node.id] = node;
12003         this.lastSelNode = node;
12004         node.ui.onSelectedChange(true);
12005         this.fireEvent("selectionchange", this, this.selNodes);
12006         return node;
12007     },
12008     
12009     /**
12010      * Deselect a node.
12011      * @param {TreeNode} node The node to unselect
12012      */
12013     unselect : function(node){
12014         if(this.selMap[node.id]){
12015             node.ui.onSelectedChange(false);
12016             var sn = this.selNodes;
12017             var index = -1;
12018             if(sn.indexOf){
12019                 index = sn.indexOf(node);
12020             }else{
12021                 for(var i = 0, len = sn.length; i < len; i++){
12022                     if(sn[i] == node){
12023                         index = i;
12024                         break;
12025                     }
12026                 }
12027             }
12028             if(index != -1){
12029                 this.selNodes.splice(index, 1);
12030             }
12031             delete this.selMap[node.id];
12032             this.fireEvent("selectionchange", this, this.selNodes);
12033         }
12034     },
12035     
12036     /**
12037      * Clear all selections
12038      */
12039     clearSelections : function(suppressEvent){
12040         var sn = this.selNodes;
12041         if(sn.length > 0){
12042             for(var i = 0, len = sn.length; i < len; i++){
12043                 sn[i].ui.onSelectedChange(false);
12044             }
12045             this.selNodes = [];
12046             this.selMap = {};
12047             if(suppressEvent !== true){
12048                 this.fireEvent("selectionchange", this, this.selNodes);
12049             }
12050         }
12051     },
12052     
12053     /**
12054      * Returns true if the node is selected
12055      * @param {TreeNode} node The node to check
12056      * @return {Boolean}
12057      */
12058     isSelected : function(node){
12059         return this.selMap[node.id] ? true : false;  
12060     },
12061     
12062     /**
12063      * Returns an array of the selected nodes
12064      * @return {Array}
12065      */
12066     getSelectedNodes : function(){
12067         return this.selNodes;    
12068     },
12069
12070     onKeyDown : Roo.tree.DefaultSelectionModel.prototype.onKeyDown,
12071
12072     selectNext : Roo.tree.DefaultSelectionModel.prototype.selectNext,
12073
12074     selectPrevious : Roo.tree.DefaultSelectionModel.prototype.selectPrevious
12075 });/*
12076  * Based on:
12077  * Ext JS Library 1.1.1
12078  * Copyright(c) 2006-2007, Ext JS, LLC.
12079  *
12080  * Originally Released Under LGPL - original licence link has changed is not relivant.
12081  *
12082  * Fork - LGPL
12083  * <script type="text/javascript">
12084  */
12085  
12086 /**
12087  * @class Roo.tree.TreeNode
12088  * @extends Roo.data.Node
12089  * @cfg {String} text The text for this node
12090  * @cfg {Boolean} expanded true to start the node expanded
12091  * @cfg {Boolean} allowDrag false to make this node undraggable if DD is on (defaults to true)
12092  * @cfg {Boolean} allowDrop false if this node cannot be drop on
12093  * @cfg {Boolean} disabled true to start the node disabled
12094  * @cfg {String} icon The path to an icon for the node. The preferred way to do this
12095  *    is to use the cls or iconCls attributes and add the icon via a CSS background image.
12096  * @cfg {String} cls A css class to be added to the node
12097  * @cfg {String} iconCls A css class to be added to the nodes icon element for applying css background images
12098  * @cfg {String} href URL of the link used for the node (defaults to #)
12099  * @cfg {String} hrefTarget target frame for the link
12100  * @cfg {String} qtip An Ext QuickTip for the node
12101  * @cfg {String} qtipCfg An Ext QuickTip config for the node (used instead of qtip)
12102  * @cfg {Boolean} singleClickExpand True for single click expand on this node
12103  * @cfg {Function} uiProvider A UI <b>class</b> to use for this node (defaults to Roo.tree.TreeNodeUI)
12104  * @cfg {Boolean} checked True to render a checked checkbox for this node, false to render an unchecked checkbox
12105  * (defaults to undefined with no checkbox rendered)
12106  * @constructor
12107  * @param {Object/String} attributes The attributes/config for the node or just a string with the text for the node
12108  */
12109 Roo.tree.TreeNode = function(attributes){
12110     attributes = attributes || {};
12111     if(typeof attributes == "string"){
12112         attributes = {text: attributes};
12113     }
12114     this.childrenRendered = false;
12115     this.rendered = false;
12116     Roo.tree.TreeNode.superclass.constructor.call(this, attributes);
12117     this.expanded = attributes.expanded === true;
12118     this.isTarget = attributes.isTarget !== false;
12119     this.draggable = attributes.draggable !== false && attributes.allowDrag !== false;
12120     this.allowChildren = attributes.allowChildren !== false && attributes.allowDrop !== false;
12121
12122     /**
12123      * Read-only. The text for this node. To change it use setText().
12124      * @type String
12125      */
12126     this.text = attributes.text;
12127     /**
12128      * True if this node is disabled.
12129      * @type Boolean
12130      */
12131     this.disabled = attributes.disabled === true;
12132
12133     this.addEvents({
12134         /**
12135         * @event textchange
12136         * Fires when the text for this node is changed
12137         * @param {Node} this This node
12138         * @param {String} text The new text
12139         * @param {String} oldText The old text
12140         */
12141         "textchange" : true,
12142         /**
12143         * @event beforeexpand
12144         * Fires before this node is expanded, return false to cancel.
12145         * @param {Node} this This node
12146         * @param {Boolean} deep
12147         * @param {Boolean} anim
12148         */
12149         "beforeexpand" : true,
12150         /**
12151         * @event beforecollapse
12152         * Fires before this node is collapsed, return false to cancel.
12153         * @param {Node} this This node
12154         * @param {Boolean} deep
12155         * @param {Boolean} anim
12156         */
12157         "beforecollapse" : true,
12158         /**
12159         * @event expand
12160         * Fires when this node is expanded
12161         * @param {Node} this This node
12162         */
12163         "expand" : true,
12164         /**
12165         * @event disabledchange
12166         * Fires when the disabled status of this node changes
12167         * @param {Node} this This node
12168         * @param {Boolean} disabled
12169         */
12170         "disabledchange" : true,
12171         /**
12172         * @event collapse
12173         * Fires when this node is collapsed
12174         * @param {Node} this This node
12175         */
12176         "collapse" : true,
12177         /**
12178         * @event beforeclick
12179         * Fires before click processing. Return false to cancel the default action.
12180         * @param {Node} this This node
12181         * @param {Roo.EventObject} e The event object
12182         */
12183         "beforeclick":true,
12184         /**
12185         * @event checkchange
12186         * Fires when a node with a checkbox's checked property changes
12187         * @param {Node} this This node
12188         * @param {Boolean} checked
12189         */
12190         "checkchange":true,
12191         /**
12192         * @event click
12193         * Fires when this node is clicked
12194         * @param {Node} this This node
12195         * @param {Roo.EventObject} e The event object
12196         */
12197         "click":true,
12198         /**
12199         * @event dblclick
12200         * Fires when this node is double clicked
12201         * @param {Node} this This node
12202         * @param {Roo.EventObject} e The event object
12203         */
12204         "dblclick":true,
12205         /**
12206         * @event contextmenu
12207         * Fires when this node is right clicked
12208         * @param {Node} this This node
12209         * @param {Roo.EventObject} e The event object
12210         */
12211         "contextmenu":true,
12212         /**
12213         * @event beforechildrenrendered
12214         * Fires right before the child nodes for this node are rendered
12215         * @param {Node} this This node
12216         */
12217         "beforechildrenrendered":true
12218     });
12219
12220     var uiClass = this.attributes.uiProvider || Roo.tree.TreeNodeUI;
12221
12222     /**
12223      * Read-only. The UI for this node
12224      * @type TreeNodeUI
12225      */
12226     this.ui = new uiClass(this);
12227     
12228     // finally support items[]
12229     if (typeof(this.attributes.items) == 'undefined' || !this.attributes.items) {
12230         return;
12231     }
12232     
12233     
12234     Roo.each(this.attributes.items, function(c) {
12235         this.appendChild(Roo.factory(c,Roo.Tree));
12236     }, this);
12237     delete this.attributes.items;
12238     
12239     
12240     
12241 };
12242 Roo.extend(Roo.tree.TreeNode, Roo.data.Node, {
12243     preventHScroll: true,
12244     /**
12245      * Returns true if this node is expanded
12246      * @return {Boolean}
12247      */
12248     isExpanded : function(){
12249         return this.expanded;
12250     },
12251
12252     /**
12253      * Returns the UI object for this node
12254      * @return {TreeNodeUI}
12255      */
12256     getUI : function(){
12257         return this.ui;
12258     },
12259
12260     // private override
12261     setFirstChild : function(node){
12262         var of = this.firstChild;
12263         Roo.tree.TreeNode.superclass.setFirstChild.call(this, node);
12264         if(this.childrenRendered && of && node != of){
12265             of.renderIndent(true, true);
12266         }
12267         if(this.rendered){
12268             this.renderIndent(true, true);
12269         }
12270     },
12271
12272     // private override
12273     setLastChild : function(node){
12274         var ol = this.lastChild;
12275         Roo.tree.TreeNode.superclass.setLastChild.call(this, node);
12276         if(this.childrenRendered && ol && node != ol){
12277             ol.renderIndent(true, true);
12278         }
12279         if(this.rendered){
12280             this.renderIndent(true, true);
12281         }
12282     },
12283
12284     // these methods are overridden to provide lazy rendering support
12285     // private override
12286     appendChild : function()
12287     {
12288         var node = Roo.tree.TreeNode.superclass.appendChild.apply(this, arguments);
12289         if(node && this.childrenRendered){
12290             node.render();
12291         }
12292         this.ui.updateExpandIcon();
12293         return node;
12294     },
12295
12296     // private override
12297     removeChild : function(node){
12298         this.ownerTree.getSelectionModel().unselect(node);
12299         Roo.tree.TreeNode.superclass.removeChild.apply(this, arguments);
12300         // if it's been rendered remove dom node
12301         if(this.childrenRendered){
12302             node.ui.remove();
12303         }
12304         if(this.childNodes.length < 1){
12305             this.collapse(false, false);
12306         }else{
12307             this.ui.updateExpandIcon();
12308         }
12309         if(!this.firstChild) {
12310             this.childrenRendered = false;
12311         }
12312         return node;
12313     },
12314
12315     // private override
12316     insertBefore : function(node, refNode){
12317         var newNode = Roo.tree.TreeNode.superclass.insertBefore.apply(this, arguments);
12318         if(newNode && refNode && this.childrenRendered){
12319             node.render();
12320         }
12321         this.ui.updateExpandIcon();
12322         return newNode;
12323     },
12324
12325     /**
12326      * Sets the text for this node
12327      * @param {String} text
12328      */
12329     setText : function(text){
12330         var oldText = this.text;
12331         this.text = text;
12332         this.attributes.text = text;
12333         if(this.rendered){ // event without subscribing
12334             this.ui.onTextChange(this, text, oldText);
12335         }
12336         this.fireEvent("textchange", this, text, oldText);
12337     },
12338
12339     /**
12340      * Triggers selection of this node
12341      */
12342     select : function(){
12343         this.getOwnerTree().getSelectionModel().select(this);
12344     },
12345
12346     /**
12347      * Triggers deselection of this node
12348      */
12349     unselect : function(){
12350         this.getOwnerTree().getSelectionModel().unselect(this);
12351     },
12352
12353     /**
12354      * Returns true if this node is selected
12355      * @return {Boolean}
12356      */
12357     isSelected : function(){
12358         return this.getOwnerTree().getSelectionModel().isSelected(this);
12359     },
12360
12361     /**
12362      * Expand this node.
12363      * @param {Boolean} deep (optional) True to expand all children as well
12364      * @param {Boolean} anim (optional) false to cancel the default animation
12365      * @param {Function} callback (optional) A callback to be called when
12366      * expanding this node completes (does not wait for deep expand to complete).
12367      * Called with 1 parameter, this node.
12368      */
12369     expand : function(deep, anim, callback){
12370         if(!this.expanded){
12371             if(this.fireEvent("beforeexpand", this, deep, anim) === false){
12372                 return;
12373             }
12374             if(!this.childrenRendered){
12375                 this.renderChildren();
12376             }
12377             this.expanded = true;
12378             
12379             if(!this.isHiddenRoot() && (this.getOwnerTree() && this.getOwnerTree().animate && anim !== false) || anim){
12380                 this.ui.animExpand(function(){
12381                     this.fireEvent("expand", this);
12382                     if(typeof callback == "function"){
12383                         callback(this);
12384                     }
12385                     if(deep === true){
12386                         this.expandChildNodes(true);
12387                     }
12388                 }.createDelegate(this));
12389                 return;
12390             }else{
12391                 this.ui.expand();
12392                 this.fireEvent("expand", this);
12393                 if(typeof callback == "function"){
12394                     callback(this);
12395                 }
12396             }
12397         }else{
12398            if(typeof callback == "function"){
12399                callback(this);
12400            }
12401         }
12402         if(deep === true){
12403             this.expandChildNodes(true);
12404         }
12405     },
12406
12407     isHiddenRoot : function(){
12408         return this.isRoot && !this.getOwnerTree().rootVisible;
12409     },
12410
12411     /**
12412      * Collapse this node.
12413      * @param {Boolean} deep (optional) True to collapse all children as well
12414      * @param {Boolean} anim (optional) false to cancel the default animation
12415      */
12416     collapse : function(deep, anim){
12417         if(this.expanded && !this.isHiddenRoot()){
12418             if(this.fireEvent("beforecollapse", this, deep, anim) === false){
12419                 return;
12420             }
12421             this.expanded = false;
12422             if((this.getOwnerTree().animate && anim !== false) || anim){
12423                 this.ui.animCollapse(function(){
12424                     this.fireEvent("collapse", this);
12425                     if(deep === true){
12426                         this.collapseChildNodes(true);
12427                     }
12428                 }.createDelegate(this));
12429                 return;
12430             }else{
12431                 this.ui.collapse();
12432                 this.fireEvent("collapse", this);
12433             }
12434         }
12435         if(deep === true){
12436             var cs = this.childNodes;
12437             for(var i = 0, len = cs.length; i < len; i++) {
12438                 cs[i].collapse(true, false);
12439             }
12440         }
12441     },
12442
12443     // private
12444     delayedExpand : function(delay){
12445         if(!this.expandProcId){
12446             this.expandProcId = this.expand.defer(delay, this);
12447         }
12448     },
12449
12450     // private
12451     cancelExpand : function(){
12452         if(this.expandProcId){
12453             clearTimeout(this.expandProcId);
12454         }
12455         this.expandProcId = false;
12456     },
12457
12458     /**
12459      * Toggles expanded/collapsed state of the node
12460      */
12461     toggle : function(){
12462         if(this.expanded){
12463             this.collapse();
12464         }else{
12465             this.expand();
12466         }
12467     },
12468
12469     /**
12470      * Ensures all parent nodes are expanded
12471      */
12472     ensureVisible : function(callback){
12473         var tree = this.getOwnerTree();
12474         tree.expandPath(this.parentNode.getPath(), false, function(){
12475             tree.getTreeEl().scrollChildIntoView(this.ui.anchor);
12476             Roo.callback(callback);
12477         }.createDelegate(this));
12478     },
12479
12480     /**
12481      * Expand all child nodes
12482      * @param {Boolean} deep (optional) true if the child nodes should also expand their child nodes
12483      */
12484     expandChildNodes : function(deep){
12485         var cs = this.childNodes;
12486         for(var i = 0, len = cs.length; i < len; i++) {
12487                 cs[i].expand(deep);
12488         }
12489     },
12490
12491     /**
12492      * Collapse all child nodes
12493      * @param {Boolean} deep (optional) true if the child nodes should also collapse their child nodes
12494      */
12495     collapseChildNodes : function(deep){
12496         var cs = this.childNodes;
12497         for(var i = 0, len = cs.length; i < len; i++) {
12498                 cs[i].collapse(deep);
12499         }
12500     },
12501
12502     /**
12503      * Disables this node
12504      */
12505     disable : function(){
12506         this.disabled = true;
12507         this.unselect();
12508         if(this.rendered && this.ui.onDisableChange){ // event without subscribing
12509             this.ui.onDisableChange(this, true);
12510         }
12511         this.fireEvent("disabledchange", this, true);
12512     },
12513
12514     /**
12515      * Enables this node
12516      */
12517     enable : function(){
12518         this.disabled = false;
12519         if(this.rendered && this.ui.onDisableChange){ // event without subscribing
12520             this.ui.onDisableChange(this, false);
12521         }
12522         this.fireEvent("disabledchange", this, false);
12523     },
12524
12525     // private
12526     renderChildren : function(suppressEvent){
12527         if(suppressEvent !== false){
12528             this.fireEvent("beforechildrenrendered", this);
12529         }
12530         var cs = this.childNodes;
12531         for(var i = 0, len = cs.length; i < len; i++){
12532             cs[i].render(true);
12533         }
12534         this.childrenRendered = true;
12535     },
12536
12537     // private
12538     sort : function(fn, scope){
12539         Roo.tree.TreeNode.superclass.sort.apply(this, arguments);
12540         if(this.childrenRendered){
12541             var cs = this.childNodes;
12542             for(var i = 0, len = cs.length; i < len; i++){
12543                 cs[i].render(true);
12544             }
12545         }
12546     },
12547
12548     // private
12549     render : function(bulkRender){
12550         this.ui.render(bulkRender);
12551         if(!this.rendered){
12552             this.rendered = true;
12553             if(this.expanded){
12554                 this.expanded = false;
12555                 this.expand(false, false);
12556             }
12557         }
12558     },
12559
12560     // private
12561     renderIndent : function(deep, refresh){
12562         if(refresh){
12563             this.ui.childIndent = null;
12564         }
12565         this.ui.renderIndent();
12566         if(deep === true && this.childrenRendered){
12567             var cs = this.childNodes;
12568             for(var i = 0, len = cs.length; i < len; i++){
12569                 cs[i].renderIndent(true, refresh);
12570             }
12571         }
12572     }
12573 });/*
12574  * Based on:
12575  * Ext JS Library 1.1.1
12576  * Copyright(c) 2006-2007, Ext JS, LLC.
12577  *
12578  * Originally Released Under LGPL - original licence link has changed is not relivant.
12579  *
12580  * Fork - LGPL
12581  * <script type="text/javascript">
12582  */
12583  
12584 /**
12585  * @class Roo.tree.AsyncTreeNode
12586  * @extends Roo.tree.TreeNode
12587  * @cfg {TreeLoader} loader A TreeLoader to be used by this node (defaults to the loader defined on the tree)
12588  * @constructor
12589  * @param {Object/String} attributes The attributes/config for the node or just a string with the text for the node 
12590  */
12591  Roo.tree.AsyncTreeNode = function(config){
12592     this.loaded = false;
12593     this.loading = false;
12594     Roo.tree.AsyncTreeNode.superclass.constructor.apply(this, arguments);
12595     /**
12596     * @event beforeload
12597     * Fires before this node is loaded, return false to cancel
12598     * @param {Node} this This node
12599     */
12600     this.addEvents({'beforeload':true, 'load': true});
12601     /**
12602     * @event load
12603     * Fires when this node is loaded
12604     * @param {Node} this This node
12605     */
12606     /**
12607      * The loader used by this node (defaults to using the tree's defined loader)
12608      * @type TreeLoader
12609      * @property loader
12610      */
12611 };
12612 Roo.extend(Roo.tree.AsyncTreeNode, Roo.tree.TreeNode, {
12613     expand : function(deep, anim, callback){
12614         if(this.loading){ // if an async load is already running, waiting til it's done
12615             var timer;
12616             var f = function(){
12617                 if(!this.loading){ // done loading
12618                     clearInterval(timer);
12619                     this.expand(deep, anim, callback);
12620                 }
12621             }.createDelegate(this);
12622             timer = setInterval(f, 200);
12623             return;
12624         }
12625         if(!this.loaded){
12626             if(this.fireEvent("beforeload", this) === false){
12627                 return;
12628             }
12629             this.loading = true;
12630             this.ui.beforeLoad(this);
12631             var loader = this.loader || this.attributes.loader || this.getOwnerTree().getLoader();
12632             if(loader){
12633                 loader.load(this, this.loadComplete.createDelegate(this, [deep, anim, callback]));
12634                 return;
12635             }
12636         }
12637         Roo.tree.AsyncTreeNode.superclass.expand.call(this, deep, anim, callback);
12638     },
12639     
12640     /**
12641      * Returns true if this node is currently loading
12642      * @return {Boolean}
12643      */
12644     isLoading : function(){
12645         return this.loading;  
12646     },
12647     
12648     loadComplete : function(deep, anim, callback){
12649         this.loading = false;
12650         this.loaded = true;
12651         this.ui.afterLoad(this);
12652         this.fireEvent("load", this);
12653         this.expand(deep, anim, callback);
12654     },
12655     
12656     /**
12657      * Returns true if this node has been loaded
12658      * @return {Boolean}
12659      */
12660     isLoaded : function(){
12661         return this.loaded;
12662     },
12663     
12664     hasChildNodes : function(){
12665         if(!this.isLeaf() && !this.loaded){
12666             return true;
12667         }else{
12668             return Roo.tree.AsyncTreeNode.superclass.hasChildNodes.call(this);
12669         }
12670     },
12671
12672     /**
12673      * Trigger a reload for this node
12674      * @param {Function} callback
12675      */
12676     reload : function(callback){
12677         this.collapse(false, false);
12678         while(this.firstChild){
12679             this.removeChild(this.firstChild);
12680         }
12681         this.childrenRendered = false;
12682         this.loaded = false;
12683         if(this.isHiddenRoot()){
12684             this.expanded = false;
12685         }
12686         this.expand(false, false, callback);
12687     }
12688 });/*
12689  * Based on:
12690  * Ext JS Library 1.1.1
12691  * Copyright(c) 2006-2007, Ext JS, LLC.
12692  *
12693  * Originally Released Under LGPL - original licence link has changed is not relivant.
12694  *
12695  * Fork - LGPL
12696  * <script type="text/javascript">
12697  */
12698  
12699 /**
12700  * @class Roo.tree.TreeNodeUI
12701  * @constructor
12702  * @param {Object} node The node to render
12703  * The TreeNode UI implementation is separate from the
12704  * tree implementation. Unless you are customizing the tree UI,
12705  * you should never have to use this directly.
12706  */
12707 Roo.tree.TreeNodeUI = function(node){
12708     this.node = node;
12709     this.rendered = false;
12710     this.animating = false;
12711     this.emptyIcon = Roo.BLANK_IMAGE_URL;
12712 };
12713
12714 Roo.tree.TreeNodeUI.prototype = {
12715     removeChild : function(node){
12716         if(this.rendered){
12717             this.ctNode.removeChild(node.ui.getEl());
12718         }
12719     },
12720
12721     beforeLoad : function(){
12722          this.addClass("x-tree-node-loading");
12723     },
12724
12725     afterLoad : function(){
12726          this.removeClass("x-tree-node-loading");
12727     },
12728
12729     onTextChange : function(node, text, oldText){
12730         if(this.rendered){
12731             this.textNode.innerHTML = text;
12732         }
12733     },
12734
12735     onDisableChange : function(node, state){
12736         this.disabled = state;
12737         if(state){
12738             this.addClass("x-tree-node-disabled");
12739         }else{
12740             this.removeClass("x-tree-node-disabled");
12741         }
12742     },
12743
12744     onSelectedChange : function(state){
12745         if(state){
12746             this.focus();
12747             this.addClass("x-tree-selected");
12748         }else{
12749             //this.blur();
12750             this.removeClass("x-tree-selected");
12751         }
12752     },
12753
12754     onMove : function(tree, node, oldParent, newParent, index, refNode){
12755         this.childIndent = null;
12756         if(this.rendered){
12757             var targetNode = newParent.ui.getContainer();
12758             if(!targetNode){//target not rendered
12759                 this.holder = document.createElement("div");
12760                 this.holder.appendChild(this.wrap);
12761                 return;
12762             }
12763             var insertBefore = refNode ? refNode.ui.getEl() : null;
12764             if(insertBefore){
12765                 targetNode.insertBefore(this.wrap, insertBefore);
12766             }else{
12767                 targetNode.appendChild(this.wrap);
12768             }
12769             this.node.renderIndent(true);
12770         }
12771     },
12772
12773     addClass : function(cls){
12774         if(this.elNode){
12775             Roo.fly(this.elNode).addClass(cls);
12776         }
12777     },
12778
12779     removeClass : function(cls){
12780         if(this.elNode){
12781             Roo.fly(this.elNode).removeClass(cls);
12782         }
12783     },
12784
12785     remove : function(){
12786         if(this.rendered){
12787             this.holder = document.createElement("div");
12788             this.holder.appendChild(this.wrap);
12789         }
12790     },
12791
12792     fireEvent : function(){
12793         return this.node.fireEvent.apply(this.node, arguments);
12794     },
12795
12796     initEvents : function(){
12797         this.node.on("move", this.onMove, this);
12798         var E = Roo.EventManager;
12799         var a = this.anchor;
12800
12801         var el = Roo.fly(a, '_treeui');
12802
12803         if(Roo.isOpera){ // opera render bug ignores the CSS
12804             el.setStyle("text-decoration", "none");
12805         }
12806
12807         el.on("click", this.onClick, this);
12808         el.on("dblclick", this.onDblClick, this);
12809
12810         if(this.checkbox){
12811             Roo.EventManager.on(this.checkbox,
12812                     Roo.isIE ? 'click' : 'change', this.onCheckChange, this);
12813         }
12814
12815         el.on("contextmenu", this.onContextMenu, this);
12816
12817         var icon = Roo.fly(this.iconNode);
12818         icon.on("click", this.onClick, this);
12819         icon.on("dblclick", this.onDblClick, this);
12820         icon.on("contextmenu", this.onContextMenu, this);
12821         E.on(this.ecNode, "click", this.ecClick, this, true);
12822
12823         if(this.node.disabled){
12824             this.addClass("x-tree-node-disabled");
12825         }
12826         if(this.node.hidden){
12827             this.addClass("x-tree-node-disabled");
12828         }
12829         var ot = this.node.getOwnerTree();
12830         var dd = ot ? (ot.enableDD || ot.enableDrag || ot.enableDrop) : false;
12831         if(dd && (!this.node.isRoot || ot.rootVisible)){
12832             Roo.dd.Registry.register(this.elNode, {
12833                 node: this.node,
12834                 handles: this.getDDHandles(),
12835                 isHandle: false
12836             });
12837         }
12838     },
12839
12840     getDDHandles : function(){
12841         return [this.iconNode, this.textNode];
12842     },
12843
12844     hide : function(){
12845         if(this.rendered){
12846             this.wrap.style.display = "none";
12847         }
12848     },
12849
12850     show : function(){
12851         if(this.rendered){
12852             this.wrap.style.display = "";
12853         }
12854     },
12855
12856     onContextMenu : function(e){
12857         if (this.node.hasListener("contextmenu") || this.node.getOwnerTree().hasListener("contextmenu")) {
12858             e.preventDefault();
12859             this.focus();
12860             this.fireEvent("contextmenu", this.node, e);
12861         }
12862     },
12863
12864     onClick : function(e){
12865         if(this.dropping){
12866             e.stopEvent();
12867             return;
12868         }
12869         if(this.fireEvent("beforeclick", this.node, e) !== false){
12870             if(!this.disabled && this.node.attributes.href){
12871                 this.fireEvent("click", this.node, e);
12872                 return;
12873             }
12874             e.preventDefault();
12875             if(this.disabled){
12876                 return;
12877             }
12878
12879             if(this.node.attributes.singleClickExpand && !this.animating && this.node.hasChildNodes()){
12880                 this.node.toggle();
12881             }
12882
12883             this.fireEvent("click", this.node, e);
12884         }else{
12885             e.stopEvent();
12886         }
12887     },
12888
12889     onDblClick : function(e){
12890         e.preventDefault();
12891         if(this.disabled){
12892             return;
12893         }
12894         if(this.checkbox){
12895             this.toggleCheck();
12896         }
12897         if(!this.animating && this.node.hasChildNodes()){
12898             this.node.toggle();
12899         }
12900         this.fireEvent("dblclick", this.node, e);
12901     },
12902
12903     onCheckChange : function(){
12904         var checked = this.checkbox.checked;
12905         this.node.attributes.checked = checked;
12906         this.fireEvent('checkchange', this.node, checked);
12907     },
12908
12909     ecClick : function(e){
12910         if(!this.animating && this.node.hasChildNodes()){
12911             this.node.toggle();
12912         }
12913     },
12914
12915     startDrop : function(){
12916         this.dropping = true;
12917     },
12918
12919     // delayed drop so the click event doesn't get fired on a drop
12920     endDrop : function(){
12921        setTimeout(function(){
12922            this.dropping = false;
12923        }.createDelegate(this), 50);
12924     },
12925
12926     expand : function(){
12927         this.updateExpandIcon();
12928         this.ctNode.style.display = "";
12929     },
12930
12931     focus : function(){
12932         if(!this.node.preventHScroll){
12933             try{this.anchor.focus();
12934             }catch(e){}
12935         }else if(!Roo.isIE){
12936             try{
12937                 var noscroll = this.node.getOwnerTree().getTreeEl().dom;
12938                 var l = noscroll.scrollLeft;
12939                 this.anchor.focus();
12940                 noscroll.scrollLeft = l;
12941             }catch(e){}
12942         }
12943     },
12944
12945     toggleCheck : function(value){
12946         var cb = this.checkbox;
12947         if(cb){
12948             cb.checked = (value === undefined ? !cb.checked : value);
12949         }
12950     },
12951
12952     blur : function(){
12953         try{
12954             this.anchor.blur();
12955         }catch(e){}
12956     },
12957
12958     animExpand : function(callback){
12959         var ct = Roo.get(this.ctNode);
12960         ct.stopFx();
12961         if(!this.node.hasChildNodes()){
12962             this.updateExpandIcon();
12963             this.ctNode.style.display = "";
12964             Roo.callback(callback);
12965             return;
12966         }
12967         this.animating = true;
12968         this.updateExpandIcon();
12969
12970         ct.slideIn('t', {
12971            callback : function(){
12972                this.animating = false;
12973                Roo.callback(callback);
12974             },
12975             scope: this,
12976             duration: this.node.ownerTree.duration || .25
12977         });
12978     },
12979
12980     highlight : function(){
12981         var tree = this.node.getOwnerTree();
12982         Roo.fly(this.wrap).highlight(
12983             tree.hlColor || "C3DAF9",
12984             {endColor: tree.hlBaseColor}
12985         );
12986     },
12987
12988     collapse : function(){
12989         this.updateExpandIcon();
12990         this.ctNode.style.display = "none";
12991     },
12992
12993     animCollapse : function(callback){
12994         var ct = Roo.get(this.ctNode);
12995         ct.enableDisplayMode('block');
12996         ct.stopFx();
12997
12998         this.animating = true;
12999         this.updateExpandIcon();
13000
13001         ct.slideOut('t', {
13002             callback : function(){
13003                this.animating = false;
13004                Roo.callback(callback);
13005             },
13006             scope: this,
13007             duration: this.node.ownerTree.duration || .25
13008         });
13009     },
13010
13011     getContainer : function(){
13012         return this.ctNode;
13013     },
13014
13015     getEl : function(){
13016         return this.wrap;
13017     },
13018
13019     appendDDGhost : function(ghostNode){
13020         ghostNode.appendChild(this.elNode.cloneNode(true));
13021     },
13022
13023     getDDRepairXY : function(){
13024         return Roo.lib.Dom.getXY(this.iconNode);
13025     },
13026
13027     onRender : function(){
13028         this.render();
13029     },
13030
13031     render : function(bulkRender){
13032         var n = this.node, a = n.attributes;
13033         var targetNode = n.parentNode ?
13034               n.parentNode.ui.getContainer() : n.ownerTree.innerCt.dom;
13035
13036         if(!this.rendered){
13037             this.rendered = true;
13038
13039             this.renderElements(n, a, targetNode, bulkRender);
13040
13041             if(a.qtip){
13042                if(this.textNode.setAttributeNS){
13043                    this.textNode.setAttributeNS("ext", "qtip", a.qtip);
13044                    if(a.qtipTitle){
13045                        this.textNode.setAttributeNS("ext", "qtitle", a.qtipTitle);
13046                    }
13047                }else{
13048                    this.textNode.setAttribute("ext:qtip", a.qtip);
13049                    if(a.qtipTitle){
13050                        this.textNode.setAttribute("ext:qtitle", a.qtipTitle);
13051                    }
13052                }
13053             }else if(a.qtipCfg){
13054                 a.qtipCfg.target = Roo.id(this.textNode);
13055                 Roo.QuickTips.register(a.qtipCfg);
13056             }
13057             this.initEvents();
13058             if(!this.node.expanded){
13059                 this.updateExpandIcon();
13060             }
13061         }else{
13062             if(bulkRender === true) {
13063                 targetNode.appendChild(this.wrap);
13064             }
13065         }
13066     },
13067
13068     renderElements : function(n, a, targetNode, bulkRender)
13069     {
13070         // add some indent caching, this helps performance when rendering a large tree
13071         this.indentMarkup = n.parentNode ? n.parentNode.ui.getChildIndent() : '';
13072         var t = n.getOwnerTree();
13073         var txt = t && t.renderer ? t.renderer(n.attributes) : Roo.util.Format.htmlEncode(n.text);
13074         if (typeof(n.attributes.html) != 'undefined') {
13075             txt = n.attributes.html;
13076         }
13077         var tip = t && t.rendererTip ? t.rendererTip(n.attributes) : txt;
13078         var cb = typeof a.checked == 'boolean';
13079         var href = a.href ? a.href : Roo.isGecko ? "" : "#";
13080         var buf = ['<li class="x-tree-node"><div class="x-tree-node-el ', a.cls,'">',
13081             '<span class="x-tree-node-indent">',this.indentMarkup,"</span>",
13082             '<img src="', this.emptyIcon, '" class="x-tree-ec-icon" />',
13083             '<img src="', a.icon || this.emptyIcon, '" class="x-tree-node-icon',(a.icon ? " x-tree-node-inline-icon" : ""),(a.iconCls ? " "+a.iconCls : ""),'" unselectable="on" />',
13084             cb ? ('<input class="x-tree-node-cb" type="checkbox" ' + (a.checked ? 'checked="checked" />' : ' />')) : '',
13085             '<a hidefocus="on" href="',href,'" tabIndex="1" ',
13086              a.hrefTarget ? ' target="'+a.hrefTarget+'"' : "", 
13087                 '><span unselectable="on" qtip="' , tip ,'">',txt,"</span></a></div>",
13088             '<ul class="x-tree-node-ct" style="display:none;"></ul>',
13089             "</li>"];
13090
13091         if(bulkRender !== true && n.nextSibling && n.nextSibling.ui.getEl()){
13092             this.wrap = Roo.DomHelper.insertHtml("beforeBegin",
13093                                 n.nextSibling.ui.getEl(), buf.join(""));
13094         }else{
13095             this.wrap = Roo.DomHelper.insertHtml("beforeEnd", targetNode, buf.join(""));
13096         }
13097
13098         this.elNode = this.wrap.childNodes[0];
13099         this.ctNode = this.wrap.childNodes[1];
13100         var cs = this.elNode.childNodes;
13101         this.indentNode = cs[0];
13102         this.ecNode = cs[1];
13103         this.iconNode = cs[2];
13104         var index = 3;
13105         if(cb){
13106             this.checkbox = cs[3];
13107             index++;
13108         }
13109         this.anchor = cs[index];
13110         this.textNode = cs[index].firstChild;
13111     },
13112
13113     getAnchor : function(){
13114         return this.anchor;
13115     },
13116
13117     getTextEl : function(){
13118         return this.textNode;
13119     },
13120
13121     getIconEl : function(){
13122         return this.iconNode;
13123     },
13124
13125     isChecked : function(){
13126         return this.checkbox ? this.checkbox.checked : false;
13127     },
13128
13129     updateExpandIcon : function(){
13130         if(this.rendered){
13131             var n = this.node, c1, c2;
13132             var cls = n.isLast() ? "x-tree-elbow-end" : "x-tree-elbow";
13133             var hasChild = n.hasChildNodes();
13134             if(hasChild){
13135                 if(n.expanded){
13136                     cls += "-minus";
13137                     c1 = "x-tree-node-collapsed";
13138                     c2 = "x-tree-node-expanded";
13139                 }else{
13140                     cls += "-plus";
13141                     c1 = "x-tree-node-expanded";
13142                     c2 = "x-tree-node-collapsed";
13143                 }
13144                 if(this.wasLeaf){
13145                     this.removeClass("x-tree-node-leaf");
13146                     this.wasLeaf = false;
13147                 }
13148                 if(this.c1 != c1 || this.c2 != c2){
13149                     Roo.fly(this.elNode).replaceClass(c1, c2);
13150                     this.c1 = c1; this.c2 = c2;
13151                 }
13152             }else{
13153                 // this changes non-leafs into leafs if they have no children.
13154                 // it's not very rational behaviour..
13155                 
13156                 if(!this.wasLeaf && this.node.leaf){
13157                     Roo.fly(this.elNode).replaceClass("x-tree-node-expanded", "x-tree-node-leaf");
13158                     delete this.c1;
13159                     delete this.c2;
13160                     this.wasLeaf = true;
13161                 }
13162             }
13163             var ecc = "x-tree-ec-icon "+cls;
13164             if(this.ecc != ecc){
13165                 this.ecNode.className = ecc;
13166                 this.ecc = ecc;
13167             }
13168         }
13169     },
13170
13171     getChildIndent : function(){
13172         if(!this.childIndent){
13173             var buf = [];
13174             var p = this.node;
13175             while(p){
13176                 if(!p.isRoot || (p.isRoot && p.ownerTree.rootVisible)){
13177                     if(!p.isLast()) {
13178                         buf.unshift('<img src="'+this.emptyIcon+'" class="x-tree-elbow-line" />');
13179                     } else {
13180                         buf.unshift('<img src="'+this.emptyIcon+'" class="x-tree-icon" />');
13181                     }
13182                 }
13183                 p = p.parentNode;
13184             }
13185             this.childIndent = buf.join("");
13186         }
13187         return this.childIndent;
13188     },
13189
13190     renderIndent : function(){
13191         if(this.rendered){
13192             var indent = "";
13193             var p = this.node.parentNode;
13194             if(p){
13195                 indent = p.ui.getChildIndent();
13196             }
13197             if(this.indentMarkup != indent){ // don't rerender if not required
13198                 this.indentNode.innerHTML = indent;
13199                 this.indentMarkup = indent;
13200             }
13201             this.updateExpandIcon();
13202         }
13203     }
13204 };
13205
13206 Roo.tree.RootTreeNodeUI = function(){
13207     Roo.tree.RootTreeNodeUI.superclass.constructor.apply(this, arguments);
13208 };
13209 Roo.extend(Roo.tree.RootTreeNodeUI, Roo.tree.TreeNodeUI, {
13210     render : function(){
13211         if(!this.rendered){
13212             var targetNode = this.node.ownerTree.innerCt.dom;
13213             this.node.expanded = true;
13214             targetNode.innerHTML = '<div class="x-tree-root-node"></div>';
13215             this.wrap = this.ctNode = targetNode.firstChild;
13216         }
13217     },
13218     collapse : function(){
13219     },
13220     expand : function(){
13221     }
13222 });/*
13223  * Based on:
13224  * Ext JS Library 1.1.1
13225  * Copyright(c) 2006-2007, Ext JS, LLC.
13226  *
13227  * Originally Released Under LGPL - original licence link has changed is not relivant.
13228  *
13229  * Fork - LGPL
13230  * <script type="text/javascript">
13231  */
13232 /**
13233  * @class Roo.tree.TreeLoader
13234  * @extends Roo.util.Observable
13235  * A TreeLoader provides for lazy loading of an {@link Roo.tree.TreeNode}'s child
13236  * nodes from a specified URL. The response must be a javascript Array definition
13237  * who's elements are node definition objects. eg:
13238  * <pre><code>
13239 {  success : true,
13240    data :      [
13241    
13242     { 'id': 1, 'text': 'A folder Node', 'leaf': false },
13243     { 'id': 2, 'text': 'A leaf Node', 'leaf': true }
13244     ]
13245 }
13246
13247
13248 </code></pre>
13249  * <br><br>
13250  * The old style respose with just an array is still supported, but not recommended.
13251  * <br><br>
13252  *
13253  * A server request is sent, and child nodes are loaded only when a node is expanded.
13254  * The loading node's id is passed to the server under the parameter name "node" to
13255  * enable the server to produce the correct child nodes.
13256  * <br><br>
13257  * To pass extra parameters, an event handler may be attached to the "beforeload"
13258  * event, and the parameters specified in the TreeLoader's baseParams property:
13259  * <pre><code>
13260     myTreeLoader.on("beforeload", function(treeLoader, node) {
13261         this.baseParams.category = node.attributes.category;
13262     }, this);
13263     
13264 </code></pre>
13265  *
13266  * This would pass an HTTP parameter called "category" to the server containing
13267  * the value of the Node's "category" attribute.
13268  * @constructor
13269  * Creates a new Treeloader.
13270  * @param {Object} config A config object containing config properties.
13271  */
13272 Roo.tree.TreeLoader = function(config){
13273     this.baseParams = {};
13274     this.requestMethod = "POST";
13275     Roo.apply(this, config);
13276
13277     this.addEvents({
13278     
13279         /**
13280          * @event beforeload
13281          * Fires before a network request is made to retrieve the Json text which specifies a node's children.
13282          * @param {Object} This TreeLoader object.
13283          * @param {Object} node The {@link Roo.tree.TreeNode} object being loaded.
13284          * @param {Object} callback The callback function specified in the {@link #load} call.
13285          */
13286         beforeload : true,
13287         /**
13288          * @event load
13289          * Fires when the node has been successfuly loaded.
13290          * @param {Object} This TreeLoader object.
13291          * @param {Object} node The {@link Roo.tree.TreeNode} object being loaded.
13292          * @param {Object} response The response object containing the data from the server.
13293          */
13294         load : true,
13295         /**
13296          * @event loadexception
13297          * Fires if the network request failed.
13298          * @param {Object} This TreeLoader object.
13299          * @param {Object} node The {@link Roo.tree.TreeNode} object being loaded.
13300          * @param {Object} response The response object containing the data from the server.
13301          */
13302         loadexception : true,
13303         /**
13304          * @event create
13305          * Fires before a node is created, enabling you to return custom Node types 
13306          * @param {Object} This TreeLoader object.
13307          * @param {Object} attr - the data returned from the AJAX call (modify it to suit)
13308          */
13309         create : true
13310     });
13311
13312     Roo.tree.TreeLoader.superclass.constructor.call(this);
13313 };
13314
13315 Roo.extend(Roo.tree.TreeLoader, Roo.util.Observable, {
13316     /**
13317     * @cfg {String} dataUrl The URL from which to request a Json string which
13318     * specifies an array of node definition object representing the child nodes
13319     * to be loaded.
13320     */
13321     /**
13322     * @cfg {String} requestMethod either GET or POST
13323     * defaults to POST (due to BC)
13324     * to be loaded.
13325     */
13326     /**
13327     * @cfg {Object} baseParams (optional) An object containing properties which
13328     * specify HTTP parameters to be passed to each request for child nodes.
13329     */
13330     /**
13331     * @cfg {Object} baseAttrs (optional) An object containing attributes to be added to all nodes
13332     * created by this loader. If the attributes sent by the server have an attribute in this object,
13333     * they take priority.
13334     */
13335     /**
13336     * @cfg {Object} uiProviders (optional) An object containing properties which
13337     * 
13338     * DEPRECATED - use 'create' event handler to modify attributes - which affect creation.
13339     * specify custom {@link Roo.tree.TreeNodeUI} implementations. If the optional
13340     * <i>uiProvider</i> attribute of a returned child node is a string rather
13341     * than a reference to a TreeNodeUI implementation, this that string value
13342     * is used as a property name in the uiProviders object. You can define the provider named
13343     * 'default' , and this will be used for all nodes (if no uiProvider is delivered by the node data)
13344     */
13345     uiProviders : {},
13346
13347     /**
13348     * @cfg {Boolean} clearOnLoad (optional) Default to true. Remove previously existing
13349     * child nodes before loading.
13350     */
13351     clearOnLoad : true,
13352
13353     /**
13354     * @cfg {String} root (optional) Default to false. Use this to read data from an object 
13355     * property on loading, rather than expecting an array. (eg. more compatible to a standard
13356     * Grid query { data : [ .....] }
13357     */
13358     
13359     root : false,
13360      /**
13361     * @cfg {String} queryParam (optional) 
13362     * Name of the query as it will be passed on the querystring (defaults to 'node')
13363     * eg. the request will be ?node=[id]
13364     */
13365     
13366     
13367     queryParam: false,
13368     
13369     /**
13370      * Load an {@link Roo.tree.TreeNode} from the URL specified in the constructor.
13371      * This is called automatically when a node is expanded, but may be used to reload
13372      * a node (or append new children if the {@link #clearOnLoad} option is false.)
13373      * @param {Roo.tree.TreeNode} node
13374      * @param {Function} callback
13375      */
13376     load : function(node, callback){
13377         if(this.clearOnLoad){
13378             while(node.firstChild){
13379                 node.removeChild(node.firstChild);
13380             }
13381         }
13382         if(node.attributes.children){ // preloaded json children
13383             var cs = node.attributes.children;
13384             for(var i = 0, len = cs.length; i < len; i++){
13385                 node.appendChild(this.createNode(cs[i]));
13386             }
13387             if(typeof callback == "function"){
13388                 callback();
13389             }
13390         }else if(this.dataUrl){
13391             this.requestData(node, callback);
13392         }
13393     },
13394
13395     getParams: function(node){
13396         var buf = [], bp = this.baseParams;
13397         for(var key in bp){
13398             if(typeof bp[key] != "function"){
13399                 buf.push(encodeURIComponent(key), "=", encodeURIComponent(bp[key]), "&");
13400             }
13401         }
13402         var n = this.queryParam === false ? 'node' : this.queryParam;
13403         buf.push(n + "=", encodeURIComponent(node.id));
13404         return buf.join("");
13405     },
13406
13407     requestData : function(node, callback){
13408         if(this.fireEvent("beforeload", this, node, callback) !== false){
13409             this.transId = Roo.Ajax.request({
13410                 method:this.requestMethod,
13411                 url: this.dataUrl||this.url,
13412                 success: this.handleResponse,
13413                 failure: this.handleFailure,
13414                 scope: this,
13415                 argument: {callback: callback, node: node},
13416                 params: this.getParams(node)
13417             });
13418         }else{
13419             // if the load is cancelled, make sure we notify
13420             // the node that we are done
13421             if(typeof callback == "function"){
13422                 callback();
13423             }
13424         }
13425     },
13426
13427     isLoading : function(){
13428         return this.transId ? true : false;
13429     },
13430
13431     abort : function(){
13432         if(this.isLoading()){
13433             Roo.Ajax.abort(this.transId);
13434         }
13435     },
13436
13437     // private
13438     createNode : function(attr)
13439     {
13440         // apply baseAttrs, nice idea Corey!
13441         if(this.baseAttrs){
13442             Roo.applyIf(attr, this.baseAttrs);
13443         }
13444         if(this.applyLoader !== false){
13445             attr.loader = this;
13446         }
13447         // uiProvider = depreciated..
13448         
13449         if(typeof(attr.uiProvider) == 'string'){
13450            attr.uiProvider = this.uiProviders[attr.uiProvider] || 
13451                 /**  eval:var:attr */ eval(attr.uiProvider);
13452         }
13453         if(typeof(this.uiProviders['default']) != 'undefined') {
13454             attr.uiProvider = this.uiProviders['default'];
13455         }
13456         
13457         this.fireEvent('create', this, attr);
13458         
13459         attr.leaf  = typeof(attr.leaf) == 'string' ? attr.leaf * 1 : attr.leaf;
13460         return(attr.leaf ?
13461                         new Roo.tree.TreeNode(attr) :
13462                         new Roo.tree.AsyncTreeNode(attr));
13463     },
13464
13465     processResponse : function(response, node, callback)
13466     {
13467         var json = response.responseText;
13468         try {
13469             
13470             var o = Roo.decode(json);
13471             
13472             if (this.root === false && typeof(o.success) != undefined) {
13473                 this.root = 'data'; // the default behaviour for list like data..
13474                 }
13475                 
13476             if (this.root !== false &&  !o.success) {
13477                 // it's a failure condition.
13478                 var a = response.argument;
13479                 this.fireEvent("loadexception", this, a.node, response);
13480                 Roo.log("Load failed - should have a handler really");
13481                 return;
13482             }
13483             
13484             
13485             
13486             if (this.root !== false) {
13487                  o = o[this.root];
13488             }
13489             
13490             for(var i = 0, len = o.length; i < len; i++){
13491                 var n = this.createNode(o[i]);
13492                 if(n){
13493                     node.appendChild(n);
13494                 }
13495             }
13496             if(typeof callback == "function"){
13497                 callback(this, node);
13498             }
13499         }catch(e){
13500             this.handleFailure(response);
13501         }
13502     },
13503
13504     handleResponse : function(response){
13505         this.transId = false;
13506         var a = response.argument;
13507         this.processResponse(response, a.node, a.callback);
13508         this.fireEvent("load", this, a.node, response);
13509     },
13510
13511     handleFailure : function(response)
13512     {
13513         // should handle failure better..
13514         this.transId = false;
13515         var a = response.argument;
13516         this.fireEvent("loadexception", this, a.node, response);
13517         if(typeof a.callback == "function"){
13518             a.callback(this, a.node);
13519         }
13520     }
13521 });/*
13522  * Based on:
13523  * Ext JS Library 1.1.1
13524  * Copyright(c) 2006-2007, Ext JS, LLC.
13525  *
13526  * Originally Released Under LGPL - original licence link has changed is not relivant.
13527  *
13528  * Fork - LGPL
13529  * <script type="text/javascript">
13530  */
13531
13532 /**
13533 * @class Roo.tree.TreeFilter
13534 * Note this class is experimental and doesn't update the indent (lines) or expand collapse icons of the nodes
13535 * @param {TreePanel} tree
13536 * @param {Object} config (optional)
13537  */
13538 Roo.tree.TreeFilter = function(tree, config){
13539     this.tree = tree;
13540     this.filtered = {};
13541     Roo.apply(this, config);
13542 };
13543
13544 Roo.tree.TreeFilter.prototype = {
13545     clearBlank:false,
13546     reverse:false,
13547     autoClear:false,
13548     remove:false,
13549
13550      /**
13551      * Filter the data by a specific attribute.
13552      * @param {String/RegExp} value Either string that the attribute value
13553      * should start with or a RegExp to test against the attribute
13554      * @param {String} attr (optional) The attribute passed in your node's attributes collection. Defaults to "text".
13555      * @param {TreeNode} startNode (optional) The node to start the filter at.
13556      */
13557     filter : function(value, attr, startNode){
13558         attr = attr || "text";
13559         var f;
13560         if(typeof value == "string"){
13561             var vlen = value.length;
13562             // auto clear empty filter
13563             if(vlen == 0 && this.clearBlank){
13564                 this.clear();
13565                 return;
13566             }
13567             value = value.toLowerCase();
13568             f = function(n){
13569                 return n.attributes[attr].substr(0, vlen).toLowerCase() == value;
13570             };
13571         }else if(value.exec){ // regex?
13572             f = function(n){
13573                 return value.test(n.attributes[attr]);
13574             };
13575         }else{
13576             throw 'Illegal filter type, must be string or regex';
13577         }
13578         this.filterBy(f, null, startNode);
13579         },
13580
13581     /**
13582      * Filter by a function. The passed function will be called with each
13583      * node in the tree (or from the startNode). If the function returns true, the node is kept
13584      * otherwise it is filtered. If a node is filtered, its children are also filtered.
13585      * @param {Function} fn The filter function
13586      * @param {Object} scope (optional) The scope of the function (defaults to the current node)
13587      */
13588     filterBy : function(fn, scope, startNode){
13589         startNode = startNode || this.tree.root;
13590         if(this.autoClear){
13591             this.clear();
13592         }
13593         var af = this.filtered, rv = this.reverse;
13594         var f = function(n){
13595             if(n == startNode){
13596                 return true;
13597             }
13598             if(af[n.id]){
13599                 return false;
13600             }
13601             var m = fn.call(scope || n, n);
13602             if(!m || rv){
13603                 af[n.id] = n;
13604                 n.ui.hide();
13605                 return false;
13606             }
13607             return true;
13608         };
13609         startNode.cascade(f);
13610         if(this.remove){
13611            for(var id in af){
13612                if(typeof id != "function"){
13613                    var n = af[id];
13614                    if(n && n.parentNode){
13615                        n.parentNode.removeChild(n);
13616                    }
13617                }
13618            }
13619         }
13620     },
13621
13622     /**
13623      * Clears the current filter. Note: with the "remove" option
13624      * set a filter cannot be cleared.
13625      */
13626     clear : function(){
13627         var t = this.tree;
13628         var af = this.filtered;
13629         for(var id in af){
13630             if(typeof id != "function"){
13631                 var n = af[id];
13632                 if(n){
13633                     n.ui.show();
13634                 }
13635             }
13636         }
13637         this.filtered = {};
13638     }
13639 };
13640 /*
13641  * Based on:
13642  * Ext JS Library 1.1.1
13643  * Copyright(c) 2006-2007, Ext JS, LLC.
13644  *
13645  * Originally Released Under LGPL - original licence link has changed is not relivant.
13646  *
13647  * Fork - LGPL
13648  * <script type="text/javascript">
13649  */
13650  
13651
13652 /**
13653  * @class Roo.tree.TreeSorter
13654  * Provides sorting of nodes in a TreePanel
13655  * 
13656  * @cfg {Boolean} folderSort True to sort leaf nodes under non leaf nodes
13657  * @cfg {String} property The named attribute on the node to sort by (defaults to text)
13658  * @cfg {String} dir The direction to sort (asc or desc) (defaults to asc)
13659  * @cfg {String} leafAttr The attribute used to determine leaf nodes in folder sort (defaults to "leaf")
13660  * @cfg {Boolean} caseSensitive true for case sensitive sort (defaults to false)
13661  * @cfg {Function} sortType A custom "casting" function used to convert node values before sorting
13662  * @constructor
13663  * @param {TreePanel} tree
13664  * @param {Object} config
13665  */
13666 Roo.tree.TreeSorter = function(tree, config){
13667     Roo.apply(this, config);
13668     tree.on("beforechildrenrendered", this.doSort, this);
13669     tree.on("append", this.updateSort, this);
13670     tree.on("insert", this.updateSort, this);
13671     
13672     var dsc = this.dir && this.dir.toLowerCase() == "desc";
13673     var p = this.property || "text";
13674     var sortType = this.sortType;
13675     var fs = this.folderSort;
13676     var cs = this.caseSensitive === true;
13677     var leafAttr = this.leafAttr || 'leaf';
13678
13679     this.sortFn = function(n1, n2){
13680         if(fs){
13681             if(n1.attributes[leafAttr] && !n2.attributes[leafAttr]){
13682                 return 1;
13683             }
13684             if(!n1.attributes[leafAttr] && n2.attributes[leafAttr]){
13685                 return -1;
13686             }
13687         }
13688         var v1 = sortType ? sortType(n1) : (cs ? n1.attributes[p] : n1.attributes[p].toUpperCase());
13689         var v2 = sortType ? sortType(n2) : (cs ? n2.attributes[p] : n2.attributes[p].toUpperCase());
13690         if(v1 < v2){
13691                         return dsc ? +1 : -1;
13692                 }else if(v1 > v2){
13693                         return dsc ? -1 : +1;
13694         }else{
13695                 return 0;
13696         }
13697     };
13698 };
13699
13700 Roo.tree.TreeSorter.prototype = {
13701     doSort : function(node){
13702         node.sort(this.sortFn);
13703     },
13704     
13705     compareNodes : function(n1, n2){
13706         return (n1.text.toUpperCase() > n2.text.toUpperCase() ? 1 : -1);
13707     },
13708     
13709     updateSort : function(tree, node){
13710         if(node.childrenRendered){
13711             this.doSort.defer(1, this, [node]);
13712         }
13713     }
13714 };/*
13715  * Based on:
13716  * Ext JS Library 1.1.1
13717  * Copyright(c) 2006-2007, Ext JS, LLC.
13718  *
13719  * Originally Released Under LGPL - original licence link has changed is not relivant.
13720  *
13721  * Fork - LGPL
13722  * <script type="text/javascript">
13723  */
13724
13725 if(Roo.dd.DropZone){
13726     
13727 Roo.tree.TreeDropZone = function(tree, config){
13728     this.allowParentInsert = false;
13729     this.allowContainerDrop = false;
13730     this.appendOnly = false;
13731     Roo.tree.TreeDropZone.superclass.constructor.call(this, tree.innerCt, config);
13732     this.tree = tree;
13733     this.lastInsertClass = "x-tree-no-status";
13734     this.dragOverData = {};
13735 };
13736
13737 Roo.extend(Roo.tree.TreeDropZone, Roo.dd.DropZone, {
13738     ddGroup : "TreeDD",
13739     scroll:  true,
13740     
13741     expandDelay : 1000,
13742     
13743     expandNode : function(node){
13744         if(node.hasChildNodes() && !node.isExpanded()){
13745             node.expand(false, null, this.triggerCacheRefresh.createDelegate(this));
13746         }
13747     },
13748     
13749     queueExpand : function(node){
13750         this.expandProcId = this.expandNode.defer(this.expandDelay, this, [node]);
13751     },
13752     
13753     cancelExpand : function(){
13754         if(this.expandProcId){
13755             clearTimeout(this.expandProcId);
13756             this.expandProcId = false;
13757         }
13758     },
13759     
13760     isValidDropPoint : function(n, pt, dd, e, data){
13761         if(!n || !data){ return false; }
13762         var targetNode = n.node;
13763         var dropNode = data.node;
13764         // default drop rules
13765         if(!(targetNode && targetNode.isTarget && pt)){
13766             return false;
13767         }
13768         if(pt == "append" && targetNode.allowChildren === false){
13769             return false;
13770         }
13771         if((pt == "above" || pt == "below") && (targetNode.parentNode && targetNode.parentNode.allowChildren === false)){
13772             return false;
13773         }
13774         if(dropNode && (targetNode == dropNode || dropNode.contains(targetNode))){
13775             return false;
13776         }
13777         // reuse the object
13778         var overEvent = this.dragOverData;
13779         overEvent.tree = this.tree;
13780         overEvent.target = targetNode;
13781         overEvent.data = data;
13782         overEvent.point = pt;
13783         overEvent.source = dd;
13784         overEvent.rawEvent = e;
13785         overEvent.dropNode = dropNode;
13786         overEvent.cancel = false;  
13787         var result = this.tree.fireEvent("nodedragover", overEvent);
13788         return overEvent.cancel === false && result !== false;
13789     },
13790     
13791     getDropPoint : function(e, n, dd)
13792     {
13793         var tn = n.node;
13794         if(tn.isRoot){
13795             return tn.allowChildren !== false ? "append" : false; // always append for root
13796         }
13797         var dragEl = n.ddel;
13798         var t = Roo.lib.Dom.getY(dragEl), b = t + dragEl.offsetHeight;
13799         var y = Roo.lib.Event.getPageY(e);
13800         //var noAppend = tn.allowChildren === false || tn.isLeaf();
13801         
13802         // we may drop nodes anywhere, as long as allowChildren has not been set to false..
13803         var noAppend = tn.allowChildren === false;
13804         if(this.appendOnly || tn.parentNode.allowChildren === false){
13805             return noAppend ? false : "append";
13806         }
13807         var noBelow = false;
13808         if(!this.allowParentInsert){
13809             noBelow = tn.hasChildNodes() && tn.isExpanded();
13810         }
13811         var q = (b - t) / (noAppend ? 2 : 3);
13812         if(y >= t && y < (t + q)){
13813             return "above";
13814         }else if(!noBelow && (noAppend || y >= b-q && y <= b)){
13815             return "below";
13816         }else{
13817             return "append";
13818         }
13819     },
13820     
13821     onNodeEnter : function(n, dd, e, data)
13822     {
13823         this.cancelExpand();
13824     },
13825     
13826     onNodeOver : function(n, dd, e, data)
13827     {
13828        
13829         var pt = this.getDropPoint(e, n, dd);
13830         var node = n.node;
13831         
13832         // auto node expand check
13833         if(!this.expandProcId && pt == "append" && node.hasChildNodes() && !n.node.isExpanded()){
13834             this.queueExpand(node);
13835         }else if(pt != "append"){
13836             this.cancelExpand();
13837         }
13838         
13839         // set the insert point style on the target node
13840         var returnCls = this.dropNotAllowed;
13841         if(this.isValidDropPoint(n, pt, dd, e, data)){
13842            if(pt){
13843                var el = n.ddel;
13844                var cls;
13845                if(pt == "above"){
13846                    returnCls = n.node.isFirst() ? "x-tree-drop-ok-above" : "x-tree-drop-ok-between";
13847                    cls = "x-tree-drag-insert-above";
13848                }else if(pt == "below"){
13849                    returnCls = n.node.isLast() ? "x-tree-drop-ok-below" : "x-tree-drop-ok-between";
13850                    cls = "x-tree-drag-insert-below";
13851                }else{
13852                    returnCls = "x-tree-drop-ok-append";
13853                    cls = "x-tree-drag-append";
13854                }
13855                if(this.lastInsertClass != cls){
13856                    Roo.fly(el).replaceClass(this.lastInsertClass, cls);
13857                    this.lastInsertClass = cls;
13858                }
13859            }
13860        }
13861        return returnCls;
13862     },
13863     
13864     onNodeOut : function(n, dd, e, data){
13865         
13866         this.cancelExpand();
13867         this.removeDropIndicators(n);
13868     },
13869     
13870     onNodeDrop : function(n, dd, e, data){
13871         var point = this.getDropPoint(e, n, dd);
13872         var targetNode = n.node;
13873         targetNode.ui.startDrop();
13874         if(!this.isValidDropPoint(n, point, dd, e, data)){
13875             targetNode.ui.endDrop();
13876             return false;
13877         }
13878         // first try to find the drop node
13879         var dropNode = data.node || (dd.getTreeNode ? dd.getTreeNode(data, targetNode, point, e) : null);
13880         var dropEvent = {
13881             tree : this.tree,
13882             target: targetNode,
13883             data: data,
13884             point: point,
13885             source: dd,
13886             rawEvent: e,
13887             dropNode: dropNode,
13888             cancel: !dropNode   
13889         };
13890         var retval = this.tree.fireEvent("beforenodedrop", dropEvent);
13891         if(retval === false || dropEvent.cancel === true || !dropEvent.dropNode){
13892             targetNode.ui.endDrop();
13893             return false;
13894         }
13895         // allow target changing
13896         targetNode = dropEvent.target;
13897         if(point == "append" && !targetNode.isExpanded()){
13898             targetNode.expand(false, null, function(){
13899                 this.completeDrop(dropEvent);
13900             }.createDelegate(this));
13901         }else{
13902             this.completeDrop(dropEvent);
13903         }
13904         return true;
13905     },
13906     
13907     completeDrop : function(de){
13908         var ns = de.dropNode, p = de.point, t = de.target;
13909         if(!(ns instanceof Array)){
13910             ns = [ns];
13911         }
13912         var n;
13913         for(var i = 0, len = ns.length; i < len; i++){
13914             n = ns[i];
13915             if(p == "above"){
13916                 t.parentNode.insertBefore(n, t);
13917             }else if(p == "below"){
13918                 t.parentNode.insertBefore(n, t.nextSibling);
13919             }else{
13920                 t.appendChild(n);
13921             }
13922         }
13923         n.ui.focus();
13924         if(this.tree.hlDrop){
13925             n.ui.highlight();
13926         }
13927         t.ui.endDrop();
13928         this.tree.fireEvent("nodedrop", de);
13929     },
13930     
13931     afterNodeMoved : function(dd, data, e, targetNode, dropNode){
13932         if(this.tree.hlDrop){
13933             dropNode.ui.focus();
13934             dropNode.ui.highlight();
13935         }
13936         this.tree.fireEvent("nodedrop", this.tree, targetNode, data, dd, e);
13937     },
13938     
13939     getTree : function(){
13940         return this.tree;
13941     },
13942     
13943     removeDropIndicators : function(n){
13944         if(n && n.ddel){
13945             var el = n.ddel;
13946             Roo.fly(el).removeClass([
13947                     "x-tree-drag-insert-above",
13948                     "x-tree-drag-insert-below",
13949                     "x-tree-drag-append"]);
13950             this.lastInsertClass = "_noclass";
13951         }
13952     },
13953     
13954     beforeDragDrop : function(target, e, id){
13955         this.cancelExpand();
13956         return true;
13957     },
13958     
13959     afterRepair : function(data){
13960         if(data && Roo.enableFx){
13961             data.node.ui.highlight();
13962         }
13963         this.hideProxy();
13964     } 
13965     
13966 });
13967
13968 }
13969 /*
13970  * Based on:
13971  * Ext JS Library 1.1.1
13972  * Copyright(c) 2006-2007, Ext JS, LLC.
13973  *
13974  * Originally Released Under LGPL - original licence link has changed is not relivant.
13975  *
13976  * Fork - LGPL
13977  * <script type="text/javascript">
13978  */
13979  
13980
13981 if(Roo.dd.DragZone){
13982 Roo.tree.TreeDragZone = function(tree, config){
13983     Roo.tree.TreeDragZone.superclass.constructor.call(this, tree.getTreeEl(), config);
13984     this.tree = tree;
13985 };
13986
13987 Roo.extend(Roo.tree.TreeDragZone, Roo.dd.DragZone, {
13988     ddGroup : "TreeDD",
13989    
13990     onBeforeDrag : function(data, e){
13991         var n = data.node;
13992         return n && n.draggable && !n.disabled;
13993     },
13994      
13995     
13996     onInitDrag : function(e){
13997         var data = this.dragData;
13998         this.tree.getSelectionModel().select(data.node);
13999         this.proxy.update("");
14000         data.node.ui.appendDDGhost(this.proxy.ghost.dom);
14001         this.tree.fireEvent("startdrag", this.tree, data.node, e);
14002     },
14003     
14004     getRepairXY : function(e, data){
14005         return data.node.ui.getDDRepairXY();
14006     },
14007     
14008     onEndDrag : function(data, e){
14009         this.tree.fireEvent("enddrag", this.tree, data.node, e);
14010         
14011         
14012     },
14013     
14014     onValidDrop : function(dd, e, id){
14015         this.tree.fireEvent("dragdrop", this.tree, this.dragData.node, dd, e);
14016         this.hideProxy();
14017     },
14018     
14019     beforeInvalidDrop : function(e, id){
14020         // this scrolls the original position back into view
14021         var sm = this.tree.getSelectionModel();
14022         sm.clearSelections();
14023         sm.select(this.dragData.node);
14024     }
14025 });
14026 }/*
14027  * Based on:
14028  * Ext JS Library 1.1.1
14029  * Copyright(c) 2006-2007, Ext JS, LLC.
14030  *
14031  * Originally Released Under LGPL - original licence link has changed is not relivant.
14032  *
14033  * Fork - LGPL
14034  * <script type="text/javascript">
14035  */
14036 /**
14037  * @class Roo.tree.TreeEditor
14038  * @extends Roo.Editor
14039  * Provides editor functionality for inline tree node editing.  Any valid {@link Roo.form.Field} can be used
14040  * as the editor field.
14041  * @constructor
14042  * @param {Object} config (used to be the tree panel.)
14043  * @param {Object} oldconfig DEPRECIATED Either a prebuilt {@link Roo.form.Field} instance or a Field config object
14044  * 
14045  * @cfg {Roo.tree.TreePanel} tree The tree to bind to.
14046  * @cfg {Roo.form.TextField} field [required] The field configuration
14047  *
14048  * 
14049  */
14050 Roo.tree.TreeEditor = function(config, oldconfig) { // was -- (tree, config){
14051     var tree = config;
14052     var field;
14053     if (oldconfig) { // old style..
14054         field = oldconfig.events ? oldconfig : new Roo.form.TextField(oldconfig);
14055     } else {
14056         // new style..
14057         tree = config.tree;
14058         config.field = config.field  || {};
14059         config.field.xtype = 'TextField';
14060         field = Roo.factory(config.field, Roo.form);
14061     }
14062     config = config || {};
14063     
14064     
14065     this.addEvents({
14066         /**
14067          * @event beforenodeedit
14068          * Fires when editing is initiated, but before the value changes.  Editing can be canceled by returning
14069          * false from the handler of this event.
14070          * @param {Editor} this
14071          * @param {Roo.tree.Node} node 
14072          */
14073         "beforenodeedit" : true
14074     });
14075     
14076     //Roo.log(config);
14077     Roo.tree.TreeEditor.superclass.constructor.call(this, field, config);
14078
14079     this.tree = tree;
14080
14081     tree.on('beforeclick', this.beforeNodeClick, this);
14082     tree.getTreeEl().on('mousedown', this.hide, this);
14083     this.on('complete', this.updateNode, this);
14084     this.on('beforestartedit', this.fitToTree, this);
14085     this.on('startedit', this.bindScroll, this, {delay:10});
14086     this.on('specialkey', this.onSpecialKey, this);
14087 };
14088
14089 Roo.extend(Roo.tree.TreeEditor, Roo.Editor, {
14090     /**
14091      * @cfg {String} alignment
14092      * The position to align to (see {@link Roo.Element#alignTo} for more details, defaults to "l-l").
14093      */
14094     alignment: "l-l",
14095     // inherit
14096     autoSize: false,
14097     /**
14098      * @cfg {Boolean} hideEl
14099      * True to hide the bound element while the editor is displayed (defaults to false)
14100      */
14101     hideEl : false,
14102     /**
14103      * @cfg {String} cls
14104      * CSS class to apply to the editor (defaults to "x-small-editor x-tree-editor")
14105      */
14106     cls: "x-small-editor x-tree-editor",
14107     /**
14108      * @cfg {Boolean} shim
14109      * True to shim the editor if selects/iframes could be displayed beneath it (defaults to false)
14110      */
14111     shim:false,
14112     // inherit
14113     shadow:"frame",
14114     /**
14115      * @cfg {Number} maxWidth
14116      * The maximum width in pixels of the editor field (defaults to 250).  Note that if the maxWidth would exceed
14117      * the containing tree element's size, it will be automatically limited for you to the container width, taking
14118      * scroll and client offsets into account prior to each edit.
14119      */
14120     maxWidth: 250,
14121
14122     editDelay : 350,
14123
14124     // private
14125     fitToTree : function(ed, el){
14126         var td = this.tree.getTreeEl().dom, nd = el.dom;
14127         if(td.scrollLeft >  nd.offsetLeft){ // ensure the node left point is visible
14128             td.scrollLeft = nd.offsetLeft;
14129         }
14130         var w = Math.min(
14131                 this.maxWidth,
14132                 (td.clientWidth > 20 ? td.clientWidth : td.offsetWidth) - Math.max(0, nd.offsetLeft-td.scrollLeft) - /*cushion*/5);
14133         this.setSize(w, '');
14134         
14135         return this.fireEvent('beforenodeedit', this, this.editNode);
14136         
14137     },
14138
14139     // private
14140     triggerEdit : function(node){
14141         this.completeEdit();
14142         this.editNode = node;
14143         this.startEdit(node.ui.textNode, node.text);
14144     },
14145
14146     // private
14147     bindScroll : function(){
14148         this.tree.getTreeEl().on('scroll', this.cancelEdit, this);
14149     },
14150
14151     // private
14152     beforeNodeClick : function(node, e){
14153         var sinceLast = (this.lastClick ? this.lastClick.getElapsed() : 0);
14154         this.lastClick = new Date();
14155         if(sinceLast > this.editDelay && this.tree.getSelectionModel().isSelected(node)){
14156             e.stopEvent();
14157             this.triggerEdit(node);
14158             return false;
14159         }
14160         return true;
14161     },
14162
14163     // private
14164     updateNode : function(ed, value){
14165         this.tree.getTreeEl().un('scroll', this.cancelEdit, this);
14166         this.editNode.setText(value);
14167     },
14168
14169     // private
14170     onHide : function(){
14171         Roo.tree.TreeEditor.superclass.onHide.call(this);
14172         if(this.editNode){
14173             this.editNode.ui.focus();
14174         }
14175     },
14176
14177     // private
14178     onSpecialKey : function(field, e){
14179         var k = e.getKey();
14180         if(k == e.ESC){
14181             e.stopEvent();
14182             this.cancelEdit();
14183         }else if(k == e.ENTER && !e.hasModifier()){
14184             e.stopEvent();
14185             this.completeEdit();
14186         }
14187     }
14188 });//<Script type="text/javascript">
14189 /*
14190  * Based on:
14191  * Ext JS Library 1.1.1
14192  * Copyright(c) 2006-2007, Ext JS, LLC.
14193  *
14194  * Originally Released Under LGPL - original licence link has changed is not relivant.
14195  *
14196  * Fork - LGPL
14197  * <script type="text/javascript">
14198  */
14199  
14200 /**
14201  * Not documented??? - probably should be...
14202  */
14203
14204 Roo.tree.ColumnNodeUI = Roo.extend(Roo.tree.TreeNodeUI, {
14205     //focus: Roo.emptyFn, // prevent odd scrolling behavior
14206     
14207     renderElements : function(n, a, targetNode, bulkRender){
14208         //consel.log("renderElements?");
14209         this.indentMarkup = n.parentNode ? n.parentNode.ui.getChildIndent() : '';
14210
14211         var t = n.getOwnerTree();
14212         var tid = Pman.Tab.Document_TypesTree.tree.el.id;
14213         
14214         var cols = t.columns;
14215         var bw = t.borderWidth;
14216         var c = cols[0];
14217         var href = a.href ? a.href : Roo.isGecko ? "" : "#";
14218          var cb = typeof a.checked == "boolean";
14219         var tx = String.format('{0}',n.text || (c.renderer ? c.renderer(a[c.dataIndex], n, a) : a[c.dataIndex]));
14220         var colcls = 'x-t-' + tid + '-c0';
14221         var buf = [
14222             '<li class="x-tree-node">',
14223             
14224                 
14225                 '<div class="x-tree-node-el ', a.cls,'">',
14226                     // extran...
14227                     '<div class="x-tree-col ', colcls, '" style="width:', c.width-bw, 'px;">',
14228                 
14229                 
14230                         '<span class="x-tree-node-indent">',this.indentMarkup,'</span>',
14231                         '<img src="', this.emptyIcon, '" class="x-tree-ec-icon  " />',
14232                         '<img src="', a.icon || this.emptyIcon, '" class="x-tree-node-icon',
14233                            (a.icon ? ' x-tree-node-inline-icon' : ''),
14234                            (a.iconCls ? ' '+a.iconCls : ''),
14235                            '" unselectable="on" />',
14236                         (cb ? ('<input class="x-tree-node-cb" type="checkbox" ' + 
14237                              (a.checked ? 'checked="checked" />' : ' />')) : ''),
14238                              
14239                         '<a class="x-tree-node-anchor" hidefocus="on" href="',href,'" tabIndex="1" ',
14240                             (a.hrefTarget ? ' target="' +a.hrefTarget + '"' : ''), '>',
14241                             '<span unselectable="on" qtip="' + tx + '">',
14242                              tx,
14243                              '</span></a>' ,
14244                     '</div>',
14245                      '<a class="x-tree-node-anchor" hidefocus="on" href="',href,'" tabIndex="1" ',
14246                             (a.hrefTarget ? ' target="' +a.hrefTarget + '"' : ''), '>'
14247                  ];
14248         for(var i = 1, len = cols.length; i < len; i++){
14249             c = cols[i];
14250             colcls = 'x-t-' + tid + '-c' +i;
14251             tx = String.format('{0}', (c.renderer ? c.renderer(a[c.dataIndex], n, a) : a[c.dataIndex]));
14252             buf.push('<div class="x-tree-col ', colcls, ' ' ,(c.cls?c.cls:''),'" style="width:',c.width-bw,'px;">',
14253                         '<div class="x-tree-col-text" qtip="' + tx +'">',tx,"</div>",
14254                       "</div>");
14255          }
14256          
14257          buf.push(
14258             '</a>',
14259             '<div class="x-clear"></div></div>',
14260             '<ul class="x-tree-node-ct" style="display:none;"></ul>',
14261             "</li>");
14262         
14263         if(bulkRender !== true && n.nextSibling && n.nextSibling.ui.getEl()){
14264             this.wrap = Roo.DomHelper.insertHtml("beforeBegin",
14265                                 n.nextSibling.ui.getEl(), buf.join(""));
14266         }else{
14267             this.wrap = Roo.DomHelper.insertHtml("beforeEnd", targetNode, buf.join(""));
14268         }
14269         var el = this.wrap.firstChild;
14270         this.elRow = el;
14271         this.elNode = el.firstChild;
14272         this.ranchor = el.childNodes[1];
14273         this.ctNode = this.wrap.childNodes[1];
14274         var cs = el.firstChild.childNodes;
14275         this.indentNode = cs[0];
14276         this.ecNode = cs[1];
14277         this.iconNode = cs[2];
14278         var index = 3;
14279         if(cb){
14280             this.checkbox = cs[3];
14281             index++;
14282         }
14283         this.anchor = cs[index];
14284         
14285         this.textNode = cs[index].firstChild;
14286         
14287         //el.on("click", this.onClick, this);
14288         //el.on("dblclick", this.onDblClick, this);
14289         
14290         
14291        // console.log(this);
14292     },
14293     initEvents : function(){
14294         Roo.tree.ColumnNodeUI.superclass.initEvents.call(this);
14295         
14296             
14297         var a = this.ranchor;
14298
14299         var el = Roo.get(a);
14300
14301         if(Roo.isOpera){ // opera render bug ignores the CSS
14302             el.setStyle("text-decoration", "none");
14303         }
14304
14305         el.on("click", this.onClick, this);
14306         el.on("dblclick", this.onDblClick, this);
14307         el.on("contextmenu", this.onContextMenu, this);
14308         
14309     },
14310     
14311     /*onSelectedChange : function(state){
14312         if(state){
14313             this.focus();
14314             this.addClass("x-tree-selected");
14315         }else{
14316             //this.blur();
14317             this.removeClass("x-tree-selected");
14318         }
14319     },*/
14320     addClass : function(cls){
14321         if(this.elRow){
14322             Roo.fly(this.elRow).addClass(cls);
14323         }
14324         
14325     },
14326     
14327     
14328     removeClass : function(cls){
14329         if(this.elRow){
14330             Roo.fly(this.elRow).removeClass(cls);
14331         }
14332     }
14333
14334     
14335     
14336 });//<Script type="text/javascript">
14337
14338 /*
14339  * Based on:
14340  * Ext JS Library 1.1.1
14341  * Copyright(c) 2006-2007, Ext JS, LLC.
14342  *
14343  * Originally Released Under LGPL - original licence link has changed is not relivant.
14344  *
14345  * Fork - LGPL
14346  * <script type="text/javascript">
14347  */
14348  
14349
14350 /**
14351  * @class Roo.tree.ColumnTree
14352  * @extends Roo.tree.TreePanel
14353  * @cfg {Object} columns  Including width, header, renderer, cls, dataIndex 
14354  * @cfg {int} borderWidth  compined right/left border allowance
14355  * @constructor
14356  * @param {String/HTMLElement/Element} el The container element
14357  * @param {Object} config
14358  */
14359 Roo.tree.ColumnTree =  function(el, config)
14360 {
14361    Roo.tree.ColumnTree.superclass.constructor.call(this, el , config);
14362    this.addEvents({
14363         /**
14364         * @event resize
14365         * Fire this event on a container when it resizes
14366         * @param {int} w Width
14367         * @param {int} h Height
14368         */
14369        "resize" : true
14370     });
14371     this.on('resize', this.onResize, this);
14372 };
14373
14374 Roo.extend(Roo.tree.ColumnTree, Roo.tree.TreePanel, {
14375     //lines:false,
14376     
14377     
14378     borderWidth: Roo.isBorderBox ? 0 : 2, 
14379     headEls : false,
14380     
14381     render : function(){
14382         // add the header.....
14383        
14384         Roo.tree.ColumnTree.superclass.render.apply(this);
14385         
14386         this.el.addClass('x-column-tree');
14387         
14388         this.headers = this.el.createChild(
14389             {cls:'x-tree-headers'},this.innerCt.dom);
14390    
14391         var cols = this.columns, c;
14392         var totalWidth = 0;
14393         this.headEls = [];
14394         var  len = cols.length;
14395         for(var i = 0; i < len; i++){
14396              c = cols[i];
14397              totalWidth += c.width;
14398             this.headEls.push(this.headers.createChild({
14399                  cls:'x-tree-hd ' + (c.cls?c.cls+'-hd':''),
14400                  cn: {
14401                      cls:'x-tree-hd-text',
14402                      html: c.header
14403                  },
14404                  style:'width:'+(c.width-this.borderWidth)+'px;'
14405              }));
14406         }
14407         this.headers.createChild({cls:'x-clear'});
14408         // prevent floats from wrapping when clipped
14409         this.headers.setWidth(totalWidth);
14410         //this.innerCt.setWidth(totalWidth);
14411         this.innerCt.setStyle({ overflow: 'auto' });
14412         this.onResize(this.width, this.height);
14413              
14414         
14415     },
14416     onResize : function(w,h)
14417     {
14418         this.height = h;
14419         this.width = w;
14420         // resize cols..
14421         this.innerCt.setWidth(this.width);
14422         this.innerCt.setHeight(this.height-20);
14423         
14424         // headers...
14425         var cols = this.columns, c;
14426         var totalWidth = 0;
14427         var expEl = false;
14428         var len = cols.length;
14429         for(var i = 0; i < len; i++){
14430             c = cols[i];
14431             if (this.autoExpandColumn !== false && c.dataIndex == this.autoExpandColumn) {
14432                 // it's the expander..
14433                 expEl  = this.headEls[i];
14434                 continue;
14435             }
14436             totalWidth += c.width;
14437             
14438         }
14439         if (expEl) {
14440             expEl.setWidth(  ((w - totalWidth)-this.borderWidth - 20));
14441         }
14442         this.headers.setWidth(w-20);
14443
14444         
14445         
14446         
14447     }
14448 });
14449 /*
14450  * Based on:
14451  * Ext JS Library 1.1.1
14452  * Copyright(c) 2006-2007, Ext JS, LLC.
14453  *
14454  * Originally Released Under LGPL - original licence link has changed is not relivant.
14455  *
14456  * Fork - LGPL
14457  * <script type="text/javascript">
14458  */
14459  
14460 /**
14461  * @class Roo.menu.Menu
14462  * @extends Roo.util.Observable
14463  * @children Roo.menu.Item Roo.menu.Separator Roo.menu.TextItem
14464  * A menu object.  This is the container to which you add all other menu items.  Menu can also serve a as a base class
14465  * when you want a specialzed menu based off of another component (like {@link Roo.menu.DateMenu} for example).
14466  * @constructor
14467  * Creates a new Menu
14468  * @param {Object} config Configuration options
14469  */
14470 Roo.menu.Menu = function(config){
14471     
14472     Roo.menu.Menu.superclass.constructor.call(this, config);
14473     
14474     this.id = this.id || Roo.id();
14475     this.addEvents({
14476         /**
14477          * @event beforeshow
14478          * Fires before this menu is displayed
14479          * @param {Roo.menu.Menu} this
14480          */
14481         beforeshow : true,
14482         /**
14483          * @event beforehide
14484          * Fires before this menu is hidden
14485          * @param {Roo.menu.Menu} this
14486          */
14487         beforehide : true,
14488         /**
14489          * @event show
14490          * Fires after this menu is displayed
14491          * @param {Roo.menu.Menu} this
14492          */
14493         show : true,
14494         /**
14495          * @event hide
14496          * Fires after this menu is hidden
14497          * @param {Roo.menu.Menu} this
14498          */
14499         hide : true,
14500         /**
14501          * @event click
14502          * Fires when this menu is clicked (or when the enter key is pressed while it is active)
14503          * @param {Roo.menu.Menu} this
14504          * @param {Roo.menu.Item} menuItem The menu item that was clicked
14505          * @param {Roo.EventObject} e
14506          */
14507         click : true,
14508         /**
14509          * @event mouseover
14510          * Fires when the mouse is hovering over this menu
14511          * @param {Roo.menu.Menu} this
14512          * @param {Roo.EventObject} e
14513          * @param {Roo.menu.Item} menuItem The menu item that was clicked
14514          */
14515         mouseover : true,
14516         /**
14517          * @event mouseout
14518          * Fires when the mouse exits this menu
14519          * @param {Roo.menu.Menu} this
14520          * @param {Roo.EventObject} e
14521          * @param {Roo.menu.Item} menuItem The menu item that was clicked
14522          */
14523         mouseout : true,
14524         /**
14525          * @event itemclick
14526          * Fires when a menu item contained in this menu is clicked
14527          * @param {Roo.menu.BaseItem} baseItem The BaseItem that was clicked
14528          * @param {Roo.EventObject} e
14529          */
14530         itemclick: true
14531     });
14532     if (this.registerMenu) {
14533         Roo.menu.MenuMgr.register(this);
14534     }
14535     
14536     var mis = this.items;
14537     this.items = new Roo.util.MixedCollection();
14538     if(mis){
14539         this.add.apply(this, mis);
14540     }
14541 };
14542
14543 Roo.extend(Roo.menu.Menu, Roo.util.Observable, {
14544     /**
14545      * @cfg {Number} minWidth The minimum width of the menu in pixels (defaults to 120)
14546      */
14547     minWidth : 120,
14548     /**
14549      * @cfg {Boolean/String} shadow True or "sides" for the default effect, "frame" for 4-way shadow, and "drop"
14550      * for bottom-right shadow (defaults to "sides")
14551      */
14552     shadow : "sides",
14553     /**
14554      * @cfg {String} subMenuAlign The {@link Roo.Element#alignTo} anchor position value to use for submenus of
14555      * this menu (defaults to "tl-tr?")
14556      */
14557     subMenuAlign : "tl-tr?",
14558     /**
14559      * @cfg {String} defaultAlign The default {@link Roo.Element#alignTo) anchor position value for this menu
14560      * relative to its element of origin (defaults to "tl-bl?")
14561      */
14562     defaultAlign : "tl-bl?",
14563     /**
14564      * @cfg {Boolean} allowOtherMenus True to allow multiple menus to be displayed at the same time (defaults to false)
14565      */
14566     allowOtherMenus : false,
14567     /**
14568      * @cfg {Boolean} registerMenu True (default) - means that clicking on screen etc. hides it.
14569      */
14570     registerMenu : true,
14571
14572     hidden:true,
14573
14574     // private
14575     render : function(){
14576         if(this.el){
14577             return;
14578         }
14579         var el = this.el = new Roo.Layer({
14580             cls: "x-menu",
14581             shadow:this.shadow,
14582             constrain: false,
14583             parentEl: this.parentEl || document.body,
14584             zindex:15000
14585         });
14586
14587         this.keyNav = new Roo.menu.MenuNav(this);
14588
14589         if(this.plain){
14590             el.addClass("x-menu-plain");
14591         }
14592         if(this.cls){
14593             el.addClass(this.cls);
14594         }
14595         // generic focus element
14596         this.focusEl = el.createChild({
14597             tag: "a", cls: "x-menu-focus", href: "#", onclick: "return false;", tabIndex:"-1"
14598         });
14599         var ul = el.createChild({tag: "ul", cls: "x-menu-list"});
14600         //disabling touch- as it's causing issues ..
14601         //ul.on(Roo.isTouch ? 'touchstart' : 'click'   , this.onClick, this);
14602         ul.on('click'   , this.onClick, this);
14603         
14604         
14605         ul.on("mouseover", this.onMouseOver, this);
14606         ul.on("mouseout", this.onMouseOut, this);
14607         this.items.each(function(item){
14608             if (item.hidden) {
14609                 return;
14610             }
14611             
14612             var li = document.createElement("li");
14613             li.className = "x-menu-list-item";
14614             ul.dom.appendChild(li);
14615             item.render(li, this);
14616         }, this);
14617         this.ul = ul;
14618         this.autoWidth();
14619     },
14620
14621     // private
14622     autoWidth : function(){
14623         var el = this.el, ul = this.ul;
14624         if(!el){
14625             return;
14626         }
14627         var w = this.width;
14628         if(w){
14629             el.setWidth(w);
14630         }else if(Roo.isIE){
14631             el.setWidth(this.minWidth);
14632             var t = el.dom.offsetWidth; // force recalc
14633             el.setWidth(ul.getWidth()+el.getFrameWidth("lr"));
14634         }
14635     },
14636
14637     // private
14638     delayAutoWidth : function(){
14639         if(this.rendered){
14640             if(!this.awTask){
14641                 this.awTask = new Roo.util.DelayedTask(this.autoWidth, this);
14642             }
14643             this.awTask.delay(20);
14644         }
14645     },
14646
14647     // private
14648     findTargetItem : function(e){
14649         var t = e.getTarget(".x-menu-list-item", this.ul,  true);
14650         if(t && t.menuItemId){
14651             return this.items.get(t.menuItemId);
14652         }
14653     },
14654
14655     // private
14656     onClick : function(e){
14657         Roo.log("menu.onClick");
14658         var t = this.findTargetItem(e);
14659         if(!t){
14660             return;
14661         }
14662         Roo.log(e);
14663         if (Roo.isTouch && e.type == 'touchstart' && t.menu  && !t.disabled) {
14664             if(t == this.activeItem && t.shouldDeactivate(e)){
14665                 this.activeItem.deactivate();
14666                 delete this.activeItem;
14667                 return;
14668             }
14669             if(t.canActivate){
14670                 this.setActiveItem(t, true);
14671             }
14672             return;
14673             
14674             
14675         }
14676         
14677         t.onClick(e);
14678         this.fireEvent("click", this, t, e);
14679     },
14680
14681     // private
14682     setActiveItem : function(item, autoExpand){
14683         if(item != this.activeItem){
14684             if(this.activeItem){
14685                 this.activeItem.deactivate();
14686             }
14687             this.activeItem = item;
14688             item.activate(autoExpand);
14689         }else if(autoExpand){
14690             item.expandMenu();
14691         }
14692     },
14693
14694     // private
14695     tryActivate : function(start, step){
14696         var items = this.items;
14697         for(var i = start, len = items.length; i >= 0 && i < len; i+= step){
14698             var item = items.get(i);
14699             if(!item.disabled && item.canActivate){
14700                 this.setActiveItem(item, false);
14701                 return item;
14702             }
14703         }
14704         return false;
14705     },
14706
14707     // private
14708     onMouseOver : function(e){
14709         var t;
14710         if(t = this.findTargetItem(e)){
14711             if(t.canActivate && !t.disabled){
14712                 this.setActiveItem(t, true);
14713             }
14714         }
14715         this.fireEvent("mouseover", this, e, t);
14716     },
14717
14718     // private
14719     onMouseOut : function(e){
14720         var t;
14721         if(t = this.findTargetItem(e)){
14722             if(t == this.activeItem && t.shouldDeactivate(e)){
14723                 this.activeItem.deactivate();
14724                 delete this.activeItem;
14725             }
14726         }
14727         this.fireEvent("mouseout", this, e, t);
14728     },
14729
14730     /**
14731      * Read-only.  Returns true if the menu is currently displayed, else false.
14732      * @type Boolean
14733      */
14734     isVisible : function(){
14735         return this.el && !this.hidden;
14736     },
14737
14738     /**
14739      * Displays this menu relative to another element
14740      * @param {String/HTMLElement/Roo.Element} element The element to align to
14741      * @param {String} position (optional) The {@link Roo.Element#alignTo} anchor position to use in aligning to
14742      * the element (defaults to this.defaultAlign)
14743      * @param {Roo.menu.Menu} parentMenu (optional) This menu's parent menu, if applicable (defaults to undefined)
14744      */
14745     show : function(el, pos, parentMenu){
14746         this.parentMenu = parentMenu;
14747         if(!this.el){
14748             this.render();
14749         }
14750         this.fireEvent("beforeshow", this);
14751         this.showAt(this.el.getAlignToXY(el, pos || this.defaultAlign), parentMenu, false);
14752     },
14753
14754     /**
14755      * Displays this menu at a specific xy position
14756      * @param {Array} xyPosition Contains X & Y [x, y] values for the position at which to show the menu (coordinates are page-based)
14757      * @param {Roo.menu.Menu} parentMenu (optional) This menu's parent menu, if applicable (defaults to undefined)
14758      */
14759     showAt : function(xy, parentMenu, /* private: */_e){
14760         this.parentMenu = parentMenu;
14761         if(!this.el){
14762             this.render();
14763         }
14764         if(_e !== false){
14765             this.fireEvent("beforeshow", this);
14766             xy = this.el.adjustForConstraints(xy);
14767         }
14768         this.el.setXY(xy);
14769         this.el.show();
14770         this.hidden = false;
14771         this.focus();
14772         this.fireEvent("show", this);
14773     },
14774
14775     focus : function(){
14776         if(!this.hidden){
14777             this.doFocus.defer(50, this);
14778         }
14779     },
14780
14781     doFocus : function(){
14782         if(!this.hidden){
14783             this.focusEl.focus();
14784         }
14785     },
14786
14787     /**
14788      * Hides this menu and optionally all parent menus
14789      * @param {Boolean} deep (optional) True to hide all parent menus recursively, if any (defaults to false)
14790      */
14791     hide : function(deep){
14792         if(this.el && this.isVisible()){
14793             this.fireEvent("beforehide", this);
14794             if(this.activeItem){
14795                 this.activeItem.deactivate();
14796                 this.activeItem = null;
14797             }
14798             this.el.hide();
14799             this.hidden = true;
14800             this.fireEvent("hide", this);
14801         }
14802         if(deep === true && this.parentMenu){
14803             this.parentMenu.hide(true);
14804         }
14805     },
14806
14807     /**
14808      * Addds one or more items of any type supported by the Menu class, or that can be converted into menu items.
14809      * Any of the following are valid:
14810      * <ul>
14811      * <li>Any menu item object based on {@link Roo.menu.Item}</li>
14812      * <li>An HTMLElement object which will be converted to a menu item</li>
14813      * <li>A menu item config object that will be created as a new menu item</li>
14814      * <li>A string, which can either be '-' or 'separator' to add a menu separator, otherwise
14815      * it will be converted into a {@link Roo.menu.TextItem} and added</li>
14816      * </ul>
14817      * Usage:
14818      * <pre><code>
14819 // Create the menu
14820 var menu = new Roo.menu.Menu();
14821
14822 // Create a menu item to add by reference
14823 var menuItem = new Roo.menu.Item({ text: 'New Item!' });
14824
14825 // Add a bunch of items at once using different methods.
14826 // Only the last item added will be returned.
14827 var item = menu.add(
14828     menuItem,                // add existing item by ref
14829     'Dynamic Item',          // new TextItem
14830     '-',                     // new separator
14831     { text: 'Config Item' }  // new item by config
14832 );
14833 </code></pre>
14834      * @param {Mixed} args One or more menu items, menu item configs or other objects that can be converted to menu items
14835      * @return {Roo.menu.Item} The menu item that was added, or the last one if multiple items were added
14836      */
14837     add : function(){
14838         var a = arguments, l = a.length, item;
14839         for(var i = 0; i < l; i++){
14840             var el = a[i];
14841             if ((typeof(el) == "object") && el.xtype && el.xns) {
14842                 el = Roo.factory(el, Roo.menu);
14843             }
14844             
14845             if(el.render){ // some kind of Item
14846                 item = this.addItem(el);
14847             }else if(typeof el == "string"){ // string
14848                 if(el == "separator" || el == "-"){
14849                     item = this.addSeparator();
14850                 }else{
14851                     item = this.addText(el);
14852                 }
14853             }else if(el.tagName || el.el){ // element
14854                 item = this.addElement(el);
14855             }else if(typeof el == "object"){ // must be menu item config?
14856                 item = this.addMenuItem(el);
14857             }
14858         }
14859         return item;
14860     },
14861
14862     /**
14863      * Returns this menu's underlying {@link Roo.Element} object
14864      * @return {Roo.Element} The element
14865      */
14866     getEl : function(){
14867         if(!this.el){
14868             this.render();
14869         }
14870         return this.el;
14871     },
14872
14873     /**
14874      * Adds a separator bar to the menu
14875      * @return {Roo.menu.Item} The menu item that was added
14876      */
14877     addSeparator : function(){
14878         return this.addItem(new Roo.menu.Separator());
14879     },
14880
14881     /**
14882      * Adds an {@link Roo.Element} object to the menu
14883      * @param {String/HTMLElement/Roo.Element} el The element or DOM node to add, or its id
14884      * @return {Roo.menu.Item} The menu item that was added
14885      */
14886     addElement : function(el){
14887         return this.addItem(new Roo.menu.BaseItem(el));
14888     },
14889
14890     /**
14891      * Adds an existing object based on {@link Roo.menu.Item} to the menu
14892      * @param {Roo.menu.Item} item The menu item to add
14893      * @return {Roo.menu.Item} The menu item that was added
14894      */
14895     addItem : function(item){
14896         this.items.add(item);
14897         if(this.ul){
14898             var li = document.createElement("li");
14899             li.className = "x-menu-list-item";
14900             this.ul.dom.appendChild(li);
14901             item.render(li, this);
14902             this.delayAutoWidth();
14903         }
14904         return item;
14905     },
14906
14907     /**
14908      * Creates a new {@link Roo.menu.Item} based an the supplied config object and adds it to the menu
14909      * @param {Object} config A MenuItem config object
14910      * @return {Roo.menu.Item} The menu item that was added
14911      */
14912     addMenuItem : function(config){
14913         if(!(config instanceof Roo.menu.Item)){
14914             if(typeof config.checked == "boolean"){ // must be check menu item config?
14915                 config = new Roo.menu.CheckItem(config);
14916             }else{
14917                 config = new Roo.menu.Item(config);
14918             }
14919         }
14920         return this.addItem(config);
14921     },
14922
14923     /**
14924      * Creates a new {@link Roo.menu.TextItem} with the supplied text and adds it to the menu
14925      * @param {String} text The text to display in the menu item
14926      * @return {Roo.menu.Item} The menu item that was added
14927      */
14928     addText : function(text){
14929         return this.addItem(new Roo.menu.TextItem({ text : text }));
14930     },
14931
14932     /**
14933      * Inserts an existing object based on {@link Roo.menu.Item} to the menu at a specified index
14934      * @param {Number} index The index in the menu's list of current items where the new item should be inserted
14935      * @param {Roo.menu.Item} item The menu item to add
14936      * @return {Roo.menu.Item} The menu item that was added
14937      */
14938     insert : function(index, item){
14939         this.items.insert(index, item);
14940         if(this.ul){
14941             var li = document.createElement("li");
14942             li.className = "x-menu-list-item";
14943             this.ul.dom.insertBefore(li, this.ul.dom.childNodes[index]);
14944             item.render(li, this);
14945             this.delayAutoWidth();
14946         }
14947         return item;
14948     },
14949
14950     /**
14951      * Removes an {@link Roo.menu.Item} from the menu and destroys the object
14952      * @param {Roo.menu.Item} item The menu item to remove
14953      */
14954     remove : function(item){
14955         this.items.removeKey(item.id);
14956         item.destroy();
14957     },
14958
14959     /**
14960      * Removes and destroys all items in the menu
14961      */
14962     removeAll : function(){
14963         var f;
14964         while(f = this.items.first()){
14965             this.remove(f);
14966         }
14967     }
14968 });
14969
14970 // MenuNav is a private utility class used internally by the Menu
14971 Roo.menu.MenuNav = function(menu){
14972     Roo.menu.MenuNav.superclass.constructor.call(this, menu.el);
14973     this.scope = this.menu = menu;
14974 };
14975
14976 Roo.extend(Roo.menu.MenuNav, Roo.KeyNav, {
14977     doRelay : function(e, h){
14978         var k = e.getKey();
14979         if(!this.menu.activeItem && e.isNavKeyPress() && k != e.SPACE && k != e.RETURN){
14980             this.menu.tryActivate(0, 1);
14981             return false;
14982         }
14983         return h.call(this.scope || this, e, this.menu);
14984     },
14985
14986     up : function(e, m){
14987         if(!m.tryActivate(m.items.indexOf(m.activeItem)-1, -1)){
14988             m.tryActivate(m.items.length-1, -1);
14989         }
14990     },
14991
14992     down : function(e, m){
14993         if(!m.tryActivate(m.items.indexOf(m.activeItem)+1, 1)){
14994             m.tryActivate(0, 1);
14995         }
14996     },
14997
14998     right : function(e, m){
14999         if(m.activeItem){
15000             m.activeItem.expandMenu(true);
15001         }
15002     },
15003
15004     left : function(e, m){
15005         m.hide();
15006         if(m.parentMenu && m.parentMenu.activeItem){
15007             m.parentMenu.activeItem.activate();
15008         }
15009     },
15010
15011     enter : function(e, m){
15012         if(m.activeItem){
15013             e.stopPropagation();
15014             m.activeItem.onClick(e);
15015             m.fireEvent("click", this, m.activeItem);
15016             return true;
15017         }
15018     }
15019 });/*
15020  * Based on:
15021  * Ext JS Library 1.1.1
15022  * Copyright(c) 2006-2007, Ext JS, LLC.
15023  *
15024  * Originally Released Under LGPL - original licence link has changed is not relivant.
15025  *
15026  * Fork - LGPL
15027  * <script type="text/javascript">
15028  */
15029  
15030 /**
15031  * @class Roo.menu.MenuMgr
15032  * Provides a common registry of all menu items on a page so that they can be easily accessed by id.
15033  * @static
15034  */
15035 Roo.menu.MenuMgr = function(){
15036    var menus, active, groups = {}, attached = false, lastShow = new Date();
15037
15038    // private - called when first menu is created
15039    function init(){
15040        menus = {};
15041        active = new Roo.util.MixedCollection();
15042        Roo.get(document).addKeyListener(27, function(){
15043            if(active.length > 0){
15044                hideAll();
15045            }
15046        });
15047    }
15048
15049    // private
15050    function hideAll(){
15051        if(active && active.length > 0){
15052            var c = active.clone();
15053            c.each(function(m){
15054                m.hide();
15055            });
15056        }
15057    }
15058
15059    // private
15060    function onHide(m){
15061        active.remove(m);
15062        if(active.length < 1){
15063            Roo.get(document).un("mousedown", onMouseDown);
15064            attached = false;
15065        }
15066    }
15067
15068    // private
15069    function onShow(m){
15070        var last = active.last();
15071        lastShow = new Date();
15072        active.add(m);
15073        if(!attached){
15074            Roo.get(document).on("mousedown", onMouseDown);
15075            attached = true;
15076        }
15077        if(m.parentMenu){
15078           m.getEl().setZIndex(parseInt(m.parentMenu.getEl().getStyle("z-index"), 10) + 3);
15079           m.parentMenu.activeChild = m;
15080        }else if(last && last.isVisible()){
15081           m.getEl().setZIndex(parseInt(last.getEl().getStyle("z-index"), 10) + 3);
15082        }
15083    }
15084
15085    // private
15086    function onBeforeHide(m){
15087        if(m.activeChild){
15088            m.activeChild.hide();
15089        }
15090        if(m.autoHideTimer){
15091            clearTimeout(m.autoHideTimer);
15092            delete m.autoHideTimer;
15093        }
15094    }
15095
15096    // private
15097    function onBeforeShow(m){
15098        var pm = m.parentMenu;
15099        if(!pm && !m.allowOtherMenus){
15100            hideAll();
15101        }else if(pm && pm.activeChild && active != m){
15102            pm.activeChild.hide();
15103        }
15104    }
15105
15106    // private
15107    function onMouseDown(e){
15108        if(lastShow.getElapsed() > 50 && active.length > 0 && !e.getTarget(".x-menu")){
15109            hideAll();
15110        }
15111    }
15112
15113    // private
15114    function onBeforeCheck(mi, state){
15115        if(state){
15116            var g = groups[mi.group];
15117            for(var i = 0, l = g.length; i < l; i++){
15118                if(g[i] != mi){
15119                    g[i].setChecked(false);
15120                }
15121            }
15122        }
15123    }
15124
15125    return {
15126
15127        /**
15128         * Hides all menus that are currently visible
15129         */
15130        hideAll : function(){
15131             hideAll();  
15132        },
15133
15134        // private
15135        register : function(menu){
15136            if(!menus){
15137                init();
15138            }
15139            menus[menu.id] = menu;
15140            menu.on("beforehide", onBeforeHide);
15141            menu.on("hide", onHide);
15142            menu.on("beforeshow", onBeforeShow);
15143            menu.on("show", onShow);
15144            var g = menu.group;
15145            if(g && menu.events["checkchange"]){
15146                if(!groups[g]){
15147                    groups[g] = [];
15148                }
15149                groups[g].push(menu);
15150                menu.on("checkchange", onCheck);
15151            }
15152        },
15153
15154         /**
15155          * Returns a {@link Roo.menu.Menu} object
15156          * @param {String/Object} menu The string menu id, an existing menu object reference, or a Menu config that will
15157          * be used to generate and return a new Menu instance.
15158          */
15159        get : function(menu){
15160            if(typeof menu == "string"){ // menu id
15161                return menus[menu];
15162            }else if(menu.events){  // menu instance
15163                return menu;
15164            }else if(typeof menu.length == 'number'){ // array of menu items?
15165                return new Roo.menu.Menu({items:menu});
15166            }else{ // otherwise, must be a config
15167                return new Roo.menu.Menu(menu);
15168            }
15169        },
15170
15171        // private
15172        unregister : function(menu){
15173            delete menus[menu.id];
15174            menu.un("beforehide", onBeforeHide);
15175            menu.un("hide", onHide);
15176            menu.un("beforeshow", onBeforeShow);
15177            menu.un("show", onShow);
15178            var g = menu.group;
15179            if(g && menu.events["checkchange"]){
15180                groups[g].remove(menu);
15181                menu.un("checkchange", onCheck);
15182            }
15183        },
15184
15185        // private
15186        registerCheckable : function(menuItem){
15187            var g = menuItem.group;
15188            if(g){
15189                if(!groups[g]){
15190                    groups[g] = [];
15191                }
15192                groups[g].push(menuItem);
15193                menuItem.on("beforecheckchange", onBeforeCheck);
15194            }
15195        },
15196
15197        // private
15198        unregisterCheckable : function(menuItem){
15199            var g = menuItem.group;
15200            if(g){
15201                groups[g].remove(menuItem);
15202                menuItem.un("beforecheckchange", onBeforeCheck);
15203            }
15204        }
15205    };
15206 }();/*
15207  * Based on:
15208  * Ext JS Library 1.1.1
15209  * Copyright(c) 2006-2007, Ext JS, LLC.
15210  *
15211  * Originally Released Under LGPL - original licence link has changed is not relivant.
15212  *
15213  * Fork - LGPL
15214  * <script type="text/javascript">
15215  */
15216  
15217
15218 /**
15219  * @class Roo.menu.BaseItem
15220  * @extends Roo.Component
15221  * @abstract
15222  * The base class for all items that render into menus.  BaseItem provides default rendering, activated state
15223  * management and base configuration options shared by all menu components.
15224  * @constructor
15225  * Creates a new BaseItem
15226  * @param {Object} config Configuration options
15227  */
15228 Roo.menu.BaseItem = function(config){
15229     Roo.menu.BaseItem.superclass.constructor.call(this, config);
15230
15231     this.addEvents({
15232         /**
15233          * @event click
15234          * Fires when this item is clicked
15235          * @param {Roo.menu.BaseItem} this
15236          * @param {Roo.EventObject} e
15237          */
15238         click: true,
15239         /**
15240          * @event activate
15241          * Fires when this item is activated
15242          * @param {Roo.menu.BaseItem} this
15243          */
15244         activate : true,
15245         /**
15246          * @event deactivate
15247          * Fires when this item is deactivated
15248          * @param {Roo.menu.BaseItem} this
15249          */
15250         deactivate : true
15251     });
15252
15253     if(this.handler){
15254         this.on("click", this.handler, this.scope, true);
15255     }
15256 };
15257
15258 Roo.extend(Roo.menu.BaseItem, Roo.Component, {
15259     /**
15260      * @cfg {Function} handler
15261      * A function that will handle the click event of this menu item (defaults to undefined)
15262      */
15263     /**
15264      * @cfg {Boolean} canActivate True if this item can be visually activated (defaults to false)
15265      */
15266     canActivate : false,
15267     
15268      /**
15269      * @cfg {Boolean} hidden True to prevent creation of this menu item (defaults to false)
15270      */
15271     hidden: false,
15272     
15273     /**
15274      * @cfg {String} activeClass The CSS class to use when the item becomes activated (defaults to "x-menu-item-active")
15275      */
15276     activeClass : "x-menu-item-active",
15277     /**
15278      * @cfg {Boolean} hideOnClick True to hide the containing menu after this item is clicked (defaults to true)
15279      */
15280     hideOnClick : true,
15281     /**
15282      * @cfg {Number} hideDelay Length of time in milliseconds to wait before hiding after a click (defaults to 100)
15283      */
15284     hideDelay : 100,
15285
15286     // private
15287     ctype: "Roo.menu.BaseItem",
15288
15289     // private
15290     actionMode : "container",
15291
15292     // private
15293     render : function(container, parentMenu){
15294         this.parentMenu = parentMenu;
15295         Roo.menu.BaseItem.superclass.render.call(this, container);
15296         this.container.menuItemId = this.id;
15297     },
15298
15299     // private
15300     onRender : function(container, position){
15301         this.el = Roo.get(this.el);
15302         container.dom.appendChild(this.el.dom);
15303     },
15304
15305     // private
15306     onClick : function(e){
15307         if(!this.disabled && this.fireEvent("click", this, e) !== false
15308                 && this.parentMenu.fireEvent("itemclick", this, e) !== false){
15309             this.handleClick(e);
15310         }else{
15311             e.stopEvent();
15312         }
15313     },
15314
15315     // private
15316     activate : function(){
15317         if(this.disabled){
15318             return false;
15319         }
15320         var li = this.container;
15321         li.addClass(this.activeClass);
15322         this.region = li.getRegion().adjust(2, 2, -2, -2);
15323         this.fireEvent("activate", this);
15324         return true;
15325     },
15326
15327     // private
15328     deactivate : function(){
15329         this.container.removeClass(this.activeClass);
15330         this.fireEvent("deactivate", this);
15331     },
15332
15333     // private
15334     shouldDeactivate : function(e){
15335         return !this.region || !this.region.contains(e.getPoint());
15336     },
15337
15338     // private
15339     handleClick : function(e){
15340         if(this.hideOnClick){
15341             this.parentMenu.hide.defer(this.hideDelay, this.parentMenu, [true]);
15342         }
15343     },
15344
15345     // private
15346     expandMenu : function(autoActivate){
15347         // do nothing
15348     },
15349
15350     // private
15351     hideMenu : function(){
15352         // do nothing
15353     }
15354 });/*
15355  * Based on:
15356  * Ext JS Library 1.1.1
15357  * Copyright(c) 2006-2007, Ext JS, LLC.
15358  *
15359  * Originally Released Under LGPL - original licence link has changed is not relivant.
15360  *
15361  * Fork - LGPL
15362  * <script type="text/javascript">
15363  */
15364  
15365 /**
15366  * @class Roo.menu.Adapter
15367  * @extends Roo.menu.BaseItem
15368  * @abstract
15369  * 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.
15370  * It provides basic rendering, activation management and enable/disable logic required to work in menus.
15371  * @constructor
15372  * Creates a new Adapter
15373  * @param {Object} config Configuration options
15374  */
15375 Roo.menu.Adapter = function(component, config){
15376     Roo.menu.Adapter.superclass.constructor.call(this, config);
15377     this.component = component;
15378 };
15379 Roo.extend(Roo.menu.Adapter, Roo.menu.BaseItem, {
15380     // private
15381     canActivate : true,
15382
15383     // private
15384     onRender : function(container, position){
15385         this.component.render(container);
15386         this.el = this.component.getEl();
15387     },
15388
15389     // private
15390     activate : function(){
15391         if(this.disabled){
15392             return false;
15393         }
15394         this.component.focus();
15395         this.fireEvent("activate", this);
15396         return true;
15397     },
15398
15399     // private
15400     deactivate : function(){
15401         this.fireEvent("deactivate", this);
15402     },
15403
15404     // private
15405     disable : function(){
15406         this.component.disable();
15407         Roo.menu.Adapter.superclass.disable.call(this);
15408     },
15409
15410     // private
15411     enable : function(){
15412         this.component.enable();
15413         Roo.menu.Adapter.superclass.enable.call(this);
15414     }
15415 });/*
15416  * Based on:
15417  * Ext JS Library 1.1.1
15418  * Copyright(c) 2006-2007, Ext JS, LLC.
15419  *
15420  * Originally Released Under LGPL - original licence link has changed is not relivant.
15421  *
15422  * Fork - LGPL
15423  * <script type="text/javascript">
15424  */
15425
15426 /**
15427  * @class Roo.menu.TextItem
15428  * @extends Roo.menu.BaseItem
15429  * Adds a static text string to a menu, usually used as either a heading or group separator.
15430  * Note: old style constructor with text is still supported.
15431  * 
15432  * @constructor
15433  * Creates a new TextItem
15434  * @param {Object} cfg Configuration
15435  */
15436 Roo.menu.TextItem = function(cfg){
15437     if (typeof(cfg) == 'string') {
15438         this.text = cfg;
15439     } else {
15440         Roo.apply(this,cfg);
15441     }
15442     
15443     Roo.menu.TextItem.superclass.constructor.call(this);
15444 };
15445
15446 Roo.extend(Roo.menu.TextItem, Roo.menu.BaseItem, {
15447     /**
15448      * @cfg {String} text Text to show on item.
15449      */
15450     text : '',
15451     
15452     /**
15453      * @cfg {Boolean} hideOnClick True to hide the containing menu after this item is clicked (defaults to false)
15454      */
15455     hideOnClick : false,
15456     /**
15457      * @cfg {String} itemCls The default CSS class to use for text items (defaults to "x-menu-text")
15458      */
15459     itemCls : "x-menu-text",
15460
15461     // private
15462     onRender : function(){
15463         var s = document.createElement("span");
15464         s.className = this.itemCls;
15465         s.innerHTML = this.text;
15466         this.el = s;
15467         Roo.menu.TextItem.superclass.onRender.apply(this, arguments);
15468     }
15469 });/*
15470  * Based on:
15471  * Ext JS Library 1.1.1
15472  * Copyright(c) 2006-2007, Ext JS, LLC.
15473  *
15474  * Originally Released Under LGPL - original licence link has changed is not relivant.
15475  *
15476  * Fork - LGPL
15477  * <script type="text/javascript">
15478  */
15479
15480 /**
15481  * @class Roo.menu.Separator
15482  * @extends Roo.menu.BaseItem
15483  * Adds a separator bar to a menu, used to divide logical groups of menu items. Generally you will
15484  * add one of these by using "-" in you call to add() or in your items config rather than creating one directly.
15485  * @constructor
15486  * @param {Object} config Configuration options
15487  */
15488 Roo.menu.Separator = function(config){
15489     Roo.menu.Separator.superclass.constructor.call(this, config);
15490 };
15491
15492 Roo.extend(Roo.menu.Separator, Roo.menu.BaseItem, {
15493     /**
15494      * @cfg {String} itemCls The default CSS class to use for separators (defaults to "x-menu-sep")
15495      */
15496     itemCls : "x-menu-sep",
15497     /**
15498      * @cfg {Boolean} hideOnClick True to hide the containing menu after this item is clicked (defaults to false)
15499      */
15500     hideOnClick : false,
15501
15502     // private
15503     onRender : function(li){
15504         var s = document.createElement("span");
15505         s.className = this.itemCls;
15506         s.innerHTML = "&#160;";
15507         this.el = s;
15508         li.addClass("x-menu-sep-li");
15509         Roo.menu.Separator.superclass.onRender.apply(this, arguments);
15510     }
15511 });/*
15512  * Based on:
15513  * Ext JS Library 1.1.1
15514  * Copyright(c) 2006-2007, Ext JS, LLC.
15515  *
15516  * Originally Released Under LGPL - original licence link has changed is not relivant.
15517  *
15518  * Fork - LGPL
15519  * <script type="text/javascript">
15520  */
15521 /**
15522  * @class Roo.menu.Item
15523  * @extends Roo.menu.BaseItem
15524  * A base class for all menu items that require menu-related functionality (like sub-menus) and are not static
15525  * display items.  Item extends the base functionality of {@link Roo.menu.BaseItem} by adding menu-specific
15526  * activation and click handling.
15527  * @constructor
15528  * Creates a new Item
15529  * @param {Object} config Configuration options
15530  */
15531 Roo.menu.Item = function(config){
15532     Roo.menu.Item.superclass.constructor.call(this, config);
15533     if(this.menu){
15534         this.menu = Roo.menu.MenuMgr.get(this.menu);
15535     }
15536 };
15537 Roo.extend(Roo.menu.Item, Roo.menu.BaseItem, {
15538     /**
15539      * @cfg {Roo.menu.Menu} menu
15540      * A Sub menu
15541      */
15542     /**
15543      * @cfg {String} text
15544      * The text to show on the menu item.
15545      */
15546     text: '',
15547      /**
15548      * @cfg {String} html to render in menu
15549      * The text to show on the menu item (HTML version).
15550      */
15551     html: '',
15552     /**
15553      * @cfg {String} icon
15554      * The path to an icon to display in this menu item (defaults to Roo.BLANK_IMAGE_URL)
15555      */
15556     icon: undefined,
15557     /**
15558      * @cfg {String} itemCls The default CSS class to use for menu items (defaults to "x-menu-item")
15559      */
15560     itemCls : "x-menu-item",
15561     /**
15562      * @cfg {Boolean} canActivate True if this item can be visually activated (defaults to true)
15563      */
15564     canActivate : true,
15565     /**
15566      * @cfg {Number} showDelay Length of time in milliseconds to wait before showing this item (defaults to 200)
15567      */
15568     showDelay: 200,
15569     // doc'd in BaseItem
15570     hideDelay: 200,
15571
15572     // private
15573     ctype: "Roo.menu.Item",
15574     
15575     // private
15576     onRender : function(container, position){
15577         var el = document.createElement("a");
15578         el.hideFocus = true;
15579         el.unselectable = "on";
15580         el.href = this.href || "#";
15581         if(this.hrefTarget){
15582             el.target = this.hrefTarget;
15583         }
15584         el.className = this.itemCls + (this.menu ?  " x-menu-item-arrow" : "") + (this.cls ?  " " + this.cls : "");
15585         
15586         var html = this.html.length ? this.html  : String.format('{0}',this.text);
15587         
15588         el.innerHTML = String.format(
15589                 '<img src="{0}" class="x-menu-item-icon {1}" />' + html,
15590                 this.icon || Roo.BLANK_IMAGE_URL, this.iconCls || '');
15591         this.el = el;
15592         Roo.menu.Item.superclass.onRender.call(this, container, position);
15593     },
15594
15595     /**
15596      * Sets the text to display in this menu item
15597      * @param {String} text The text to display
15598      * @param {Boolean} isHTML true to indicate text is pure html.
15599      */
15600     setText : function(text, isHTML){
15601         if (isHTML) {
15602             this.html = text;
15603         } else {
15604             this.text = text;
15605             this.html = '';
15606         }
15607         if(this.rendered){
15608             var html = this.html.length ? this.html  : String.format('{0}',this.text);
15609      
15610             this.el.update(String.format(
15611                 '<img src="{0}" class="x-menu-item-icon {2}">' + html,
15612                 this.icon || Roo.BLANK_IMAGE_URL, this.text, this.iconCls || ''));
15613             this.parentMenu.autoWidth();
15614         }
15615     },
15616
15617     // private
15618     handleClick : function(e){
15619         if(!this.href){ // if no link defined, stop the event automatically
15620             e.stopEvent();
15621         }
15622         Roo.menu.Item.superclass.handleClick.apply(this, arguments);
15623     },
15624
15625     // private
15626     activate : function(autoExpand){
15627         if(Roo.menu.Item.superclass.activate.apply(this, arguments)){
15628             this.focus();
15629             if(autoExpand){
15630                 this.expandMenu();
15631             }
15632         }
15633         return true;
15634     },
15635
15636     // private
15637     shouldDeactivate : function(e){
15638         if(Roo.menu.Item.superclass.shouldDeactivate.call(this, e)){
15639             if(this.menu && this.menu.isVisible()){
15640                 return !this.menu.getEl().getRegion().contains(e.getPoint());
15641             }
15642             return true;
15643         }
15644         return false;
15645     },
15646
15647     // private
15648     deactivate : function(){
15649         Roo.menu.Item.superclass.deactivate.apply(this, arguments);
15650         this.hideMenu();
15651     },
15652
15653     // private
15654     expandMenu : function(autoActivate){
15655         if(!this.disabled && this.menu){
15656             clearTimeout(this.hideTimer);
15657             delete this.hideTimer;
15658             if(!this.menu.isVisible() && !this.showTimer){
15659                 this.showTimer = this.deferExpand.defer(this.showDelay, this, [autoActivate]);
15660             }else if (this.menu.isVisible() && autoActivate){
15661                 this.menu.tryActivate(0, 1);
15662             }
15663         }
15664     },
15665
15666     // private
15667     deferExpand : function(autoActivate){
15668         delete this.showTimer;
15669         this.menu.show(this.container, this.parentMenu.subMenuAlign || "tl-tr?", this.parentMenu);
15670         if(autoActivate){
15671             this.menu.tryActivate(0, 1);
15672         }
15673     },
15674
15675     // private
15676     hideMenu : function(){
15677         clearTimeout(this.showTimer);
15678         delete this.showTimer;
15679         if(!this.hideTimer && this.menu && this.menu.isVisible()){
15680             this.hideTimer = this.deferHide.defer(this.hideDelay, this);
15681         }
15682     },
15683
15684     // private
15685     deferHide : function(){
15686         delete this.hideTimer;
15687         this.menu.hide();
15688     }
15689 });/*
15690  * Based on:
15691  * Ext JS Library 1.1.1
15692  * Copyright(c) 2006-2007, Ext JS, LLC.
15693  *
15694  * Originally Released Under LGPL - original licence link has changed is not relivant.
15695  *
15696  * Fork - LGPL
15697  * <script type="text/javascript">
15698  */
15699  
15700 /**
15701  * @class Roo.menu.CheckItem
15702  * @extends Roo.menu.Item
15703  * Adds a menu item that contains a checkbox by default, but can also be part of a radio group.
15704  * @constructor
15705  * Creates a new CheckItem
15706  * @param {Object} config Configuration options
15707  */
15708 Roo.menu.CheckItem = function(config){
15709     Roo.menu.CheckItem.superclass.constructor.call(this, config);
15710     this.addEvents({
15711         /**
15712          * @event beforecheckchange
15713          * Fires before the checked value is set, providing an opportunity to cancel if needed
15714          * @param {Roo.menu.CheckItem} this
15715          * @param {Boolean} checked The new checked value that will be set
15716          */
15717         "beforecheckchange" : true,
15718         /**
15719          * @event checkchange
15720          * Fires after the checked value has been set
15721          * @param {Roo.menu.CheckItem} this
15722          * @param {Boolean} checked The checked value that was set
15723          */
15724         "checkchange" : true
15725     });
15726     if(this.checkHandler){
15727         this.on('checkchange', this.checkHandler, this.scope);
15728     }
15729 };
15730 Roo.extend(Roo.menu.CheckItem, Roo.menu.Item, {
15731     /**
15732      * @cfg {String} group
15733      * All check items with the same group name will automatically be grouped into a single-select
15734      * radio button group (defaults to '')
15735      */
15736     /**
15737      * @cfg {String} itemCls The default CSS class to use for check items (defaults to "x-menu-item x-menu-check-item")
15738      */
15739     itemCls : "x-menu-item x-menu-check-item",
15740     /**
15741      * @cfg {String} groupClass The default CSS class to use for radio group check items (defaults to "x-menu-group-item")
15742      */
15743     groupClass : "x-menu-group-item",
15744
15745     /**
15746      * @cfg {Boolean} checked True to initialize this checkbox as checked (defaults to false).  Note that
15747      * if this checkbox is part of a radio group (group = true) only the last item in the group that is
15748      * initialized with checked = true will be rendered as checked.
15749      */
15750     checked: false,
15751
15752     // private
15753     ctype: "Roo.menu.CheckItem",
15754
15755     // private
15756     onRender : function(c){
15757         Roo.menu.CheckItem.superclass.onRender.apply(this, arguments);
15758         if(this.group){
15759             this.el.addClass(this.groupClass);
15760         }
15761         Roo.menu.MenuMgr.registerCheckable(this);
15762         if(this.checked){
15763             this.checked = false;
15764             this.setChecked(true, true);
15765         }
15766     },
15767
15768     // private
15769     destroy : function(){
15770         if(this.rendered){
15771             Roo.menu.MenuMgr.unregisterCheckable(this);
15772         }
15773         Roo.menu.CheckItem.superclass.destroy.apply(this, arguments);
15774     },
15775
15776     /**
15777      * Set the checked state of this item
15778      * @param {Boolean} checked The new checked value
15779      * @param {Boolean} suppressEvent (optional) True to prevent the checkchange event from firing (defaults to false)
15780      */
15781     setChecked : function(state, suppressEvent){
15782         if(this.checked != state && this.fireEvent("beforecheckchange", this, state) !== false){
15783             if(this.container){
15784                 this.container[state ? "addClass" : "removeClass"]("x-menu-item-checked");
15785             }
15786             this.checked = state;
15787             if(suppressEvent !== true){
15788                 this.fireEvent("checkchange", this, state);
15789             }
15790         }
15791     },
15792
15793     // private
15794     handleClick : function(e){
15795        if(!this.disabled && !(this.checked && this.group)){// disable unselect on radio item
15796            this.setChecked(!this.checked);
15797        }
15798        Roo.menu.CheckItem.superclass.handleClick.apply(this, arguments);
15799     }
15800 });/*
15801  * Based on:
15802  * Ext JS Library 1.1.1
15803  * Copyright(c) 2006-2007, Ext JS, LLC.
15804  *
15805  * Originally Released Under LGPL - original licence link has changed is not relivant.
15806  *
15807  * Fork - LGPL
15808  * <script type="text/javascript">
15809  */
15810  
15811 /**
15812  * @class Roo.menu.DateItem
15813  * @extends Roo.menu.Adapter
15814  * A menu item that wraps the {@link Roo.DatPicker} component.
15815  * @constructor
15816  * Creates a new DateItem
15817  * @param {Object} config Configuration options
15818  */
15819 Roo.menu.DateItem = function(config){
15820     Roo.menu.DateItem.superclass.constructor.call(this, new Roo.DatePicker(config), config);
15821     /** The Roo.DatePicker object @type Roo.DatePicker */
15822     this.picker = this.component;
15823     this.addEvents({select: true});
15824     
15825     this.picker.on("render", function(picker){
15826         picker.getEl().swallowEvent("click");
15827         picker.container.addClass("x-menu-date-item");
15828     });
15829
15830     this.picker.on("select", this.onSelect, this);
15831 };
15832
15833 Roo.extend(Roo.menu.DateItem, Roo.menu.Adapter, {
15834     // private
15835     onSelect : function(picker, date){
15836         this.fireEvent("select", this, date, picker);
15837         Roo.menu.DateItem.superclass.handleClick.call(this);
15838     }
15839 });/*
15840  * Based on:
15841  * Ext JS Library 1.1.1
15842  * Copyright(c) 2006-2007, Ext JS, LLC.
15843  *
15844  * Originally Released Under LGPL - original licence link has changed is not relivant.
15845  *
15846  * Fork - LGPL
15847  * <script type="text/javascript">
15848  */
15849  
15850 /**
15851  * @class Roo.menu.ColorItem
15852  * @extends Roo.menu.Adapter
15853  * A menu item that wraps the {@link Roo.ColorPalette} component.
15854  * @constructor
15855  * Creates a new ColorItem
15856  * @param {Object} config Configuration options
15857  */
15858 Roo.menu.ColorItem = function(config){
15859     Roo.menu.ColorItem.superclass.constructor.call(this, new Roo.ColorPalette(config), config);
15860     /** The Roo.ColorPalette object @type Roo.ColorPalette */
15861     this.palette = this.component;
15862     this.relayEvents(this.palette, ["select"]);
15863     if(this.selectHandler){
15864         this.on('select', this.selectHandler, this.scope);
15865     }
15866 };
15867 Roo.extend(Roo.menu.ColorItem, Roo.menu.Adapter);/*
15868  * Based on:
15869  * Ext JS Library 1.1.1
15870  * Copyright(c) 2006-2007, Ext JS, LLC.
15871  *
15872  * Originally Released Under LGPL - original licence link has changed is not relivant.
15873  *
15874  * Fork - LGPL
15875  * <script type="text/javascript">
15876  */
15877  
15878
15879 /**
15880  * @class Roo.menu.DateMenu
15881  * @extends Roo.menu.Menu
15882  * A menu containing a {@link Roo.menu.DateItem} component (which provides a date picker).
15883  * @constructor
15884  * Creates a new DateMenu
15885  * @param {Object} config Configuration options
15886  */
15887 Roo.menu.DateMenu = function(config){
15888     Roo.menu.DateMenu.superclass.constructor.call(this, config);
15889     this.plain = true;
15890     var di = new Roo.menu.DateItem(config);
15891     this.add(di);
15892     /**
15893      * The {@link Roo.DatePicker} instance for this DateMenu
15894      * @type DatePicker
15895      */
15896     this.picker = di.picker;
15897     /**
15898      * @event select
15899      * @param {DatePicker} picker
15900      * @param {Date} date
15901      */
15902     this.relayEvents(di, ["select"]);
15903     this.on('beforeshow', function(){
15904         if(this.picker){
15905             this.picker.hideMonthPicker(false);
15906         }
15907     }, this);
15908 };
15909 Roo.extend(Roo.menu.DateMenu, Roo.menu.Menu, {
15910     cls:'x-date-menu'
15911 });/*
15912  * Based on:
15913  * Ext JS Library 1.1.1
15914  * Copyright(c) 2006-2007, Ext JS, LLC.
15915  *
15916  * Originally Released Under LGPL - original licence link has changed is not relivant.
15917  *
15918  * Fork - LGPL
15919  * <script type="text/javascript">
15920  */
15921  
15922
15923 /**
15924  * @class Roo.menu.ColorMenu
15925  * @extends Roo.menu.Menu
15926  * A menu containing a {@link Roo.menu.ColorItem} component (which provides a basic color picker).
15927  * @constructor
15928  * Creates a new ColorMenu
15929  * @param {Object} config Configuration options
15930  */
15931 Roo.menu.ColorMenu = function(config){
15932     Roo.menu.ColorMenu.superclass.constructor.call(this, config);
15933     this.plain = true;
15934     var ci = new Roo.menu.ColorItem(config);
15935     this.add(ci);
15936     /**
15937      * The {@link Roo.ColorPalette} instance for this ColorMenu
15938      * @type ColorPalette
15939      */
15940     this.palette = ci.palette;
15941     /**
15942      * @event select
15943      * @param {ColorPalette} palette
15944      * @param {String} color
15945      */
15946     this.relayEvents(ci, ["select"]);
15947 };
15948 Roo.extend(Roo.menu.ColorMenu, Roo.menu.Menu);/*
15949  * Based on:
15950  * Ext JS Library 1.1.1
15951  * Copyright(c) 2006-2007, Ext JS, LLC.
15952  *
15953  * Originally Released Under LGPL - original licence link has changed is not relivant.
15954  *
15955  * Fork - LGPL
15956  * <script type="text/javascript">
15957  */
15958  
15959 /**
15960  * @class Roo.form.TextItem
15961  * @extends Roo.BoxComponent
15962  * Base class for form fields that provides default event handling, sizing, value handling and other functionality.
15963  * @constructor
15964  * Creates a new TextItem
15965  * @param {Object} config Configuration options
15966  */
15967 Roo.form.TextItem = function(config){
15968     Roo.form.TextItem.superclass.constructor.call(this, config);
15969 };
15970
15971 Roo.extend(Roo.form.TextItem, Roo.BoxComponent,  {
15972     
15973     /**
15974      * @cfg {String} tag the tag for this item (default div)
15975      */
15976     tag : 'div',
15977     /**
15978      * @cfg {String} html the content for this item
15979      */
15980     html : '',
15981     
15982     getAutoCreate : function()
15983     {
15984         var cfg = {
15985             id: this.id,
15986             tag: this.tag,
15987             html: this.html,
15988             cls: 'x-form-item'
15989         };
15990         
15991         return cfg;
15992         
15993     },
15994     
15995     onRender : function(ct, position)
15996     {
15997         Roo.form.TextItem.superclass.onRender.call(this, ct, position);
15998         
15999         if(!this.el){
16000             var cfg = this.getAutoCreate();
16001             if(!cfg.name){
16002                 cfg.name = typeof(this.name) == 'undefined' ? this.id : this.name;
16003             }
16004             if (!cfg.name.length) {
16005                 delete cfg.name;
16006             }
16007             this.el = ct.createChild(cfg, position);
16008         }
16009     },
16010     /*
16011      * setHTML
16012      * @param {String} html update the Contents of the element.
16013      */
16014     setHTML : function(html)
16015     {
16016         this.fieldEl.dom.innerHTML = html;
16017     }
16018     
16019 });/*
16020  * Based on:
16021  * Ext JS Library 1.1.1
16022  * Copyright(c) 2006-2007, Ext JS, LLC.
16023  *
16024  * Originally Released Under LGPL - original licence link has changed is not relivant.
16025  *
16026  * Fork - LGPL
16027  * <script type="text/javascript">
16028  */
16029  
16030 /**
16031  * @class Roo.form.Field
16032  * @extends Roo.BoxComponent
16033  * Base class for form fields that provides default event handling, sizing, value handling and other functionality.
16034  * @constructor
16035  * Creates a new Field
16036  * @param {Object} config Configuration options
16037  */
16038 Roo.form.Field = function(config){
16039     Roo.form.Field.superclass.constructor.call(this, config);
16040 };
16041
16042 Roo.extend(Roo.form.Field, Roo.BoxComponent,  {
16043     /**
16044      * @cfg {String} fieldLabel Label to use when rendering a form.
16045      */
16046        /**
16047      * @cfg {String} qtip Mouse over tip
16048      */
16049      
16050     /**
16051      * @cfg {String} invalidClass The CSS class to use when marking a field invalid (defaults to "x-form-invalid")
16052      */
16053     invalidClass : "x-form-invalid",
16054     /**
16055      * @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")
16056      */
16057     invalidText : "The value in this field is invalid",
16058     /**
16059      * @cfg {String} focusClass The CSS class to use when the field receives focus (defaults to "x-form-focus")
16060      */
16061     focusClass : "x-form-focus",
16062     /**
16063      * @cfg {String/Boolean} validationEvent The event that should initiate field validation. Set to false to disable
16064       automatic validation (defaults to "keyup").
16065      */
16066     validationEvent : "keyup",
16067     /**
16068      * @cfg {Boolean} validateOnBlur Whether the field should validate when it loses focus (defaults to true).
16069      */
16070     validateOnBlur : true,
16071     /**
16072      * @cfg {Number} validationDelay The length of time in milliseconds after user input begins until validation is initiated (defaults to 250)
16073      */
16074     validationDelay : 250,
16075     /**
16076      * @cfg {String/Object} autoCreate A DomHelper element spec, or true for a default element spec (defaults to
16077      * {tag: "input", type: "text", size: "20", autocomplete: "off"})
16078      */
16079     defaultAutoCreate : {tag: "input", type: "text", size: "20", autocomplete: "new-password"},
16080     /**
16081      * @cfg {String} fieldClass The default CSS class for the field (defaults to "x-form-field")
16082      */
16083     fieldClass : "x-form-field",
16084     /**
16085      * @cfg {String} msgTarget The location where error text should display.  Should be one of the following values (defaults to 'qtip'):
16086      *<pre>
16087 Value         Description
16088 -----------   ----------------------------------------------------------------------
16089 qtip          Display a quick tip when the user hovers over the field
16090 title         Display a default browser title attribute popup
16091 under         Add a block div beneath the field containing the error text
16092 side          Add an error icon to the right of the field with a popup on hover
16093 [element id]  Add the error text directly to the innerHTML of the specified element
16094 </pre>
16095      */
16096     msgTarget : 'qtip',
16097     /**
16098      * @cfg {String} msgFx <b>Experimental</b> The effect used when displaying a validation message under the field (defaults to 'normal').
16099      */
16100     msgFx : 'normal',
16101
16102     /**
16103      * @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.
16104      */
16105     readOnly : false,
16106
16107     /**
16108      * @cfg {Boolean} disabled True to disable the field (defaults to false).
16109      */
16110     disabled : false,
16111
16112     /**
16113      * @cfg {String} inputType The type attribute for input fields -- e.g. radio, text, password (defaults to "text").
16114      */
16115     inputType : undefined,
16116     
16117     /**
16118      * @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).
16119          */
16120         tabIndex : undefined,
16121         
16122     // private
16123     isFormField : true,
16124
16125     // private
16126     hasFocus : false,
16127     /**
16128      * @property {Roo.Element} fieldEl
16129      * Element Containing the rendered Field (with label etc.)
16130      */
16131     /**
16132      * @cfg {Mixed} value A value to initialize this field with.
16133      */
16134     value : undefined,
16135
16136     /**
16137      * @cfg {String} name The field's HTML name attribute.
16138      */
16139     /**
16140      * @cfg {String} cls A CSS class to apply to the field's underlying element.
16141      */
16142     // private
16143     loadedValue : false,
16144      
16145      
16146         // private ??
16147         initComponent : function(){
16148         Roo.form.Field.superclass.initComponent.call(this);
16149         this.addEvents({
16150             /**
16151              * @event focus
16152              * Fires when this field receives input focus.
16153              * @param {Roo.form.Field} this
16154              */
16155             focus : true,
16156             /**
16157              * @event blur
16158              * Fires when this field loses input focus.
16159              * @param {Roo.form.Field} this
16160              */
16161             blur : true,
16162             /**
16163              * @event specialkey
16164              * Fires when any key related to navigation (arrows, tab, enter, esc, etc.) is pressed.  You can check
16165              * {@link Roo.EventObject#getKey} to determine which key was pressed.
16166              * @param {Roo.form.Field} this
16167              * @param {Roo.EventObject} e The event object
16168              */
16169             specialkey : true,
16170             /**
16171              * @event change
16172              * Fires just before the field blurs if the field value has changed.
16173              * @param {Roo.form.Field} this
16174              * @param {Mixed} newValue The new value
16175              * @param {Mixed} oldValue The original value
16176              */
16177             change : true,
16178             /**
16179              * @event invalid
16180              * Fires after the field has been marked as invalid.
16181              * @param {Roo.form.Field} this
16182              * @param {String} msg The validation message
16183              */
16184             invalid : true,
16185             /**
16186              * @event valid
16187              * Fires after the field has been validated with no errors.
16188              * @param {Roo.form.Field} this
16189              */
16190             valid : true,
16191              /**
16192              * @event keyup
16193              * Fires after the key up
16194              * @param {Roo.form.Field} this
16195              * @param {Roo.EventObject}  e The event Object
16196              */
16197             keyup : true
16198         });
16199     },
16200
16201     /**
16202      * Returns the name attribute of the field if available
16203      * @return {String} name The field name
16204      */
16205     getName: function(){
16206          return this.rendered && this.el.dom.name ? this.el.dom.name : (this.hiddenName || '');
16207     },
16208
16209     // private
16210     onRender : function(ct, position){
16211         Roo.form.Field.superclass.onRender.call(this, ct, position);
16212         if(!this.el){
16213             var cfg = this.getAutoCreate();
16214             if(!cfg.name){
16215                 cfg.name = typeof(this.name) == 'undefined' ? this.id : this.name;
16216             }
16217             if (!cfg.name.length) {
16218                 delete cfg.name;
16219             }
16220             if(this.inputType){
16221                 cfg.type = this.inputType;
16222             }
16223             this.el = ct.createChild(cfg, position);
16224         }
16225         var type = this.el.dom.type;
16226         if(type){
16227             if(type == 'password'){
16228                 type = 'text';
16229             }
16230             this.el.addClass('x-form-'+type);
16231         }
16232         if(this.readOnly){
16233             this.el.dom.readOnly = true;
16234         }
16235         if(this.tabIndex !== undefined){
16236             this.el.dom.setAttribute('tabIndex', this.tabIndex);
16237         }
16238
16239         this.el.addClass([this.fieldClass, this.cls]);
16240         this.initValue();
16241     },
16242
16243     /**
16244      * Apply the behaviors of this component to an existing element. <b>This is used instead of render().</b>
16245      * @param {String/HTMLElement/Element} el The id of the node, a DOM node or an existing Element
16246      * @return {Roo.form.Field} this
16247      */
16248     applyTo : function(target){
16249         this.allowDomMove = false;
16250         this.el = Roo.get(target);
16251         this.render(this.el.dom.parentNode);
16252         return this;
16253     },
16254
16255     // private
16256     initValue : function(){
16257         if(this.value !== undefined){
16258             this.setValue(this.value);
16259         }else if(this.el.dom.value.length > 0){
16260             this.setValue(this.el.dom.value);
16261         }
16262     },
16263
16264     /**
16265      * Returns true if this field has been changed since it was originally loaded and is not disabled.
16266      * DEPRICATED  - it never worked well - use hasChanged/resetHasChanged.
16267      */
16268     isDirty : function() {
16269         if(this.disabled) {
16270             return false;
16271         }
16272         return String(this.getValue()) !== String(this.originalValue);
16273     },
16274
16275     /**
16276      * stores the current value in loadedValue
16277      */
16278     resetHasChanged : function()
16279     {
16280         this.loadedValue = String(this.getValue());
16281     },
16282     /**
16283      * checks the current value against the 'loaded' value.
16284      * Note - will return false if 'resetHasChanged' has not been called first.
16285      */
16286     hasChanged : function()
16287     {
16288         if(this.disabled || this.readOnly) {
16289             return false;
16290         }
16291         return this.loadedValue !== false && String(this.getValue()) !== this.loadedValue;
16292     },
16293     
16294     
16295     
16296     // private
16297     afterRender : function(){
16298         Roo.form.Field.superclass.afterRender.call(this);
16299         this.initEvents();
16300     },
16301
16302     // private
16303     fireKey : function(e){
16304         //Roo.log('field ' + e.getKey());
16305         if(e.isNavKeyPress()){
16306             this.fireEvent("specialkey", this, e);
16307         }
16308     },
16309
16310     /**
16311      * Resets the current field value to the originally loaded value and clears any validation messages
16312      */
16313     reset : function(){
16314         this.setValue(this.resetValue);
16315         this.originalValue = this.getValue();
16316         this.clearInvalid();
16317     },
16318
16319     // private
16320     initEvents : function(){
16321         // safari killled keypress - so keydown is now used..
16322         this.el.on("keydown" , this.fireKey,  this);
16323         this.el.on("focus", this.onFocus,  this);
16324         this.el.on("blur", this.onBlur,  this);
16325         this.el.relayEvent('keyup', this);
16326
16327         // reference to original value for reset
16328         this.originalValue = this.getValue();
16329         this.resetValue =  this.getValue();
16330     },
16331
16332     // private
16333     onFocus : function(){
16334         if(!Roo.isOpera && this.focusClass){ // don't touch in Opera
16335             this.el.addClass(this.focusClass);
16336         }
16337         if(!this.hasFocus){
16338             this.hasFocus = true;
16339             this.startValue = this.getValue();
16340             this.fireEvent("focus", this);
16341         }
16342     },
16343
16344     beforeBlur : Roo.emptyFn,
16345
16346     // private
16347     onBlur : function(){
16348         this.beforeBlur();
16349         if(!Roo.isOpera && this.focusClass){ // don't touch in Opera
16350             this.el.removeClass(this.focusClass);
16351         }
16352         this.hasFocus = false;
16353         if(this.validationEvent !== false && this.validateOnBlur && this.validationEvent != "blur"){
16354             this.validate();
16355         }
16356         var v = this.getValue();
16357         if(String(v) !== String(this.startValue)){
16358             this.fireEvent('change', this, v, this.startValue);
16359         }
16360         this.fireEvent("blur", this);
16361     },
16362
16363     /**
16364      * Returns whether or not the field value is currently valid
16365      * @param {Boolean} preventMark True to disable marking the field invalid
16366      * @return {Boolean} True if the value is valid, else false
16367      */
16368     isValid : function(preventMark){
16369         if(this.disabled){
16370             return true;
16371         }
16372         var restore = this.preventMark;
16373         this.preventMark = preventMark === true;
16374         var v = this.validateValue(this.processValue(this.getRawValue()));
16375         this.preventMark = restore;
16376         return v;
16377     },
16378
16379     /**
16380      * Validates the field value
16381      * @return {Boolean} True if the value is valid, else false
16382      */
16383     validate : function(){
16384         if(this.disabled || this.validateValue(this.processValue(this.getRawValue()))){
16385             this.clearInvalid();
16386             return true;
16387         }
16388         return false;
16389     },
16390
16391     processValue : function(value){
16392         return value;
16393     },
16394
16395     // private
16396     // Subclasses should provide the validation implementation by overriding this
16397     validateValue : function(value){
16398         return true;
16399     },
16400
16401     /**
16402      * Mark this field as invalid
16403      * @param {String} msg The validation message
16404      */
16405     markInvalid : function(msg){
16406         if(!this.rendered || this.preventMark){ // not rendered
16407             return;
16408         }
16409         
16410         var obj = (typeof(this.combo) != 'undefined') ? this.combo : this; // fix the combox array!!
16411         
16412         obj.el.addClass(this.invalidClass);
16413         msg = msg || this.invalidText;
16414         switch(this.msgTarget){
16415             case 'qtip':
16416                 obj.el.dom.qtip = msg;
16417                 obj.el.dom.qclass = 'x-form-invalid-tip';
16418                 if(Roo.QuickTips){ // fix for floating editors interacting with DND
16419                     Roo.QuickTips.enable();
16420                 }
16421                 break;
16422             case 'title':
16423                 this.el.dom.title = msg;
16424                 break;
16425             case 'under':
16426                 if(!this.errorEl){
16427                     var elp = this.el.findParent('.x-form-element', 5, true);
16428                     this.errorEl = elp.createChild({cls:'x-form-invalid-msg'});
16429                     this.errorEl.setWidth(elp.getWidth(true)-20);
16430                 }
16431                 this.errorEl.update(msg);
16432                 Roo.form.Field.msgFx[this.msgFx].show(this.errorEl, this);
16433                 break;
16434             case 'side':
16435                 if(!this.errorIcon){
16436                     var elp = this.el.findParent('.x-form-element', 5, true);
16437                     this.errorIcon = elp.createChild({cls:'x-form-invalid-icon'});
16438                 }
16439                 this.alignErrorIcon();
16440                 this.errorIcon.dom.qtip = msg;
16441                 this.errorIcon.dom.qclass = 'x-form-invalid-tip';
16442                 this.errorIcon.show();
16443                 this.on('resize', this.alignErrorIcon, this);
16444                 break;
16445             default:
16446                 var t = Roo.getDom(this.msgTarget);
16447                 t.innerHTML = msg;
16448                 t.style.display = this.msgDisplay;
16449                 break;
16450         }
16451         this.fireEvent('invalid', this, msg);
16452     },
16453
16454     // private
16455     alignErrorIcon : function(){
16456         this.errorIcon.alignTo(this.el, 'tl-tr', [2, 0]);
16457     },
16458
16459     /**
16460      * Clear any invalid styles/messages for this field
16461      */
16462     clearInvalid : function(){
16463         if(!this.rendered || this.preventMark){ // not rendered
16464             return;
16465         }
16466         var obj = (typeof(this.combo) != 'undefined') ? this.combo : this; // fix the combox array!!
16467         
16468         obj.el.removeClass(this.invalidClass);
16469         switch(this.msgTarget){
16470             case 'qtip':
16471                 obj.el.dom.qtip = '';
16472                 break;
16473             case 'title':
16474                 this.el.dom.title = '';
16475                 break;
16476             case 'under':
16477                 if(this.errorEl){
16478                     Roo.form.Field.msgFx[this.msgFx].hide(this.errorEl, this);
16479                 }
16480                 break;
16481             case 'side':
16482                 if(this.errorIcon){
16483                     this.errorIcon.dom.qtip = '';
16484                     this.errorIcon.hide();
16485                     this.un('resize', this.alignErrorIcon, this);
16486                 }
16487                 break;
16488             default:
16489                 var t = Roo.getDom(this.msgTarget);
16490                 t.innerHTML = '';
16491                 t.style.display = 'none';
16492                 break;
16493         }
16494         this.fireEvent('valid', this);
16495     },
16496
16497     /**
16498      * Returns the raw data value which may or may not be a valid, defined value.  To return a normalized value see {@link #getValue}.
16499      * @return {Mixed} value The field value
16500      */
16501     getRawValue : function(){
16502         var v = this.el.getValue();
16503         
16504         return v;
16505     },
16506
16507     /**
16508      * Returns the normalized data value (undefined or emptyText will be returned as '').  To return the raw value see {@link #getRawValue}.
16509      * @return {Mixed} value The field value
16510      */
16511     getValue : function(){
16512         var v = this.el.getValue();
16513          
16514         return v;
16515     },
16516
16517     /**
16518      * Sets the underlying DOM field's value directly, bypassing validation.  To set the value with validation see {@link #setValue}.
16519      * @param {Mixed} value The value to set
16520      */
16521     setRawValue : function(v){
16522         return this.el.dom.value = (v === null || v === undefined ? '' : v);
16523     },
16524
16525     /**
16526      * Sets a data value into the field and validates it.  To set the value directly without validation see {@link #setRawValue}.
16527      * @param {Mixed} value The value to set
16528      */
16529     setValue : function(v){
16530         this.value = v;
16531         if(this.rendered){
16532             this.el.dom.value = (v === null || v === undefined ? '' : v);
16533              this.validate();
16534         }
16535     },
16536
16537     adjustSize : function(w, h){
16538         var s = Roo.form.Field.superclass.adjustSize.call(this, w, h);
16539         s.width = this.adjustWidth(this.el.dom.tagName, s.width);
16540         return s;
16541     },
16542
16543     adjustWidth : function(tag, w){
16544         tag = tag.toLowerCase();
16545         if(typeof w == 'number' && Roo.isStrict && !Roo.isSafari){
16546             if(Roo.isIE && (tag == 'input' || tag == 'textarea')){
16547                 if(tag == 'input'){
16548                     return w + 2;
16549                 }
16550                 if(tag == 'textarea'){
16551                     return w-2;
16552                 }
16553             }else if(Roo.isOpera){
16554                 if(tag == 'input'){
16555                     return w + 2;
16556                 }
16557                 if(tag == 'textarea'){
16558                     return w-2;
16559                 }
16560             }
16561         }
16562         return w;
16563     }
16564 });
16565
16566
16567 // anything other than normal should be considered experimental
16568 Roo.form.Field.msgFx = {
16569     normal : {
16570         show: function(msgEl, f){
16571             msgEl.setDisplayed('block');
16572         },
16573
16574         hide : function(msgEl, f){
16575             msgEl.setDisplayed(false).update('');
16576         }
16577     },
16578
16579     slide : {
16580         show: function(msgEl, f){
16581             msgEl.slideIn('t', {stopFx:true});
16582         },
16583
16584         hide : function(msgEl, f){
16585             msgEl.slideOut('t', {stopFx:true,useDisplay:true});
16586         }
16587     },
16588
16589     slideRight : {
16590         show: function(msgEl, f){
16591             msgEl.fixDisplay();
16592             msgEl.alignTo(f.el, 'tl-tr');
16593             msgEl.slideIn('l', {stopFx:true});
16594         },
16595
16596         hide : function(msgEl, f){
16597             msgEl.slideOut('l', {stopFx:true,useDisplay:true});
16598         }
16599     }
16600 };/*
16601  * Based on:
16602  * Ext JS Library 1.1.1
16603  * Copyright(c) 2006-2007, Ext JS, LLC.
16604  *
16605  * Originally Released Under LGPL - original licence link has changed is not relivant.
16606  *
16607  * Fork - LGPL
16608  * <script type="text/javascript">
16609  */
16610  
16611
16612 /**
16613  * @class Roo.form.TextField
16614  * @extends Roo.form.Field
16615  * Basic text field.  Can be used as a direct replacement for traditional text inputs, or as the base
16616  * class for more sophisticated input controls (like {@link Roo.form.TextArea} and {@link Roo.form.ComboBox}).
16617  * @constructor
16618  * Creates a new TextField
16619  * @param {Object} config Configuration options
16620  */
16621 Roo.form.TextField = function(config){
16622     Roo.form.TextField.superclass.constructor.call(this, config);
16623     this.addEvents({
16624         /**
16625          * @event autosize
16626          * Fires when the autosize function is triggered.  The field may or may not have actually changed size
16627          * according to the default logic, but this event provides a hook for the developer to apply additional
16628          * logic at runtime to resize the field if needed.
16629              * @param {Roo.form.Field} this This text field
16630              * @param {Number} width The new field width
16631              */
16632         autosize : true
16633     });
16634 };
16635
16636 Roo.extend(Roo.form.TextField, Roo.form.Field,  {
16637     /**
16638      * @cfg {Boolean} grow True if this field should automatically grow and shrink to its content
16639      */
16640     grow : false,
16641     /**
16642      * @cfg {Number} growMin The minimum width to allow when grow = true (defaults to 30)
16643      */
16644     growMin : 30,
16645     /**
16646      * @cfg {Number} growMax The maximum width to allow when grow = true (defaults to 800)
16647      */
16648     growMax : 800,
16649     /**
16650      * @cfg {String} vtype A validation type name as defined in {@link Roo.form.VTypes} (defaults to null)
16651      */
16652     vtype : null,
16653     /**
16654      * @cfg {String} maskRe An input mask regular expression that will be used to filter keystrokes that don't match (defaults to null)
16655      */
16656     maskRe : null,
16657     /**
16658      * @cfg {Boolean} disableKeyFilter True to disable input keystroke filtering (defaults to false)
16659      */
16660     disableKeyFilter : false,
16661     /**
16662      * @cfg {Boolean} allowBlank False to validate that the value length > 0 (defaults to true)
16663      */
16664     allowBlank : true,
16665     /**
16666      * @cfg {Number} minLength Minimum input field length required (defaults to 0)
16667      */
16668     minLength : 0,
16669     /**
16670      * @cfg {Number} maxLength Maximum input field length allowed (defaults to Number.MAX_VALUE)
16671      */
16672     maxLength : Number.MAX_VALUE,
16673     /**
16674      * @cfg {String} minLengthText Error text to display if the minimum length validation fails (defaults to "The minimum length for this field is {minLength}")
16675      */
16676     minLengthText : "The minimum length for this field is {0}",
16677     /**
16678      * @cfg {String} maxLengthText Error text to display if the maximum length validation fails (defaults to "The maximum length for this field is {maxLength}")
16679      */
16680     maxLengthText : "The maximum length for this field is {0}",
16681     /**
16682      * @cfg {Boolean} selectOnFocus True to automatically select any existing field text when the field receives input focus (defaults to false)
16683      */
16684     selectOnFocus : false,
16685     /**
16686      * @cfg {Boolean} allowLeadingSpace True to prevent the stripping of leading white space 
16687      */    
16688     allowLeadingSpace : false,
16689     /**
16690      * @cfg {String} blankText Error text to display if the allow blank validation fails (defaults to "This field is required")
16691      */
16692     blankText : "This field is required",
16693     /**
16694      * @cfg {Function} validator A custom validation function to be called during field validation (defaults to null).
16695      * If available, this function will be called only after the basic validators all return true, and will be passed the
16696      * current field value and expected to return boolean true if the value is valid or a string error message if invalid.
16697      */
16698     validator : null,
16699     /**
16700      * @cfg {RegExp} regex A JavaScript RegExp object to be tested against the field value during validation (defaults to null).
16701      * If available, this regex will be evaluated only after the basic validators all return true, and will be passed the
16702      * current field value.  If the test fails, the field will be marked invalid using {@link #regexText}.
16703      */
16704     regex : null,
16705     /**
16706      * @cfg {String} regexText The error text to display if {@link #regex} is used and the test fails during validation (defaults to "")
16707      */
16708     regexText : "",
16709     /**
16710      * @cfg {String} emptyText The default text to display in an empty field - placeholder... (defaults to null).
16711      */
16712     emptyText : null,
16713    
16714
16715     // private
16716     initEvents : function()
16717     {
16718         if (this.emptyText) {
16719             this.el.attr('placeholder', this.emptyText);
16720         }
16721         
16722         Roo.form.TextField.superclass.initEvents.call(this);
16723         if(this.validationEvent == 'keyup'){
16724             this.validationTask = new Roo.util.DelayedTask(this.validate, this);
16725             this.el.on('keyup', this.filterValidation, this);
16726         }
16727         else if(this.validationEvent !== false){
16728             this.el.on(this.validationEvent, this.validate, this, {buffer: this.validationDelay});
16729         }
16730         
16731         if(this.selectOnFocus){
16732             this.on("focus", this.preFocus, this);
16733         }
16734         if (!this.allowLeadingSpace) {
16735             this.on('blur', this.cleanLeadingSpace, this);
16736         }
16737         
16738         if(this.maskRe || (this.vtype && this.disableKeyFilter !== true && (this.maskRe = Roo.form.VTypes[this.vtype+'Mask']))){
16739             this.el.on("keypress", this.filterKeys, this);
16740         }
16741         if(this.grow){
16742             this.el.on("keyup", this.onKeyUp,  this, {buffer:50});
16743             this.el.on("click", this.autoSize,  this);
16744         }
16745         if(this.el.is('input[type=password]') && Roo.isSafari){
16746             this.el.on('keydown', this.SafariOnKeyDown, this);
16747         }
16748     },
16749
16750     processValue : function(value){
16751         if(this.stripCharsRe){
16752             var newValue = value.replace(this.stripCharsRe, '');
16753             if(newValue !== value){
16754                 this.setRawValue(newValue);
16755                 return newValue;
16756             }
16757         }
16758         return value;
16759     },
16760
16761     filterValidation : function(e){
16762         if(!e.isNavKeyPress()){
16763             this.validationTask.delay(this.validationDelay);
16764         }
16765     },
16766
16767     // private
16768     onKeyUp : function(e){
16769         if(!e.isNavKeyPress()){
16770             this.autoSize();
16771         }
16772     },
16773     // private - clean the leading white space
16774     cleanLeadingSpace : function(e)
16775     {
16776         if ( this.inputType == 'file') {
16777             return;
16778         }
16779         
16780         this.setValue((this.getValue() + '').replace(/^\s+/,''));
16781     },
16782     /**
16783      * Resets the current field value to the originally-loaded value and clears any validation messages.
16784      *  
16785      */
16786     reset : function(){
16787         Roo.form.TextField.superclass.reset.call(this);
16788        
16789     }, 
16790     // private
16791     preFocus : function(){
16792         
16793         if(this.selectOnFocus){
16794             this.el.dom.select();
16795         }
16796     },
16797
16798     
16799     // private
16800     filterKeys : function(e){
16801         var k = e.getKey();
16802         if(!Roo.isIE && (e.isNavKeyPress() || k == e.BACKSPACE || (k == e.DELETE && e.button == -1))){
16803             return;
16804         }
16805         var c = e.getCharCode(), cc = String.fromCharCode(c);
16806         if(Roo.isIE && (e.isSpecialKey() || !cc)){
16807             return;
16808         }
16809         if(!this.maskRe.test(cc)){
16810             e.stopEvent();
16811         }
16812     },
16813
16814     setValue : function(v){
16815         
16816         Roo.form.TextField.superclass.setValue.apply(this, arguments);
16817         
16818         this.autoSize();
16819     },
16820
16821     /**
16822      * Validates a value according to the field's validation rules and marks the field as invalid
16823      * if the validation fails
16824      * @param {Mixed} value The value to validate
16825      * @return {Boolean} True if the value is valid, else false
16826      */
16827     validateValue : function(value){
16828         if(value.length < 1)  { // if it's blank
16829              if(this.allowBlank){
16830                 this.clearInvalid();
16831                 return true;
16832              }else{
16833                 this.markInvalid(this.blankText);
16834                 return false;
16835              }
16836         }
16837         if(value.length < this.minLength){
16838             this.markInvalid(String.format(this.minLengthText, this.minLength));
16839             return false;
16840         }
16841         if(value.length > this.maxLength){
16842             this.markInvalid(String.format(this.maxLengthText, this.maxLength));
16843             return false;
16844         }
16845         if(this.vtype){
16846             var vt = Roo.form.VTypes;
16847             if(!vt[this.vtype](value, this)){
16848                 this.markInvalid(this.vtypeText || vt[this.vtype +'Text']);
16849                 return false;
16850             }
16851         }
16852         if(typeof this.validator == "function"){
16853             var msg = this.validator(value);
16854             if(msg !== true){
16855                 this.markInvalid(msg);
16856                 return false;
16857             }
16858         }
16859         if(this.regex && !this.regex.test(value)){
16860             this.markInvalid(this.regexText);
16861             return false;
16862         }
16863         return true;
16864     },
16865
16866     /**
16867      * Selects text in this field
16868      * @param {Number} start (optional) The index where the selection should start (defaults to 0)
16869      * @param {Number} end (optional) The index where the selection should end (defaults to the text length)
16870      */
16871     selectText : function(start, end){
16872         var v = this.getRawValue();
16873         if(v.length > 0){
16874             start = start === undefined ? 0 : start;
16875             end = end === undefined ? v.length : end;
16876             var d = this.el.dom;
16877             if(d.setSelectionRange){
16878                 d.setSelectionRange(start, end);
16879             }else if(d.createTextRange){
16880                 var range = d.createTextRange();
16881                 range.moveStart("character", start);
16882                 range.moveEnd("character", v.length-end);
16883                 range.select();
16884             }
16885         }
16886     },
16887
16888     /**
16889      * Automatically grows the field to accomodate the width of the text up to the maximum field width allowed.
16890      * This only takes effect if grow = true, and fires the autosize event.
16891      */
16892     autoSize : function(){
16893         if(!this.grow || !this.rendered){
16894             return;
16895         }
16896         if(!this.metrics){
16897             this.metrics = Roo.util.TextMetrics.createInstance(this.el);
16898         }
16899         var el = this.el;
16900         var v = el.dom.value;
16901         var d = document.createElement('div');
16902         d.appendChild(document.createTextNode(v));
16903         v = d.innerHTML;
16904         d = null;
16905         v += "&#160;";
16906         var w = Math.min(this.growMax, Math.max(this.metrics.getWidth(v) + /* add extra padding */ 10, this.growMin));
16907         this.el.setWidth(w);
16908         this.fireEvent("autosize", this, w);
16909     },
16910     
16911     // private
16912     SafariOnKeyDown : function(event)
16913     {
16914         // this is a workaround for a password hang bug on chrome/ webkit.
16915         
16916         var isSelectAll = false;
16917         
16918         if(this.el.dom.selectionEnd > 0){
16919             isSelectAll = (this.el.dom.selectionEnd - this.el.dom.selectionStart - this.getValue().length == 0) ? true : false;
16920         }
16921         if(((event.getKey() == 8 || event.getKey() == 46) && this.getValue().length ==1)){ // backspace and delete key
16922             event.preventDefault();
16923             this.setValue('');
16924             return;
16925         }
16926         
16927         if(isSelectAll && event.getCharCode() > 31){ // backspace and delete key
16928             
16929             event.preventDefault();
16930             // this is very hacky as keydown always get's upper case.
16931             
16932             var cc = String.fromCharCode(event.getCharCode());
16933             
16934             
16935             this.setValue( event.shiftKey ?  cc : cc.toLowerCase());
16936             
16937         }
16938         
16939         
16940     }
16941 });/*
16942  * Based on:
16943  * Ext JS Library 1.1.1
16944  * Copyright(c) 2006-2007, Ext JS, LLC.
16945  *
16946  * Originally Released Under LGPL - original licence link has changed is not relivant.
16947  *
16948  * Fork - LGPL
16949  * <script type="text/javascript">
16950  */
16951  
16952 /**
16953  * @class Roo.form.Hidden
16954  * @extends Roo.form.TextField
16955  * Simple Hidden element used on forms 
16956  * 
16957  * usage: form.add(new Roo.form.HiddenField({ 'name' : 'test1' }));
16958  * 
16959  * @constructor
16960  * Creates a new Hidden form element.
16961  * @param {Object} config Configuration options
16962  */
16963
16964
16965
16966 // easy hidden field...
16967 Roo.form.Hidden = function(config){
16968     Roo.form.Hidden.superclass.constructor.call(this, config);
16969 };
16970   
16971 Roo.extend(Roo.form.Hidden, Roo.form.TextField, {
16972     fieldLabel:      '',
16973     inputType:      'hidden',
16974     width:          50,
16975     allowBlank:     true,
16976     labelSeparator: '',
16977     hidden:         true,
16978     itemCls :       'x-form-item-display-none'
16979
16980
16981 });
16982
16983
16984 /*
16985  * Based on:
16986  * Ext JS Library 1.1.1
16987  * Copyright(c) 2006-2007, Ext JS, LLC.
16988  *
16989  * Originally Released Under LGPL - original licence link has changed is not relivant.
16990  *
16991  * Fork - LGPL
16992  * <script type="text/javascript">
16993  */
16994  
16995 /**
16996  * @class Roo.form.TriggerField
16997  * @extends Roo.form.TextField
16998  * Provides a convenient wrapper for TextFields that adds a clickable trigger button (looks like a combobox by default).
16999  * The trigger has no default action, so you must assign a function to implement the trigger click handler by
17000  * overriding {@link #onTriggerClick}. You can create a TriggerField directly, as it renders exactly like a combobox
17001  * for which you can provide a custom implementation.  For example:
17002  * <pre><code>
17003 var trigger = new Roo.form.TriggerField();
17004 trigger.onTriggerClick = myTriggerFn;
17005 trigger.applyTo('my-field');
17006 </code></pre>
17007  *
17008  * However, in general you will most likely want to use TriggerField as the base class for a reusable component.
17009  * {@link Roo.form.DateField} and {@link Roo.form.ComboBox} are perfect examples of this.
17010  * @cfg {String} triggerClass An additional CSS class used to style the trigger button.  The trigger will always get the
17011  * class 'x-form-trigger' by default and triggerClass will be <b>appended</b> if specified.
17012  * @constructor
17013  * Create a new TriggerField.
17014  * @param {Object} config Configuration options (valid {@Roo.form.TextField} config options will also be applied
17015  * to the base TextField)
17016  */
17017 Roo.form.TriggerField = function(config){
17018     this.mimicing = false;
17019     Roo.form.TriggerField.superclass.constructor.call(this, config);
17020 };
17021
17022 Roo.extend(Roo.form.TriggerField, Roo.form.TextField,  {
17023     /**
17024      * @cfg {String} triggerClass A CSS class to apply to the trigger
17025      */
17026     /**
17027      * @cfg {String/Object} autoCreate A DomHelper element spec, or true for a default element spec (defaults to
17028      * {tag: "input", type: "text", size: "16", autocomplete: "off"})
17029      */
17030     defaultAutoCreate : {tag: "input", type: "text", size: "16", autocomplete: "new-password"},
17031     /**
17032      * @cfg {Boolean} hideTrigger True to hide the trigger element and display only the base text field (defaults to false)
17033      */
17034     hideTrigger:false,
17035
17036     /** @cfg {Boolean} grow @hide */
17037     /** @cfg {Number} growMin @hide */
17038     /** @cfg {Number} growMax @hide */
17039
17040     /**
17041      * @hide 
17042      * @method
17043      */
17044     autoSize: Roo.emptyFn,
17045     // private
17046     monitorTab : true,
17047     // private
17048     deferHeight : true,
17049
17050     
17051     actionMode : 'wrap',
17052     // private
17053     onResize : function(w, h){
17054         Roo.form.TriggerField.superclass.onResize.apply(this, arguments);
17055         if(typeof w == 'number'){
17056             var x = w - this.trigger.getWidth();
17057             this.el.setWidth(this.adjustWidth('input', x));
17058             this.trigger.setStyle('left', x+'px');
17059         }
17060     },
17061
17062     // private
17063     adjustSize : Roo.BoxComponent.prototype.adjustSize,
17064
17065     // private
17066     getResizeEl : function(){
17067         return this.wrap;
17068     },
17069
17070     // private
17071     getPositionEl : function(){
17072         return this.wrap;
17073     },
17074
17075     // private
17076     alignErrorIcon : function(){
17077         this.errorIcon.alignTo(this.wrap, 'tl-tr', [2, 0]);
17078     },
17079
17080     // private
17081     onRender : function(ct, position){
17082         Roo.form.TriggerField.superclass.onRender.call(this, ct, position);
17083         this.wrap = this.el.wrap({cls: "x-form-field-wrap"});
17084         this.trigger = this.wrap.createChild(this.triggerConfig ||
17085                 {tag: "img", src: Roo.BLANK_IMAGE_URL, cls: "x-form-trigger " + this.triggerClass});
17086         if(this.hideTrigger){
17087             this.trigger.setDisplayed(false);
17088         }
17089         this.initTrigger();
17090         if(!this.width){
17091             this.wrap.setWidth(this.el.getWidth()+this.trigger.getWidth());
17092         }
17093     },
17094
17095     // private
17096     initTrigger : function(){
17097         this.trigger.on("click", this.onTriggerClick, this, {preventDefault:true});
17098         this.trigger.addClassOnOver('x-form-trigger-over');
17099         this.trigger.addClassOnClick('x-form-trigger-click');
17100     },
17101
17102     // private
17103     onDestroy : function(){
17104         if(this.trigger){
17105             this.trigger.removeAllListeners();
17106             this.trigger.remove();
17107         }
17108         if(this.wrap){
17109             this.wrap.remove();
17110         }
17111         Roo.form.TriggerField.superclass.onDestroy.call(this);
17112     },
17113
17114     // private
17115     onFocus : function(){
17116         Roo.form.TriggerField.superclass.onFocus.call(this);
17117         if(!this.mimicing){
17118             this.wrap.addClass('x-trigger-wrap-focus');
17119             this.mimicing = true;
17120             Roo.get(Roo.isIE ? document.body : document).on("mousedown", this.mimicBlur, this);
17121             if(this.monitorTab){
17122                 this.el.on("keydown", this.checkTab, this);
17123             }
17124         }
17125     },
17126
17127     // private
17128     checkTab : function(e){
17129         if(e.getKey() == e.TAB){
17130             this.triggerBlur();
17131         }
17132     },
17133
17134     // private
17135     onBlur : function(){
17136         // do nothing
17137     },
17138
17139     // private
17140     mimicBlur : function(e, t){
17141         if(!this.wrap.contains(t) && this.validateBlur()){
17142             this.triggerBlur();
17143         }
17144     },
17145
17146     // private
17147     triggerBlur : function(){
17148         this.mimicing = false;
17149         Roo.get(Roo.isIE ? document.body : document).un("mousedown", this.mimicBlur);
17150         if(this.monitorTab){
17151             this.el.un("keydown", this.checkTab, this);
17152         }
17153         this.wrap.removeClass('x-trigger-wrap-focus');
17154         Roo.form.TriggerField.superclass.onBlur.call(this);
17155     },
17156
17157     // private
17158     // This should be overriden by any subclass that needs to check whether or not the field can be blurred.
17159     validateBlur : function(e, t){
17160         return true;
17161     },
17162
17163     // private
17164     onDisable : function(){
17165         Roo.form.TriggerField.superclass.onDisable.call(this);
17166         if(this.wrap){
17167             this.wrap.addClass('x-item-disabled');
17168         }
17169     },
17170
17171     // private
17172     onEnable : function(){
17173         Roo.form.TriggerField.superclass.onEnable.call(this);
17174         if(this.wrap){
17175             this.wrap.removeClass('x-item-disabled');
17176         }
17177     },
17178
17179     // private
17180     onShow : function(){
17181         var ae = this.getActionEl();
17182         
17183         if(ae){
17184             ae.dom.style.display = '';
17185             ae.dom.style.visibility = 'visible';
17186         }
17187     },
17188
17189     // private
17190     
17191     onHide : function(){
17192         var ae = this.getActionEl();
17193         ae.dom.style.display = 'none';
17194     },
17195
17196     /**
17197      * The function that should handle the trigger's click event.  This method does nothing by default until overridden
17198      * by an implementing function.
17199      * @method
17200      * @param {EventObject} e
17201      */
17202     onTriggerClick : Roo.emptyFn
17203 });
17204
17205 // TwinTriggerField is not a public class to be used directly.  It is meant as an abstract base class
17206 // to be extended by an implementing class.  For an example of implementing this class, see the custom
17207 // SearchField implementation here: http://extjs.com/deploy/ext/examples/form/custom.html
17208 Roo.form.TwinTriggerField = Roo.extend(Roo.form.TriggerField, {
17209     initComponent : function(){
17210         Roo.form.TwinTriggerField.superclass.initComponent.call(this);
17211
17212         this.triggerConfig = {
17213             tag:'span', cls:'x-form-twin-triggers', cn:[
17214             {tag: "img", src: Roo.BLANK_IMAGE_URL, cls: "x-form-trigger " + this.trigger1Class},
17215             {tag: "img", src: Roo.BLANK_IMAGE_URL, cls: "x-form-trigger " + this.trigger2Class}
17216         ]};
17217     },
17218
17219     getTrigger : function(index){
17220         return this.triggers[index];
17221     },
17222
17223     initTrigger : function(){
17224         var ts = this.trigger.select('.x-form-trigger', true);
17225         this.wrap.setStyle('overflow', 'hidden');
17226         var triggerField = this;
17227         ts.each(function(t, all, index){
17228             t.hide = function(){
17229                 var w = triggerField.wrap.getWidth();
17230                 this.dom.style.display = 'none';
17231                 triggerField.el.setWidth(w-triggerField.trigger.getWidth());
17232             };
17233             t.show = function(){
17234                 var w = triggerField.wrap.getWidth();
17235                 this.dom.style.display = '';
17236                 triggerField.el.setWidth(w-triggerField.trigger.getWidth());
17237             };
17238             var triggerIndex = 'Trigger'+(index+1);
17239
17240             if(this['hide'+triggerIndex]){
17241                 t.dom.style.display = 'none';
17242             }
17243             t.on("click", this['on'+triggerIndex+'Click'], this, {preventDefault:true});
17244             t.addClassOnOver('x-form-trigger-over');
17245             t.addClassOnClick('x-form-trigger-click');
17246         }, this);
17247         this.triggers = ts.elements;
17248     },
17249
17250     onTrigger1Click : Roo.emptyFn,
17251     onTrigger2Click : Roo.emptyFn
17252 });/*
17253  * Based on:
17254  * Ext JS Library 1.1.1
17255  * Copyright(c) 2006-2007, Ext JS, LLC.
17256  *
17257  * Originally Released Under LGPL - original licence link has changed is not relivant.
17258  *
17259  * Fork - LGPL
17260  * <script type="text/javascript">
17261  */
17262  
17263 /**
17264  * @class Roo.form.TextArea
17265  * @extends Roo.form.TextField
17266  * Multiline text field.  Can be used as a direct replacement for traditional textarea fields, plus adds
17267  * support for auto-sizing.
17268  * @constructor
17269  * Creates a new TextArea
17270  * @param {Object} config Configuration options
17271  */
17272 Roo.form.TextArea = function(config){
17273     Roo.form.TextArea.superclass.constructor.call(this, config);
17274     // these are provided exchanges for backwards compat
17275     // minHeight/maxHeight were replaced by growMin/growMax to be
17276     // compatible with TextField growing config values
17277     if(this.minHeight !== undefined){
17278         this.growMin = this.minHeight;
17279     }
17280     if(this.maxHeight !== undefined){
17281         this.growMax = this.maxHeight;
17282     }
17283 };
17284
17285 Roo.extend(Roo.form.TextArea, Roo.form.TextField,  {
17286     /**
17287      * @cfg {Number} growMin The minimum height to allow when grow = true (defaults to 60)
17288      */
17289     growMin : 60,
17290     /**
17291      * @cfg {Number} growMax The maximum height to allow when grow = true (defaults to 1000)
17292      */
17293     growMax: 1000,
17294     /**
17295      * @cfg {Boolean} preventScrollbars True to prevent scrollbars from appearing regardless of how much text is
17296      * in the field (equivalent to setting overflow: hidden, defaults to false)
17297      */
17298     preventScrollbars: false,
17299     /**
17300      * @cfg {String/Object} autoCreate A DomHelper element spec, or true for a default element spec (defaults to
17301      * {tag: "textarea", style: "width:300px;height:60px;", autocomplete: "off"})
17302      */
17303
17304     // private
17305     onRender : function(ct, position){
17306         if(!this.el){
17307             this.defaultAutoCreate = {
17308                 tag: "textarea",
17309                 style:"width:300px;height:60px;",
17310                 autocomplete: "new-password"
17311             };
17312         }
17313         Roo.form.TextArea.superclass.onRender.call(this, ct, position);
17314         if(this.grow){
17315             this.textSizeEl = Roo.DomHelper.append(document.body, {
17316                 tag: "pre", cls: "x-form-grow-sizer"
17317             });
17318             if(this.preventScrollbars){
17319                 this.el.setStyle("overflow", "hidden");
17320             }
17321             this.el.setHeight(this.growMin);
17322         }
17323     },
17324
17325     onDestroy : function(){
17326         if(this.textSizeEl){
17327             this.textSizeEl.parentNode.removeChild(this.textSizeEl);
17328         }
17329         Roo.form.TextArea.superclass.onDestroy.call(this);
17330     },
17331
17332     // private
17333     onKeyUp : function(e){
17334         if(!e.isNavKeyPress() || e.getKey() == e.ENTER){
17335             this.autoSize();
17336         }
17337     },
17338
17339     /**
17340      * Automatically grows the field to accomodate the height of the text up to the maximum field height allowed.
17341      * This only takes effect if grow = true, and fires the autosize event if the height changes.
17342      */
17343     autoSize : function(){
17344         if(!this.grow || !this.textSizeEl){
17345             return;
17346         }
17347         var el = this.el;
17348         var v = el.dom.value;
17349         var ts = this.textSizeEl;
17350
17351         ts.innerHTML = '';
17352         ts.appendChild(document.createTextNode(v));
17353         v = ts.innerHTML;
17354
17355         Roo.fly(ts).setWidth(this.el.getWidth());
17356         if(v.length < 1){
17357             v = "&#160;&#160;";
17358         }else{
17359             if(Roo.isIE){
17360                 v = v.replace(/\n/g, '<p>&#160;</p>');
17361             }
17362             v += "&#160;\n&#160;";
17363         }
17364         ts.innerHTML = v;
17365         var h = Math.min(this.growMax, Math.max(ts.offsetHeight, this.growMin));
17366         if(h != this.lastHeight){
17367             this.lastHeight = h;
17368             this.el.setHeight(h);
17369             this.fireEvent("autosize", this, h);
17370         }
17371     }
17372 });/*
17373  * Based on:
17374  * Ext JS Library 1.1.1
17375  * Copyright(c) 2006-2007, Ext JS, LLC.
17376  *
17377  * Originally Released Under LGPL - original licence link has changed is not relivant.
17378  *
17379  * Fork - LGPL
17380  * <script type="text/javascript">
17381  */
17382  
17383
17384 /**
17385  * @class Roo.form.NumberField
17386  * @extends Roo.form.TextField
17387  * Numeric text field that provides automatic keystroke filtering and numeric validation.
17388  * @constructor
17389  * Creates a new NumberField
17390  * @param {Object} config Configuration options
17391  */
17392 Roo.form.NumberField = function(config){
17393     Roo.form.NumberField.superclass.constructor.call(this, config);
17394 };
17395
17396 Roo.extend(Roo.form.NumberField, Roo.form.TextField,  {
17397     /**
17398      * @cfg {String} fieldClass The default CSS class for the field (defaults to "x-form-field x-form-num-field")
17399      */
17400     fieldClass: "x-form-field x-form-num-field",
17401     /**
17402      * @cfg {Boolean} allowDecimals False to disallow decimal values (defaults to true)
17403      */
17404     allowDecimals : true,
17405     /**
17406      * @cfg {String} decimalSeparator Character(s) to allow as the decimal separator (defaults to '.')
17407      */
17408     decimalSeparator : ".",
17409     /**
17410      * @cfg {Number} decimalPrecision The maximum precision to display after the decimal separator (defaults to 2)
17411      */
17412     decimalPrecision : 2,
17413     /**
17414      * @cfg {Boolean} allowNegative False to prevent entering a negative sign (defaults to true)
17415      */
17416     allowNegative : true,
17417     /**
17418      * @cfg {Number} minValue The minimum allowed value (defaults to Number.NEGATIVE_INFINITY)
17419      */
17420     minValue : Number.NEGATIVE_INFINITY,
17421     /**
17422      * @cfg {Number} maxValue The maximum allowed value (defaults to Number.MAX_VALUE)
17423      */
17424     maxValue : Number.MAX_VALUE,
17425     /**
17426      * @cfg {String} minText Error text to display if the minimum value validation fails (defaults to "The minimum value for this field is {minValue}")
17427      */
17428     minText : "The minimum value for this field is {0}",
17429     /**
17430      * @cfg {String} maxText Error text to display if the maximum value validation fails (defaults to "The maximum value for this field is {maxValue}")
17431      */
17432     maxText : "The maximum value for this field is {0}",
17433     /**
17434      * @cfg {String} nanText Error text to display if the value is not a valid number.  For example, this can happen
17435      * if a valid character like '.' or '-' is left in the field with no number (defaults to "{value} is not a valid number")
17436      */
17437     nanText : "{0} is not a valid number",
17438
17439     // private
17440     initEvents : function(){
17441         Roo.form.NumberField.superclass.initEvents.call(this);
17442         var allowed = "0123456789";
17443         if(this.allowDecimals){
17444             allowed += this.decimalSeparator;
17445         }
17446         if(this.allowNegative){
17447             allowed += "-";
17448         }
17449         this.stripCharsRe = new RegExp('[^'+allowed+']', 'gi');
17450         var keyPress = function(e){
17451             var k = e.getKey();
17452             if(!Roo.isIE && (e.isSpecialKey() || k == e.BACKSPACE || k == e.DELETE)){
17453                 return;
17454             }
17455             var c = e.getCharCode();
17456             if(allowed.indexOf(String.fromCharCode(c)) === -1){
17457                 e.stopEvent();
17458             }
17459         };
17460         this.el.on("keypress", keyPress, this);
17461     },
17462
17463     // private
17464     validateValue : function(value){
17465         if(!Roo.form.NumberField.superclass.validateValue.call(this, value)){
17466             return false;
17467         }
17468         if(value.length < 1){ // if it's blank and textfield didn't flag it then it's valid
17469              return true;
17470         }
17471         var num = this.parseValue(value);
17472         if(isNaN(num)){
17473             this.markInvalid(String.format(this.nanText, value));
17474             return false;
17475         }
17476         if(num < this.minValue){
17477             this.markInvalid(String.format(this.minText, this.minValue));
17478             return false;
17479         }
17480         if(num > this.maxValue){
17481             this.markInvalid(String.format(this.maxText, this.maxValue));
17482             return false;
17483         }
17484         return true;
17485     },
17486
17487     getValue : function(){
17488         return this.fixPrecision(this.parseValue(Roo.form.NumberField.superclass.getValue.call(this)));
17489     },
17490
17491     // private
17492     parseValue : function(value){
17493         value = parseFloat(String(value).replace(this.decimalSeparator, "."));
17494         return isNaN(value) ? '' : value;
17495     },
17496
17497     // private
17498     fixPrecision : function(value){
17499         var nan = isNaN(value);
17500         if(!this.allowDecimals || this.decimalPrecision == -1 || nan || !value){
17501             return nan ? '' : value;
17502         }
17503         return parseFloat(value).toFixed(this.decimalPrecision);
17504     },
17505
17506     setValue : function(v){
17507         v = this.fixPrecision(v);
17508         Roo.form.NumberField.superclass.setValue.call(this, String(v).replace(".", this.decimalSeparator));
17509     },
17510
17511     // private
17512     decimalPrecisionFcn : function(v){
17513         return Math.floor(v);
17514     },
17515
17516     beforeBlur : function(){
17517         var v = this.parseValue(this.getRawValue());
17518         if(v){
17519             this.setValue(v);
17520         }
17521     }
17522 });/*
17523  * Based on:
17524  * Ext JS Library 1.1.1
17525  * Copyright(c) 2006-2007, Ext JS, LLC.
17526  *
17527  * Originally Released Under LGPL - original licence link has changed is not relivant.
17528  *
17529  * Fork - LGPL
17530  * <script type="text/javascript">
17531  */
17532  
17533 /**
17534  * @class Roo.form.DateField
17535  * @extends Roo.form.TriggerField
17536  * Provides a date input field with a {@link Roo.DatePicker} dropdown and automatic date validation.
17537 * @constructor
17538 * Create a new DateField
17539 * @param {Object} config
17540  */
17541 Roo.form.DateField = function(config)
17542 {
17543     Roo.form.DateField.superclass.constructor.call(this, config);
17544     
17545       this.addEvents({
17546          
17547         /**
17548          * @event select
17549          * Fires when a date is selected
17550              * @param {Roo.form.DateField} combo This combo box
17551              * @param {Date} date The date selected
17552              */
17553         'select' : true
17554          
17555     });
17556     
17557     
17558     if(typeof this.minValue == "string") {
17559         this.minValue = this.parseDate(this.minValue);
17560     }
17561     if(typeof this.maxValue == "string") {
17562         this.maxValue = this.parseDate(this.maxValue);
17563     }
17564     this.ddMatch = null;
17565     if(this.disabledDates){
17566         var dd = this.disabledDates;
17567         var re = "(?:";
17568         for(var i = 0; i < dd.length; i++){
17569             re += dd[i];
17570             if(i != dd.length-1) {
17571                 re += "|";
17572             }
17573         }
17574         this.ddMatch = new RegExp(re + ")");
17575     }
17576 };
17577
17578 Roo.extend(Roo.form.DateField, Roo.form.TriggerField,  {
17579     /**
17580      * @cfg {String} format
17581      * The default date format string which can be overriden for localization support.  The format must be
17582      * valid according to {@link Date#parseDate} (defaults to 'm/d/y').
17583      */
17584     format : "m/d/y",
17585     /**
17586      * @cfg {String} altFormats
17587      * Multiple date formats separated by "|" to try when parsing a user input value and it doesn't match the defined
17588      * format (defaults to 'm/d/Y|m-d-y|m-d-Y|m/d|m-d|d').
17589      */
17590     altFormats : "m/d/Y|m-d-y|m-d-Y|m/d|m-d|md|mdy|mdY|d",
17591     /**
17592      * @cfg {Array} disabledDays
17593      * An array of days to disable, 0 based. For example, [0, 6] disables Sunday and Saturday (defaults to null).
17594      */
17595     disabledDays : null,
17596     /**
17597      * @cfg {String} disabledDaysText
17598      * The tooltip to display when the date falls on a disabled day (defaults to 'Disabled')
17599      */
17600     disabledDaysText : "Disabled",
17601     /**
17602      * @cfg {Array} disabledDates
17603      * An array of "dates" to disable, as strings. These strings will be used to build a dynamic regular
17604      * expression so they are very powerful. Some examples:
17605      * <ul>
17606      * <li>["03/08/2003", "09/16/2003"] would disable those exact dates</li>
17607      * <li>["03/08", "09/16"] would disable those days for every year</li>
17608      * <li>["^03/08"] would only match the beginning (useful if you are using short years)</li>
17609      * <li>["03/../2006"] would disable every day in March 2006</li>
17610      * <li>["^03"] would disable every day in every March</li>
17611      * </ul>
17612      * In order to support regular expressions, if you are using a date format that has "." in it, you will have to
17613      * escape the dot when restricting dates. For example: ["03\\.08\\.03"].
17614      */
17615     disabledDates : null,
17616     /**
17617      * @cfg {String} disabledDatesText
17618      * The tooltip text to display when the date falls on a disabled date (defaults to 'Disabled')
17619      */
17620     disabledDatesText : "Disabled",
17621         
17622         
17623         /**
17624      * @cfg {Date/String} zeroValue
17625      * if the date is less that this number, then the field is rendered as empty
17626      * default is 1800
17627      */
17628         zeroValue : '1800-01-01',
17629         
17630         
17631     /**
17632      * @cfg {Date/String} minValue
17633      * The minimum allowed date. Can be either a Javascript date object or a string date in a
17634      * valid format (defaults to null).
17635      */
17636     minValue : null,
17637     /**
17638      * @cfg {Date/String} maxValue
17639      * The maximum allowed date. Can be either a Javascript date object or a string date in a
17640      * valid format (defaults to null).
17641      */
17642     maxValue : null,
17643     /**
17644      * @cfg {String} minText
17645      * The error text to display when the date in the cell is before minValue (defaults to
17646      * 'The date in this field must be after {minValue}').
17647      */
17648     minText : "The date in this field must be equal to or after {0}",
17649     /**
17650      * @cfg {String} maxText
17651      * The error text to display when the date in the cell is after maxValue (defaults to
17652      * 'The date in this field must be before {maxValue}').
17653      */
17654     maxText : "The date in this field must be equal to or before {0}",
17655     /**
17656      * @cfg {String} invalidText
17657      * The error text to display when the date in the field is invalid (defaults to
17658      * '{value} is not a valid date - it must be in the format {format}').
17659      */
17660     invalidText : "{0} is not a valid date - it must be in the format {1}",
17661     /**
17662      * @cfg {String} triggerClass
17663      * An additional CSS class used to style the trigger button.  The trigger will always get the
17664      * class 'x-form-trigger' and triggerClass will be <b>appended</b> if specified (defaults to 'x-form-date-trigger'
17665      * which displays a calendar icon).
17666      */
17667     triggerClass : 'x-form-date-trigger',
17668     
17669
17670     /**
17671      * @cfg {Boolean} useIso
17672      * if enabled, then the date field will use a hidden field to store the 
17673      * real value as iso formated date. default (false)
17674      */ 
17675     useIso : false,
17676     /**
17677      * @cfg {String/Object} autoCreate
17678      * A DomHelper element spec, or true for a default element spec (defaults to
17679      * {tag: "input", type: "text", size: "10", autocomplete: "off"})
17680      */ 
17681     // private
17682     defaultAutoCreate : {tag: "input", type: "text", size: "10", autocomplete: "off"},
17683     
17684     // private
17685     hiddenField: false,
17686     
17687     onRender : function(ct, position)
17688     {
17689         Roo.form.DateField.superclass.onRender.call(this, ct, position);
17690         if (this.useIso) {
17691             //this.el.dom.removeAttribute('name'); 
17692             Roo.log("Changing name?");
17693             this.el.dom.setAttribute('name', this.name + '____hidden___' ); 
17694             this.hiddenField = this.el.insertSibling({ tag:'input', type:'hidden', name: this.name },
17695                     'before', true);
17696             this.hiddenField.value = this.value ? this.formatDate(this.value, 'Y-m-d') : '';
17697             // prevent input submission
17698             this.hiddenName = this.name;
17699         }
17700             
17701             
17702     },
17703     
17704     // private
17705     validateValue : function(value)
17706     {
17707         value = this.formatDate(value);
17708         if(!Roo.form.DateField.superclass.validateValue.call(this, value)){
17709             Roo.log('super failed');
17710             return false;
17711         }
17712         if(value.length < 1){ // if it's blank and textfield didn't flag it then it's valid
17713              return true;
17714         }
17715         var svalue = value;
17716         value = this.parseDate(value);
17717         if(!value){
17718             Roo.log('parse date failed' + svalue);
17719             this.markInvalid(String.format(this.invalidText, svalue, this.format));
17720             return false;
17721         }
17722         var time = value.getTime();
17723         if(this.minValue && time < this.minValue.getTime()){
17724             this.markInvalid(String.format(this.minText, this.formatDate(this.minValue)));
17725             return false;
17726         }
17727         if(this.maxValue && time > this.maxValue.getTime()){
17728             this.markInvalid(String.format(this.maxText, this.formatDate(this.maxValue)));
17729             return false;
17730         }
17731         if(this.disabledDays){
17732             var day = value.getDay();
17733             for(var i = 0; i < this.disabledDays.length; i++) {
17734                 if(day === this.disabledDays[i]){
17735                     this.markInvalid(this.disabledDaysText);
17736                     return false;
17737                 }
17738             }
17739         }
17740         var fvalue = this.formatDate(value);
17741         if(this.ddMatch && this.ddMatch.test(fvalue)){
17742             this.markInvalid(String.format(this.disabledDatesText, fvalue));
17743             return false;
17744         }
17745         return true;
17746     },
17747
17748     // private
17749     // Provides logic to override the default TriggerField.validateBlur which just returns true
17750     validateBlur : function(){
17751         return !this.menu || !this.menu.isVisible();
17752     },
17753     
17754     getName: function()
17755     {
17756         // returns hidden if it's set..
17757         if (!this.rendered) {return ''};
17758         return !this.hiddenName && this.el.dom.name  ? this.el.dom.name : (this.hiddenName || '');
17759         
17760     },
17761
17762     /**
17763      * Returns the current date value of the date field.
17764      * @return {Date} The date value
17765      */
17766     getValue : function(){
17767         
17768         return  this.hiddenField ?
17769                 this.hiddenField.value :
17770                 this.parseDate(Roo.form.DateField.superclass.getValue.call(this)) || "";
17771     },
17772
17773     /**
17774      * Sets the value of the date field.  You can pass a date object or any string that can be parsed into a valid
17775      * date, using DateField.format as the date format, according to the same rules as {@link Date#parseDate}
17776      * (the default format used is "m/d/y").
17777      * <br />Usage:
17778      * <pre><code>
17779 //All of these calls set the same date value (May 4, 2006)
17780
17781 //Pass a date object:
17782 var dt = new Date('5/4/06');
17783 dateField.setValue(dt);
17784
17785 //Pass a date string (default format):
17786 dateField.setValue('5/4/06');
17787
17788 //Pass a date string (custom format):
17789 dateField.format = 'Y-m-d';
17790 dateField.setValue('2006-5-4');
17791 </code></pre>
17792      * @param {String/Date} date The date or valid date string
17793      */
17794     setValue : function(date){
17795         if (this.hiddenField) {
17796             this.hiddenField.value = this.formatDate(this.parseDate(date), 'Y-m-d');
17797         }
17798         Roo.form.DateField.superclass.setValue.call(this, this.formatDate(this.parseDate(date)));
17799         // make sure the value field is always stored as a date..
17800         this.value = this.parseDate(date);
17801         
17802         
17803     },
17804
17805     // private
17806     parseDate : function(value){
17807                 
17808                 if (value instanceof Date) {
17809                         if (value < Date.parseDate(this.zeroValue, 'Y-m-d') ) {
17810                                 return  '';
17811                         }
17812                         return value;
17813                 }
17814                 
17815                 
17816         if(!value || value instanceof Date){
17817             return value;
17818         }
17819         var v = Date.parseDate(value, this.format);
17820          if (!v && this.useIso) {
17821             v = Date.parseDate(value, 'Y-m-d');
17822         }
17823         if(!v && this.altFormats){
17824             if(!this.altFormatsArray){
17825                 this.altFormatsArray = this.altFormats.split("|");
17826             }
17827             for(var i = 0, len = this.altFormatsArray.length; i < len && !v; i++){
17828                 v = Date.parseDate(value, this.altFormatsArray[i]);
17829             }
17830         }
17831                 if (v < Date.parseDate(this.zeroValue, 'Y-m-d') ) {
17832                         v = '';
17833                 }
17834         return v;
17835     },
17836
17837     // private
17838     formatDate : function(date, fmt){
17839         return (!date || !(date instanceof Date)) ?
17840                date : date.dateFormat(fmt || this.format);
17841     },
17842
17843     // private
17844     menuListeners : {
17845         select: function(m, d){
17846             
17847             this.setValue(d);
17848             this.fireEvent('select', this, d);
17849         },
17850         show : function(){ // retain focus styling
17851             this.onFocus();
17852         },
17853         hide : function(){
17854             this.focus.defer(10, this);
17855             var ml = this.menuListeners;
17856             this.menu.un("select", ml.select,  this);
17857             this.menu.un("show", ml.show,  this);
17858             this.menu.un("hide", ml.hide,  this);
17859         }
17860     },
17861
17862     // private
17863     // Implements the default empty TriggerField.onTriggerClick function to display the DatePicker
17864     onTriggerClick : function(){
17865         if(this.disabled){
17866             return;
17867         }
17868         if(this.menu == null){
17869             this.menu = new Roo.menu.DateMenu();
17870         }
17871         Roo.apply(this.menu.picker,  {
17872             showClear: this.allowBlank,
17873             minDate : this.minValue,
17874             maxDate : this.maxValue,
17875             disabledDatesRE : this.ddMatch,
17876             disabledDatesText : this.disabledDatesText,
17877             disabledDays : this.disabledDays,
17878             disabledDaysText : this.disabledDaysText,
17879             format : this.useIso ? 'Y-m-d' : this.format,
17880             minText : String.format(this.minText, this.formatDate(this.minValue)),
17881             maxText : String.format(this.maxText, this.formatDate(this.maxValue))
17882         });
17883         this.menu.on(Roo.apply({}, this.menuListeners, {
17884             scope:this
17885         }));
17886         this.menu.picker.setValue(this.getValue() || new Date());
17887         this.menu.show(this.el, "tl-bl?");
17888     },
17889
17890     beforeBlur : function(){
17891         var v = this.parseDate(this.getRawValue());
17892         if(v){
17893             this.setValue(v);
17894         }
17895     },
17896
17897     /*@
17898      * overide
17899      * 
17900      */
17901     isDirty : function() {
17902         if(this.disabled) {
17903             return false;
17904         }
17905         
17906         if(typeof(this.startValue) === 'undefined'){
17907             return false;
17908         }
17909         
17910         return String(this.getValue()) !== String(this.startValue);
17911         
17912     },
17913     // @overide
17914     cleanLeadingSpace : function(e)
17915     {
17916        return;
17917     }
17918     
17919 });/*
17920  * Based on:
17921  * Ext JS Library 1.1.1
17922  * Copyright(c) 2006-2007, Ext JS, LLC.
17923  *
17924  * Originally Released Under LGPL - original licence link has changed is not relivant.
17925  *
17926  * Fork - LGPL
17927  * <script type="text/javascript">
17928  */
17929  
17930 /**
17931  * @class Roo.form.MonthField
17932  * @extends Roo.form.TriggerField
17933  * Provides a date input field with a {@link Roo.DatePicker} dropdown and automatic date validation.
17934 * @constructor
17935 * Create a new MonthField
17936 * @param {Object} config
17937  */
17938 Roo.form.MonthField = function(config){
17939     
17940     Roo.form.MonthField.superclass.constructor.call(this, config);
17941     
17942       this.addEvents({
17943          
17944         /**
17945          * @event select
17946          * Fires when a date is selected
17947              * @param {Roo.form.MonthFieeld} combo This combo box
17948              * @param {Date} date The date selected
17949              */
17950         'select' : true
17951          
17952     });
17953     
17954     
17955     if(typeof this.minValue == "string") {
17956         this.minValue = this.parseDate(this.minValue);
17957     }
17958     if(typeof this.maxValue == "string") {
17959         this.maxValue = this.parseDate(this.maxValue);
17960     }
17961     this.ddMatch = null;
17962     if(this.disabledDates){
17963         var dd = this.disabledDates;
17964         var re = "(?:";
17965         for(var i = 0; i < dd.length; i++){
17966             re += dd[i];
17967             if(i != dd.length-1) {
17968                 re += "|";
17969             }
17970         }
17971         this.ddMatch = new RegExp(re + ")");
17972     }
17973 };
17974
17975 Roo.extend(Roo.form.MonthField, Roo.form.TriggerField,  {
17976     /**
17977      * @cfg {String} format
17978      * The default date format string which can be overriden for localization support.  The format must be
17979      * valid according to {@link Date#parseDate} (defaults to 'm/d/y').
17980      */
17981     format : "M Y",
17982     /**
17983      * @cfg {String} altFormats
17984      * Multiple date formats separated by "|" to try when parsing a user input value and it doesn't match the defined
17985      * format (defaults to 'm/d/Y|m-d-y|m-d-Y|m/d|m-d|d').
17986      */
17987     altFormats : "M Y|m/Y|m-y|m-Y|my|mY",
17988     /**
17989      * @cfg {Array} disabledDays
17990      * An array of days to disable, 0 based. For example, [0, 6] disables Sunday and Saturday (defaults to null).
17991      */
17992     disabledDays : [0,1,2,3,4,5,6],
17993     /**
17994      * @cfg {String} disabledDaysText
17995      * The tooltip to display when the date falls on a disabled day (defaults to 'Disabled')
17996      */
17997     disabledDaysText : "Disabled",
17998     /**
17999      * @cfg {Array} disabledDates
18000      * An array of "dates" to disable, as strings. These strings will be used to build a dynamic regular
18001      * expression so they are very powerful. Some examples:
18002      * <ul>
18003      * <li>["03/08/2003", "09/16/2003"] would disable those exact dates</li>
18004      * <li>["03/08", "09/16"] would disable those days for every year</li>
18005      * <li>["^03/08"] would only match the beginning (useful if you are using short years)</li>
18006      * <li>["03/../2006"] would disable every day in March 2006</li>
18007      * <li>["^03"] would disable every day in every March</li>
18008      * </ul>
18009      * In order to support regular expressions, if you are using a date format that has "." in it, you will have to
18010      * escape the dot when restricting dates. For example: ["03\\.08\\.03"].
18011      */
18012     disabledDates : null,
18013     /**
18014      * @cfg {String} disabledDatesText
18015      * The tooltip text to display when the date falls on a disabled date (defaults to 'Disabled')
18016      */
18017     disabledDatesText : "Disabled",
18018     /**
18019      * @cfg {Date/String} minValue
18020      * The minimum allowed date. Can be either a Javascript date object or a string date in a
18021      * valid format (defaults to null).
18022      */
18023     minValue : null,
18024     /**
18025      * @cfg {Date/String} maxValue
18026      * The maximum allowed date. Can be either a Javascript date object or a string date in a
18027      * valid format (defaults to null).
18028      */
18029     maxValue : null,
18030     /**
18031      * @cfg {String} minText
18032      * The error text to display when the date in the cell is before minValue (defaults to
18033      * 'The date in this field must be after {minValue}').
18034      */
18035     minText : "The date in this field must be equal to or after {0}",
18036     /**
18037      * @cfg {String} maxTextf
18038      * The error text to display when the date in the cell is after maxValue (defaults to
18039      * 'The date in this field must be before {maxValue}').
18040      */
18041     maxText : "The date in this field must be equal to or before {0}",
18042     /**
18043      * @cfg {String} invalidText
18044      * The error text to display when the date in the field is invalid (defaults to
18045      * '{value} is not a valid date - it must be in the format {format}').
18046      */
18047     invalidText : "{0} is not a valid date - it must be in the format {1}",
18048     /**
18049      * @cfg {String} triggerClass
18050      * An additional CSS class used to style the trigger button.  The trigger will always get the
18051      * class 'x-form-trigger' and triggerClass will be <b>appended</b> if specified (defaults to 'x-form-date-trigger'
18052      * which displays a calendar icon).
18053      */
18054     triggerClass : 'x-form-date-trigger',
18055     
18056
18057     /**
18058      * @cfg {Boolean} useIso
18059      * if enabled, then the date field will use a hidden field to store the 
18060      * real value as iso formated date. default (true)
18061      */ 
18062     useIso : true,
18063     /**
18064      * @cfg {String/Object} autoCreate
18065      * A DomHelper element spec, or true for a default element spec (defaults to
18066      * {tag: "input", type: "text", size: "10", autocomplete: "off"})
18067      */ 
18068     // private
18069     defaultAutoCreate : {tag: "input", type: "text", size: "10", autocomplete: "new-password"},
18070     
18071     // private
18072     hiddenField: false,
18073     
18074     hideMonthPicker : false,
18075     
18076     onRender : function(ct, position)
18077     {
18078         Roo.form.MonthField.superclass.onRender.call(this, ct, position);
18079         if (this.useIso) {
18080             this.el.dom.removeAttribute('name'); 
18081             this.hiddenField = this.el.insertSibling({ tag:'input', type:'hidden', name: this.name },
18082                     'before', true);
18083             this.hiddenField.value = this.value ? this.formatDate(this.value, 'Y-m-d') : '';
18084             // prevent input submission
18085             this.hiddenName = this.name;
18086         }
18087             
18088             
18089     },
18090     
18091     // private
18092     validateValue : function(value)
18093     {
18094         value = this.formatDate(value);
18095         if(!Roo.form.MonthField.superclass.validateValue.call(this, value)){
18096             return false;
18097         }
18098         if(value.length < 1){ // if it's blank and textfield didn't flag it then it's valid
18099              return true;
18100         }
18101         var svalue = value;
18102         value = this.parseDate(value);
18103         if(!value){
18104             this.markInvalid(String.format(this.invalidText, svalue, this.format));
18105             return false;
18106         }
18107         var time = value.getTime();
18108         if(this.minValue && time < this.minValue.getTime()){
18109             this.markInvalid(String.format(this.minText, this.formatDate(this.minValue)));
18110             return false;
18111         }
18112         if(this.maxValue && time > this.maxValue.getTime()){
18113             this.markInvalid(String.format(this.maxText, this.formatDate(this.maxValue)));
18114             return false;
18115         }
18116         /*if(this.disabledDays){
18117             var day = value.getDay();
18118             for(var i = 0; i < this.disabledDays.length; i++) {
18119                 if(day === this.disabledDays[i]){
18120                     this.markInvalid(this.disabledDaysText);
18121                     return false;
18122                 }
18123             }
18124         }
18125         */
18126         var fvalue = this.formatDate(value);
18127         /*if(this.ddMatch && this.ddMatch.test(fvalue)){
18128             this.markInvalid(String.format(this.disabledDatesText, fvalue));
18129             return false;
18130         }
18131         */
18132         return true;
18133     },
18134
18135     // private
18136     // Provides logic to override the default TriggerField.validateBlur which just returns true
18137     validateBlur : function(){
18138         return !this.menu || !this.menu.isVisible();
18139     },
18140
18141     /**
18142      * Returns the current date value of the date field.
18143      * @return {Date} The date value
18144      */
18145     getValue : function(){
18146         
18147         
18148         
18149         return  this.hiddenField ?
18150                 this.hiddenField.value :
18151                 this.parseDate(Roo.form.MonthField.superclass.getValue.call(this)) || "";
18152     },
18153
18154     /**
18155      * Sets the value of the date field.  You can pass a date object or any string that can be parsed into a valid
18156      * date, using MonthField.format as the date format, according to the same rules as {@link Date#parseDate}
18157      * (the default format used is "m/d/y").
18158      * <br />Usage:
18159      * <pre><code>
18160 //All of these calls set the same date value (May 4, 2006)
18161
18162 //Pass a date object:
18163 var dt = new Date('5/4/06');
18164 monthField.setValue(dt);
18165
18166 //Pass a date string (default format):
18167 monthField.setValue('5/4/06');
18168
18169 //Pass a date string (custom format):
18170 monthField.format = 'Y-m-d';
18171 monthField.setValue('2006-5-4');
18172 </code></pre>
18173      * @param {String/Date} date The date or valid date string
18174      */
18175     setValue : function(date){
18176         Roo.log('month setValue' + date);
18177         // can only be first of month..
18178         
18179         var val = this.parseDate(date);
18180         
18181         if (this.hiddenField) {
18182             this.hiddenField.value = this.formatDate(this.parseDate(date), 'Y-m-d');
18183         }
18184         Roo.form.MonthField.superclass.setValue.call(this, this.formatDate(this.parseDate(date)));
18185         this.value = this.parseDate(date);
18186     },
18187
18188     // private
18189     parseDate : function(value){
18190         if(!value || value instanceof Date){
18191             value = value ? Date.parseDate(value.format('Y-m') + '-01', 'Y-m-d') : null;
18192             return value;
18193         }
18194         var v = Date.parseDate(value, this.format);
18195         if (!v && this.useIso) {
18196             v = Date.parseDate(value, 'Y-m-d');
18197         }
18198         if (v) {
18199             // 
18200             v = Date.parseDate(v.format('Y-m') +'-01', 'Y-m-d');
18201         }
18202         
18203         
18204         if(!v && this.altFormats){
18205             if(!this.altFormatsArray){
18206                 this.altFormatsArray = this.altFormats.split("|");
18207             }
18208             for(var i = 0, len = this.altFormatsArray.length; i < len && !v; i++){
18209                 v = Date.parseDate(value, this.altFormatsArray[i]);
18210             }
18211         }
18212         return v;
18213     },
18214
18215     // private
18216     formatDate : function(date, fmt){
18217         return (!date || !(date instanceof Date)) ?
18218                date : date.dateFormat(fmt || this.format);
18219     },
18220
18221     // private
18222     menuListeners : {
18223         select: function(m, d){
18224             this.setValue(d);
18225             this.fireEvent('select', this, d);
18226         },
18227         show : function(){ // retain focus styling
18228             this.onFocus();
18229         },
18230         hide : function(){
18231             this.focus.defer(10, this);
18232             var ml = this.menuListeners;
18233             this.menu.un("select", ml.select,  this);
18234             this.menu.un("show", ml.show,  this);
18235             this.menu.un("hide", ml.hide,  this);
18236         }
18237     },
18238     // private
18239     // Implements the default empty TriggerField.onTriggerClick function to display the DatePicker
18240     onTriggerClick : function(){
18241         if(this.disabled){
18242             return;
18243         }
18244         if(this.menu == null){
18245             this.menu = new Roo.menu.DateMenu();
18246            
18247         }
18248         
18249         Roo.apply(this.menu.picker,  {
18250             
18251             showClear: this.allowBlank,
18252             minDate : this.minValue,
18253             maxDate : this.maxValue,
18254             disabledDatesRE : this.ddMatch,
18255             disabledDatesText : this.disabledDatesText,
18256             
18257             format : this.useIso ? 'Y-m-d' : this.format,
18258             minText : String.format(this.minText, this.formatDate(this.minValue)),
18259             maxText : String.format(this.maxText, this.formatDate(this.maxValue))
18260             
18261         });
18262          this.menu.on(Roo.apply({}, this.menuListeners, {
18263             scope:this
18264         }));
18265        
18266         
18267         var m = this.menu;
18268         var p = m.picker;
18269         
18270         // hide month picker get's called when we called by 'before hide';
18271         
18272         var ignorehide = true;
18273         p.hideMonthPicker  = function(disableAnim){
18274             if (ignorehide) {
18275                 return;
18276             }
18277              if(this.monthPicker){
18278                 Roo.log("hideMonthPicker called");
18279                 if(disableAnim === true){
18280                     this.monthPicker.hide();
18281                 }else{
18282                     this.monthPicker.slideOut('t', {duration:.2});
18283                     p.setValue(new Date(m.picker.mpSelYear, m.picker.mpSelMonth, 1));
18284                     p.fireEvent("select", this, this.value);
18285                     m.hide();
18286                 }
18287             }
18288         }
18289         
18290         Roo.log('picker set value');
18291         Roo.log(this.getValue());
18292         p.setValue(this.getValue() ? this.parseDate(this.getValue()) : new Date());
18293         m.show(this.el, 'tl-bl?');
18294         ignorehide  = false;
18295         // this will trigger hideMonthPicker..
18296         
18297         
18298         // hidden the day picker
18299         Roo.select('.x-date-picker table', true).first().dom.style.visibility = "hidden";
18300         
18301         
18302         
18303       
18304         
18305         p.showMonthPicker.defer(100, p);
18306     
18307         
18308        
18309     },
18310
18311     beforeBlur : function(){
18312         var v = this.parseDate(this.getRawValue());
18313         if(v){
18314             this.setValue(v);
18315         }
18316     }
18317
18318     /** @cfg {Boolean} grow @hide */
18319     /** @cfg {Number} growMin @hide */
18320     /** @cfg {Number} growMax @hide */
18321     /**
18322      * @hide
18323      * @method autoSize
18324      */
18325 });/*
18326  * Based on:
18327  * Ext JS Library 1.1.1
18328  * Copyright(c) 2006-2007, Ext JS, LLC.
18329  *
18330  * Originally Released Under LGPL - original licence link has changed is not relivant.
18331  *
18332  * Fork - LGPL
18333  * <script type="text/javascript">
18334  */
18335  
18336
18337 /**
18338  * @class Roo.form.ComboBox
18339  * @extends Roo.form.TriggerField
18340  * A combobox control with support for autocomplete, remote-loading, paging and many other features.
18341  * @constructor
18342  * Create a new ComboBox.
18343  * @param {Object} config Configuration options
18344  */
18345 Roo.form.ComboBox = function(config){
18346     Roo.form.ComboBox.superclass.constructor.call(this, config);
18347     this.addEvents({
18348         /**
18349          * @event expand
18350          * Fires when the dropdown list is expanded
18351              * @param {Roo.form.ComboBox} combo This combo box
18352              */
18353         'expand' : true,
18354         /**
18355          * @event collapse
18356          * Fires when the dropdown list is collapsed
18357              * @param {Roo.form.ComboBox} combo This combo box
18358              */
18359         'collapse' : true,
18360         /**
18361          * @event beforeselect
18362          * Fires before a list item is selected. Return false to cancel the selection.
18363              * @param {Roo.form.ComboBox} combo This combo box
18364              * @param {Roo.data.Record} record The data record returned from the underlying store
18365              * @param {Number} index The index of the selected item in the dropdown list
18366              */
18367         'beforeselect' : true,
18368         /**
18369          * @event select
18370          * Fires when a list item is selected
18371              * @param {Roo.form.ComboBox} combo This combo box
18372              * @param {Roo.data.Record} record The data record returned from the underlying store (or false on clear)
18373              * @param {Number} index The index of the selected item in the dropdown list
18374              */
18375         'select' : true,
18376         /**
18377          * @event beforequery
18378          * Fires before all queries are processed. Return false to cancel the query or set cancel to true.
18379          * The event object passed has these properties:
18380              * @param {Roo.form.ComboBox} combo This combo box
18381              * @param {String} query The query
18382              * @param {Boolean} forceAll true to force "all" query
18383              * @param {Boolean} cancel true to cancel the query
18384              * @param {Object} e The query event object
18385              */
18386         'beforequery': true,
18387          /**
18388          * @event add
18389          * Fires when the 'add' icon is pressed (add a listener to enable add button)
18390              * @param {Roo.form.ComboBox} combo This combo box
18391              */
18392         'add' : true,
18393         /**
18394          * @event edit
18395          * Fires when the 'edit' icon is pressed (add a listener to enable add button)
18396              * @param {Roo.form.ComboBox} combo This combo box
18397              * @param {Roo.data.Record|false} record The data record returned from the underlying store (or false on nothing selected)
18398              */
18399         'edit' : true
18400         
18401         
18402     });
18403     if(this.transform){
18404         this.allowDomMove = false;
18405         var s = Roo.getDom(this.transform);
18406         if(!this.hiddenName){
18407             this.hiddenName = s.name;
18408         }
18409         if(!this.store){
18410             this.mode = 'local';
18411             var d = [], opts = s.options;
18412             for(var i = 0, len = opts.length;i < len; i++){
18413                 var o = opts[i];
18414                 var value = (Roo.isIE ? o.getAttributeNode('value').specified : o.hasAttribute('value')) ? o.value : o.text;
18415                 if(o.selected) {
18416                     this.value = value;
18417                 }
18418                 d.push([value, o.text]);
18419             }
18420             this.store = new Roo.data.SimpleStore({
18421                 'id': 0,
18422                 fields: ['value', 'text'],
18423                 data : d
18424             });
18425             this.valueField = 'value';
18426             this.displayField = 'text';
18427         }
18428         s.name = Roo.id(); // wipe out the name in case somewhere else they have a reference
18429         if(!this.lazyRender){
18430             this.target = true;
18431             this.el = Roo.DomHelper.insertBefore(s, this.autoCreate || this.defaultAutoCreate);
18432             s.parentNode.removeChild(s); // remove it
18433             this.render(this.el.parentNode);
18434         }else{
18435             s.parentNode.removeChild(s); // remove it
18436         }
18437
18438     }
18439     if (this.store) {
18440         this.store = Roo.factory(this.store, Roo.data);
18441     }
18442     
18443     this.selectedIndex = -1;
18444     if(this.mode == 'local'){
18445         if(config.queryDelay === undefined){
18446             this.queryDelay = 10;
18447         }
18448         if(config.minChars === undefined){
18449             this.minChars = 0;
18450         }
18451     }
18452 };
18453
18454 Roo.extend(Roo.form.ComboBox, Roo.form.TriggerField, {
18455     /**
18456      * @cfg {String/HTMLElement/Element} transform The id, DOM node or element of an existing select to convert to a ComboBox
18457      */
18458     /**
18459      * @cfg {Boolean} lazyRender True to prevent the ComboBox from rendering until requested (should always be used when
18460      * rendering into an Roo.Editor, defaults to false)
18461      */
18462     /**
18463      * @cfg {Boolean/Object} autoCreate A DomHelper element spec, or true for a default element spec (defaults to:
18464      * {tag: "input", type: "text", size: "24", autocomplete: "off"})
18465      */
18466     /**
18467      * @cfg {Roo.data.Store} store The data store to which this combo is bound (defaults to undefined)
18468      */
18469     /**
18470      * @cfg {String} title If supplied, a header element is created containing this text and added into the top of
18471      * the dropdown list (defaults to undefined, with no header element)
18472      */
18473
18474      /**
18475      * @cfg {String/Roo.Template} tpl The template to use to render the output
18476      */
18477      
18478     // private
18479     defaultAutoCreate : {tag: "input", type: "text", size: "24", autocomplete: "off"},
18480     /**
18481      * @cfg {Number} listWidth The width in pixels of the dropdown list (defaults to the width of the ComboBox field)
18482      */
18483     listWidth: undefined,
18484     /**
18485      * @cfg {String} displayField The underlying data field name to bind to this CombBox (defaults to undefined if
18486      * mode = 'remote' or 'text' if mode = 'local')
18487      */
18488     displayField: undefined,
18489     /**
18490      * @cfg {String} valueField The underlying data value name to bind to this CombBox (defaults to undefined if
18491      * mode = 'remote' or 'value' if mode = 'local'). 
18492      * Note: use of a valueField requires the user make a selection
18493      * in order for a value to be mapped.
18494      */
18495     valueField: undefined,
18496     
18497     
18498     /**
18499      * @cfg {String} hiddenName If specified, a hidden form field with this name is dynamically generated to store the
18500      * field's data value (defaults to the underlying DOM element's name)
18501      */
18502     hiddenName: undefined,
18503     /**
18504      * @cfg {String} listClass CSS class to apply to the dropdown list element (defaults to '')
18505      */
18506     listClass: '',
18507     /**
18508      * @cfg {String} selectedClass CSS class to apply to the selected item in the dropdown list (defaults to 'x-combo-selected')
18509      */
18510     selectedClass: 'x-combo-selected',
18511     /**
18512      * @cfg {String} triggerClass An additional CSS class used to style the trigger button.  The trigger will always get the
18513      * class 'x-form-trigger' and triggerClass will be <b>appended</b> if specified (defaults to 'x-form-arrow-trigger'
18514      * which displays a downward arrow icon).
18515      */
18516     triggerClass : 'x-form-arrow-trigger',
18517     /**
18518      * @cfg {Boolean/String} shadow True or "sides" for the default effect, "frame" for 4-way shadow, and "drop" for bottom-right
18519      */
18520     shadow:'sides',
18521     /**
18522      * @cfg {String} listAlign A valid anchor position value. See {@link Roo.Element#alignTo} for details on supported
18523      * anchor positions (defaults to 'tl-bl')
18524      */
18525     listAlign: 'tl-bl?',
18526     /**
18527      * @cfg {Number} maxHeight The maximum height in pixels of the dropdown list before scrollbars are shown (defaults to 300)
18528      */
18529     maxHeight: 300,
18530     /**
18531      * @cfg {String} triggerAction The action to execute when the trigger field is activated.  Use 'all' to run the
18532      * query specified by the allQuery config option (defaults to 'query')
18533      */
18534     triggerAction: 'query',
18535     /**
18536      * @cfg {Number} minChars The minimum number of characters the user must type before autocomplete and typeahead activate
18537      * (defaults to 4, does not apply if editable = false)
18538      */
18539     minChars : 4,
18540     /**
18541      * @cfg {Boolean} typeAhead True to populate and autoselect the remainder of the text being typed after a configurable
18542      * delay (typeAheadDelay) if it matches a known value (defaults to false)
18543      */
18544     typeAhead: false,
18545     /**
18546      * @cfg {Number} queryDelay The length of time in milliseconds to delay between the start of typing and sending the
18547      * query to filter the dropdown list (defaults to 500 if mode = 'remote' or 10 if mode = 'local')
18548      */
18549     queryDelay: 500,
18550     /**
18551      * @cfg {Number} pageSize If greater than 0, a paging toolbar is displayed in the footer of the dropdown list and the
18552      * filter queries will execute with page start and limit parameters.  Only applies when mode = 'remote' (defaults to 0)
18553      */
18554     pageSize: 0,
18555     /**
18556      * @cfg {Boolean} selectOnFocus True to select any existing text in the field immediately on focus.  Only applies
18557      * when editable = true (defaults to false)
18558      */
18559     selectOnFocus:false,
18560     /**
18561      * @cfg {String} queryParam Name of the query as it will be passed on the querystring (defaults to 'query')
18562      */
18563     queryParam: 'query',
18564     /**
18565      * @cfg {String} loadingText The text to display in the dropdown list while data is loading.  Only applies
18566      * when mode = 'remote' (defaults to 'Loading...')
18567      */
18568     loadingText: 'Loading...',
18569     /**
18570      * @cfg {Boolean} resizable True to add a resize handle to the bottom of the dropdown list (defaults to false)
18571      */
18572     resizable: false,
18573     /**
18574      * @cfg {Number} handleHeight The height in pixels of the dropdown list resize handle if resizable = true (defaults to 8)
18575      */
18576     handleHeight : 8,
18577     /**
18578      * @cfg {Boolean} editable False to prevent the user from typing text directly into the field, just like a
18579      * traditional select (defaults to true)
18580      */
18581     editable: true,
18582     /**
18583      * @cfg {String} allQuery The text query to send to the server to return all records for the list with no filtering (defaults to '')
18584      */
18585     allQuery: '',
18586     /**
18587      * @cfg {String} mode Set to 'local' if the ComboBox loads local data (defaults to 'remote' which loads from the server)
18588      */
18589     mode: 'remote',
18590     /**
18591      * @cfg {Number} minListWidth The minimum width of the dropdown list in pixels (defaults to 70, will be ignored if
18592      * listWidth has a higher value)
18593      */
18594     minListWidth : 70,
18595     /**
18596      * @cfg {Boolean} forceSelection True to restrict the selected value to one of the values in the list, false to
18597      * allow the user to set arbitrary text into the field (defaults to false)
18598      */
18599     forceSelection:false,
18600     /**
18601      * @cfg {Number} typeAheadDelay The length of time in milliseconds to wait until the typeahead text is displayed
18602      * if typeAhead = true (defaults to 250)
18603      */
18604     typeAheadDelay : 250,
18605     /**
18606      * @cfg {String} valueNotFoundText When using a name/value combo, if the value passed to setValue is not found in
18607      * the store, valueNotFoundText will be displayed as the field text if defined (defaults to undefined)
18608      */
18609     valueNotFoundText : undefined,
18610     /**
18611      * @cfg {Boolean} blockFocus Prevents all focus calls, so it can work with things like HTML edtor bar
18612      */
18613     blockFocus : false,
18614     
18615     /**
18616      * @cfg {Boolean} disableClear Disable showing of clear button.
18617      */
18618     disableClear : false,
18619     /**
18620      * @cfg {Boolean} alwaysQuery  Disable caching of results, and always send query
18621      */
18622     alwaysQuery : false,
18623     
18624     //private
18625     addicon : false,
18626     editicon: false,
18627     
18628     // element that contains real text value.. (when hidden is used..)
18629      
18630     // private
18631     onRender : function(ct, position)
18632     {
18633         Roo.form.ComboBox.superclass.onRender.call(this, ct, position);
18634         
18635         if(this.hiddenName){
18636             this.hiddenField = this.el.insertSibling({tag:'input', type:'hidden', name: this.hiddenName, id:  (this.hiddenId||this.hiddenName)},
18637                     'before', true);
18638             this.hiddenField.value =
18639                 this.hiddenValue !== undefined ? this.hiddenValue :
18640                 this.value !== undefined ? this.value : '';
18641
18642             // prevent input submission
18643             this.el.dom.removeAttribute('name');
18644              
18645              
18646         }
18647         
18648         if(Roo.isGecko){
18649             this.el.dom.setAttribute('autocomplete', 'off');
18650         }
18651
18652         var cls = 'x-combo-list';
18653
18654         this.list = new Roo.Layer({
18655             shadow: this.shadow, cls: [cls, this.listClass].join(' '), constrain:false
18656         });
18657
18658         var lw = this.listWidth || Math.max(this.wrap.getWidth(), this.minListWidth);
18659         this.list.setWidth(lw);
18660         this.list.swallowEvent('mousewheel');
18661         this.assetHeight = 0;
18662
18663         if(this.title){
18664             this.header = this.list.createChild({cls:cls+'-hd', html: this.title});
18665             this.assetHeight += this.header.getHeight();
18666         }
18667
18668         this.innerList = this.list.createChild({cls:cls+'-inner'});
18669         this.innerList.on('mouseover', this.onViewOver, this);
18670         this.innerList.on('mousemove', this.onViewMove, this);
18671         this.innerList.setWidth(lw - this.list.getFrameWidth('lr'));
18672         
18673         if(this.allowBlank && !this.pageSize && !this.disableClear){
18674             this.footer = this.list.createChild({cls:cls+'-ft'});
18675             this.pageTb = new Roo.Toolbar(this.footer);
18676            
18677         }
18678         if(this.pageSize){
18679             this.footer = this.list.createChild({cls:cls+'-ft'});
18680             this.pageTb = new Roo.PagingToolbar(this.footer, this.store,
18681                     {pageSize: this.pageSize});
18682             
18683         }
18684         
18685         if (this.pageTb && this.allowBlank && !this.disableClear) {
18686             var _this = this;
18687             this.pageTb.add(new Roo.Toolbar.Fill(), {
18688                 cls: 'x-btn-icon x-btn-clear',
18689                 text: '&#160;',
18690                 handler: function()
18691                 {
18692                     _this.collapse();
18693                     _this.clearValue();
18694                     _this.onSelect(false, -1);
18695                 }
18696             });
18697         }
18698         if (this.footer) {
18699             this.assetHeight += this.footer.getHeight();
18700         }
18701         
18702
18703         if(!this.tpl){
18704             this.tpl = '<div class="'+cls+'-item">{' + this.displayField + '}</div>';
18705         }
18706
18707         this.view = new Roo.View(this.innerList, this.tpl, {
18708             singleSelect:true,
18709             store: this.store,
18710             selectedClass: this.selectedClass
18711         });
18712
18713         this.view.on('click', this.onViewClick, this);
18714
18715         this.store.on('beforeload', this.onBeforeLoad, this);
18716         this.store.on('load', this.onLoad, this);
18717         this.store.on('loadexception', this.onLoadException, this);
18718
18719         if(this.resizable){
18720             this.resizer = new Roo.Resizable(this.list,  {
18721                pinned:true, handles:'se'
18722             });
18723             this.resizer.on('resize', function(r, w, h){
18724                 this.maxHeight = h-this.handleHeight-this.list.getFrameWidth('tb')-this.assetHeight;
18725                 this.listWidth = w;
18726                 this.innerList.setWidth(w - this.list.getFrameWidth('lr'));
18727                 this.restrictHeight();
18728             }, this);
18729             this[this.pageSize?'footer':'innerList'].setStyle('margin-bottom', this.handleHeight+'px');
18730         }
18731         if(!this.editable){
18732             this.editable = true;
18733             this.setEditable(false);
18734         }  
18735         
18736         
18737         if (typeof(this.events.add.listeners) != 'undefined') {
18738             
18739             this.addicon = this.wrap.createChild(
18740                 {tag: 'img', src: Roo.BLANK_IMAGE_URL, cls: 'x-form-combo-add' });  
18741        
18742             this.addicon.on('click', function(e) {
18743                 this.fireEvent('add', this);
18744             }, this);
18745         }
18746         if (typeof(this.events.edit.listeners) != 'undefined') {
18747             
18748             this.editicon = this.wrap.createChild(
18749                 {tag: 'img', src: Roo.BLANK_IMAGE_URL, cls: 'x-form-combo-edit' });  
18750             if (this.addicon) {
18751                 this.editicon.setStyle('margin-left', '40px');
18752             }
18753             this.editicon.on('click', function(e) {
18754                 
18755                 // we fire even  if inothing is selected..
18756                 this.fireEvent('edit', this, this.lastData );
18757                 
18758             }, this);
18759         }
18760         
18761         
18762         
18763     },
18764
18765     // private
18766     initEvents : function(){
18767         Roo.form.ComboBox.superclass.initEvents.call(this);
18768
18769         this.keyNav = new Roo.KeyNav(this.el, {
18770             "up" : function(e){
18771                 this.inKeyMode = true;
18772                 this.selectPrev();
18773             },
18774
18775             "down" : function(e){
18776                 if(!this.isExpanded()){
18777                     this.onTriggerClick();
18778                 }else{
18779                     this.inKeyMode = true;
18780                     this.selectNext();
18781                 }
18782             },
18783
18784             "enter" : function(e){
18785                 this.onViewClick();
18786                 //return true;
18787             },
18788
18789             "esc" : function(e){
18790                 this.collapse();
18791             },
18792
18793             "tab" : function(e){
18794                 this.onViewClick(false);
18795                 this.fireEvent("specialkey", this, e);
18796                 return true;
18797             },
18798
18799             scope : this,
18800
18801             doRelay : function(foo, bar, hname){
18802                 if(hname == 'down' || this.scope.isExpanded()){
18803                    return Roo.KeyNav.prototype.doRelay.apply(this, arguments);
18804                 }
18805                 return true;
18806             },
18807
18808             forceKeyDown: true
18809         });
18810         this.queryDelay = Math.max(this.queryDelay || 10,
18811                 this.mode == 'local' ? 10 : 250);
18812         this.dqTask = new Roo.util.DelayedTask(this.initQuery, this);
18813         if(this.typeAhead){
18814             this.taTask = new Roo.util.DelayedTask(this.onTypeAhead, this);
18815         }
18816         if(this.editable !== false){
18817             this.el.on("keyup", this.onKeyUp, this);
18818         }
18819         if(this.forceSelection){
18820             this.on('blur', this.doForce, this);
18821         }
18822     },
18823
18824     onDestroy : function(){
18825         if(this.view){
18826             this.view.setStore(null);
18827             this.view.el.removeAllListeners();
18828             this.view.el.remove();
18829             this.view.purgeListeners();
18830         }
18831         if(this.list){
18832             this.list.destroy();
18833         }
18834         if(this.store){
18835             this.store.un('beforeload', this.onBeforeLoad, this);
18836             this.store.un('load', this.onLoad, this);
18837             this.store.un('loadexception', this.onLoadException, this);
18838         }
18839         Roo.form.ComboBox.superclass.onDestroy.call(this);
18840     },
18841
18842     // private
18843     fireKey : function(e){
18844         if(e.isNavKeyPress() && !this.list.isVisible()){
18845             this.fireEvent("specialkey", this, e);
18846         }
18847     },
18848
18849     // private
18850     onResize: function(w, h){
18851         Roo.form.ComboBox.superclass.onResize.apply(this, arguments);
18852         
18853         if(typeof w != 'number'){
18854             // we do not handle it!?!?
18855             return;
18856         }
18857         var tw = this.trigger.getWidth();
18858         tw += this.addicon ? this.addicon.getWidth() : 0;
18859         tw += this.editicon ? this.editicon.getWidth() : 0;
18860         var x = w - tw;
18861         this.el.setWidth( this.adjustWidth('input', x));
18862             
18863         this.trigger.setStyle('left', x+'px');
18864         
18865         if(this.list && this.listWidth === undefined){
18866             var lw = Math.max(x + this.trigger.getWidth(), this.minListWidth);
18867             this.list.setWidth(lw);
18868             this.innerList.setWidth(lw - this.list.getFrameWidth('lr'));
18869         }
18870         
18871     
18872         
18873     },
18874
18875     /**
18876      * Allow or prevent the user from directly editing the field text.  If false is passed,
18877      * the user will only be able to select from the items defined in the dropdown list.  This method
18878      * is the runtime equivalent of setting the 'editable' config option at config time.
18879      * @param {Boolean} value True to allow the user to directly edit the field text
18880      */
18881     setEditable : function(value){
18882         if(value == this.editable){
18883             return;
18884         }
18885         this.editable = value;
18886         if(!value){
18887             this.el.dom.setAttribute('readOnly', true);
18888             this.el.on('mousedown', this.onTriggerClick,  this);
18889             this.el.addClass('x-combo-noedit');
18890         }else{
18891             this.el.dom.setAttribute('readOnly', false);
18892             this.el.un('mousedown', this.onTriggerClick,  this);
18893             this.el.removeClass('x-combo-noedit');
18894         }
18895     },
18896
18897     // private
18898     onBeforeLoad : function(){
18899         if(!this.hasFocus){
18900             return;
18901         }
18902         this.innerList.update(this.loadingText ?
18903                '<div class="loading-indicator">'+this.loadingText+'</div>' : '');
18904         this.restrictHeight();
18905         this.selectedIndex = -1;
18906     },
18907
18908     // private
18909     onLoad : function(){
18910         if(!this.hasFocus){
18911             return;
18912         }
18913         if(this.store.getCount() > 0){
18914             this.expand();
18915             this.restrictHeight();
18916             if(this.lastQuery == this.allQuery){
18917                 if(this.editable){
18918                     this.el.dom.select();
18919                 }
18920                 if(!this.selectByValue(this.value, true)){
18921                     this.select(0, true);
18922                 }
18923             }else{
18924                 this.selectNext();
18925                 if(this.typeAhead && this.lastKey != Roo.EventObject.BACKSPACE && this.lastKey != Roo.EventObject.DELETE){
18926                     this.taTask.delay(this.typeAheadDelay);
18927                 }
18928             }
18929         }else{
18930             this.onEmptyResults();
18931         }
18932         //this.el.focus();
18933     },
18934     // private
18935     onLoadException : function()
18936     {
18937         this.collapse();
18938         Roo.log(this.store.reader.jsonData);
18939         if (this.store && typeof(this.store.reader.jsonData.errorMsg) != 'undefined') {
18940             Roo.MessageBox.alert("Error loading",this.store.reader.jsonData.errorMsg);
18941         }
18942         
18943         
18944     },
18945     // private
18946     onTypeAhead : function(){
18947         if(this.store.getCount() > 0){
18948             var r = this.store.getAt(0);
18949             var newValue = r.data[this.displayField];
18950             var len = newValue.length;
18951             var selStart = this.getRawValue().length;
18952             if(selStart != len){
18953                 this.setRawValue(newValue);
18954                 this.selectText(selStart, newValue.length);
18955             }
18956         }
18957     },
18958
18959     // private
18960     onSelect : function(record, index){
18961         if(this.fireEvent('beforeselect', this, record, index) !== false){
18962             this.setFromData(index > -1 ? record.data : false);
18963             this.collapse();
18964             this.fireEvent('select', this, record, index);
18965         }
18966     },
18967
18968     /**
18969      * Returns the currently selected field value or empty string if no value is set.
18970      * @return {String} value The selected value
18971      */
18972     getValue : function(){
18973         if(this.valueField){
18974             return typeof this.value != 'undefined' ? this.value : '';
18975         }
18976         return Roo.form.ComboBox.superclass.getValue.call(this);
18977     },
18978
18979     /**
18980      * Clears any text/value currently set in the field
18981      */
18982     clearValue : function(){
18983         if(this.hiddenField){
18984             this.hiddenField.value = '';
18985         }
18986         this.value = '';
18987         this.setRawValue('');
18988         this.lastSelectionText = '';
18989         
18990     },
18991
18992     /**
18993      * Sets the specified value into the field.  If the value finds a match, the corresponding record text
18994      * will be displayed in the field.  If the value does not match the data value of an existing item,
18995      * and the valueNotFoundText config option is defined, it will be displayed as the default field text.
18996      * Otherwise the field will be blank (although the value will still be set).
18997      * @param {String} value The value to match
18998      */
18999     setValue : function(v){
19000         var text = v;
19001         if(this.valueField){
19002             var r = this.findRecord(this.valueField, v);
19003             if(r){
19004                 text = r.data[this.displayField];
19005             }else if(this.valueNotFoundText !== undefined){
19006                 text = this.valueNotFoundText;
19007             }
19008         }
19009         this.lastSelectionText = text;
19010         if(this.hiddenField){
19011             this.hiddenField.value = v;
19012         }
19013         Roo.form.ComboBox.superclass.setValue.call(this, text);
19014         this.value = v;
19015     },
19016     /**
19017      * @property {Object} the last set data for the element
19018      */
19019     
19020     lastData : false,
19021     /**
19022      * Sets the value of the field based on a object which is related to the record format for the store.
19023      * @param {Object} value the value to set as. or false on reset?
19024      */
19025     setFromData : function(o){
19026         var dv = ''; // display value
19027         var vv = ''; // value value..
19028         this.lastData = o;
19029         if (this.displayField) {
19030             dv = !o || typeof(o[this.displayField]) == 'undefined' ? '' : o[this.displayField];
19031         } else {
19032             // this is an error condition!!!
19033             Roo.log('no  displayField value set for '+ (this.name ? this.name : this.id));
19034         }
19035         
19036         if(this.valueField){
19037             vv = !o || typeof(o[this.valueField]) == 'undefined' ? dv : o[this.valueField];
19038         }
19039         if(this.hiddenField){
19040             this.hiddenField.value = vv;
19041             
19042             this.lastSelectionText = dv;
19043             Roo.form.ComboBox.superclass.setValue.call(this, dv);
19044             this.value = vv;
19045             return;
19046         }
19047         // no hidden field.. - we store the value in 'value', but still display
19048         // display field!!!!
19049         this.lastSelectionText = dv;
19050         Roo.form.ComboBox.superclass.setValue.call(this, dv);
19051         this.value = vv;
19052         
19053         
19054     },
19055     // private
19056     reset : function(){
19057         // overridden so that last data is reset..
19058         this.setValue(this.resetValue);
19059         this.originalValue = this.getValue();
19060         this.clearInvalid();
19061         this.lastData = false;
19062         if (this.view) {
19063             this.view.clearSelections();
19064         }
19065     },
19066     // private
19067     findRecord : function(prop, value){
19068         var record;
19069         if(this.store.getCount() > 0){
19070             this.store.each(function(r){
19071                 if(r.data[prop] == value){
19072                     record = r;
19073                     return false;
19074                 }
19075                 return true;
19076             });
19077         }
19078         return record;
19079     },
19080     
19081     getName: function()
19082     {
19083         // returns hidden if it's set..
19084         if (!this.rendered) {return ''};
19085         return !this.hiddenName && this.el.dom.name  ? this.el.dom.name : (this.hiddenName || '');
19086         
19087     },
19088     // private
19089     onViewMove : function(e, t){
19090         this.inKeyMode = false;
19091     },
19092
19093     // private
19094     onViewOver : function(e, t){
19095         if(this.inKeyMode){ // prevent key nav and mouse over conflicts
19096             return;
19097         }
19098         var item = this.view.findItemFromChild(t);
19099         if(item){
19100             var index = this.view.indexOf(item);
19101             this.select(index, false);
19102         }
19103     },
19104
19105     // private
19106     onViewClick : function(doFocus)
19107     {
19108         var index = this.view.getSelectedIndexes()[0];
19109         var r = this.store.getAt(index);
19110         if(r){
19111             this.onSelect(r, index);
19112         }
19113         if(doFocus !== false && !this.blockFocus){
19114             this.el.focus();
19115         }
19116     },
19117
19118     // private
19119     restrictHeight : function(){
19120         this.innerList.dom.style.height = '';
19121         var inner = this.innerList.dom;
19122         var h = Math.max(inner.clientHeight, inner.offsetHeight, inner.scrollHeight);
19123         this.innerList.setHeight(h < this.maxHeight ? 'auto' : this.maxHeight);
19124         this.list.beginUpdate();
19125         this.list.setHeight(this.innerList.getHeight()+this.list.getFrameWidth('tb')+(this.resizable?this.handleHeight:0)+this.assetHeight);
19126         this.list.alignTo(this.el, this.listAlign);
19127         this.list.endUpdate();
19128     },
19129
19130     // private
19131     onEmptyResults : function(){
19132         this.collapse();
19133     },
19134
19135     /**
19136      * Returns true if the dropdown list is expanded, else false.
19137      */
19138     isExpanded : function(){
19139         return this.list.isVisible();
19140     },
19141
19142     /**
19143      * Select an item in the dropdown list by its data value. This function does NOT cause the select event to fire.
19144      * The store must be loaded and the list expanded for this function to work, otherwise use setValue.
19145      * @param {String} value The data value of the item to select
19146      * @param {Boolean} scrollIntoView False to prevent the dropdown list from autoscrolling to display the
19147      * selected item if it is not currently in view (defaults to true)
19148      * @return {Boolean} True if the value matched an item in the list, else false
19149      */
19150     selectByValue : function(v, scrollIntoView){
19151         if(v !== undefined && v !== null){
19152             var r = this.findRecord(this.valueField || this.displayField, v);
19153             if(r){
19154                 this.select(this.store.indexOf(r), scrollIntoView);
19155                 return true;
19156             }
19157         }
19158         return false;
19159     },
19160
19161     /**
19162      * Select an item in the dropdown list by its numeric index in the list. This function does NOT cause the select event to fire.
19163      * The store must be loaded and the list expanded for this function to work, otherwise use setValue.
19164      * @param {Number} index The zero-based index of the list item to select
19165      * @param {Boolean} scrollIntoView False to prevent the dropdown list from autoscrolling to display the
19166      * selected item if it is not currently in view (defaults to true)
19167      */
19168     select : function(index, scrollIntoView){
19169         this.selectedIndex = index;
19170         this.view.select(index);
19171         if(scrollIntoView !== false){
19172             var el = this.view.getNode(index);
19173             if(el){
19174                 this.innerList.scrollChildIntoView(el, false);
19175             }
19176         }
19177     },
19178
19179     // private
19180     selectNext : function(){
19181         var ct = this.store.getCount();
19182         if(ct > 0){
19183             if(this.selectedIndex == -1){
19184                 this.select(0);
19185             }else if(this.selectedIndex < ct-1){
19186                 this.select(this.selectedIndex+1);
19187             }
19188         }
19189     },
19190
19191     // private
19192     selectPrev : function(){
19193         var ct = this.store.getCount();
19194         if(ct > 0){
19195             if(this.selectedIndex == -1){
19196                 this.select(0);
19197             }else if(this.selectedIndex != 0){
19198                 this.select(this.selectedIndex-1);
19199             }
19200         }
19201     },
19202
19203     // private
19204     onKeyUp : function(e){
19205         if(this.editable !== false && !e.isSpecialKey()){
19206             this.lastKey = e.getKey();
19207             this.dqTask.delay(this.queryDelay);
19208         }
19209     },
19210
19211     // private
19212     validateBlur : function(){
19213         return !this.list || !this.list.isVisible();   
19214     },
19215
19216     // private
19217     initQuery : function(){
19218         this.doQuery(this.getRawValue());
19219     },
19220
19221     // private
19222     doForce : function(){
19223         if(this.el.dom.value.length > 0){
19224             this.el.dom.value =
19225                 this.lastSelectionText === undefined ? '' : this.lastSelectionText;
19226              
19227         }
19228     },
19229
19230     /**
19231      * Execute a query to filter the dropdown list.  Fires the beforequery event prior to performing the
19232      * query allowing the query action to be canceled if needed.
19233      * @param {String} query The SQL query to execute
19234      * @param {Boolean} forceAll True to force the query to execute even if there are currently fewer characters
19235      * in the field than the minimum specified by the minChars config option.  It also clears any filter previously
19236      * saved in the current store (defaults to false)
19237      */
19238     doQuery : function(q, forceAll){
19239         if(q === undefined || q === null){
19240             q = '';
19241         }
19242         var qe = {
19243             query: q,
19244             forceAll: forceAll,
19245             combo: this,
19246             cancel:false
19247         };
19248         if(this.fireEvent('beforequery', qe)===false || qe.cancel){
19249             return false;
19250         }
19251         q = qe.query;
19252         forceAll = qe.forceAll;
19253         if(forceAll === true || (q.length >= this.minChars)){
19254             if(this.lastQuery != q || this.alwaysQuery){
19255                 this.lastQuery = q;
19256                 if(this.mode == 'local'){
19257                     this.selectedIndex = -1;
19258                     if(forceAll){
19259                         this.store.clearFilter();
19260                     }else{
19261                         this.store.filter(this.displayField, q);
19262                     }
19263                     this.onLoad();
19264                 }else{
19265                     this.store.baseParams[this.queryParam] = q;
19266                     this.store.load({
19267                         params: this.getParams(q)
19268                     });
19269                     this.expand();
19270                 }
19271             }else{
19272                 this.selectedIndex = -1;
19273                 this.onLoad();   
19274             }
19275         }
19276     },
19277
19278     // private
19279     getParams : function(q){
19280         var p = {};
19281         //p[this.queryParam] = q;
19282         if(this.pageSize){
19283             p.start = 0;
19284             p.limit = this.pageSize;
19285         }
19286         return p;
19287     },
19288
19289     /**
19290      * Hides the dropdown list if it is currently expanded. Fires the 'collapse' event on completion.
19291      */
19292     collapse : function(){
19293         if(!this.isExpanded()){
19294             return;
19295         }
19296         this.list.hide();
19297         Roo.get(document).un('mousedown', this.collapseIf, this);
19298         Roo.get(document).un('mousewheel', this.collapseIf, this);
19299         if (!this.editable) {
19300             Roo.get(document).un('keydown', this.listKeyPress, this);
19301         }
19302         this.fireEvent('collapse', this);
19303     },
19304
19305     // private
19306     collapseIf : function(e){
19307         if(!e.within(this.wrap) && !e.within(this.list)){
19308             this.collapse();
19309         }
19310     },
19311
19312     /**
19313      * Expands the dropdown list if it is currently hidden. Fires the 'expand' event on completion.
19314      */
19315     expand : function(){
19316         if(this.isExpanded() || !this.hasFocus){
19317             return;
19318         }
19319         this.list.alignTo(this.el, this.listAlign);
19320         this.list.show();
19321         Roo.get(document).on('mousedown', this.collapseIf, this);
19322         Roo.get(document).on('mousewheel', this.collapseIf, this);
19323         if (!this.editable) {
19324             Roo.get(document).on('keydown', this.listKeyPress, this);
19325         }
19326         
19327         this.fireEvent('expand', this);
19328     },
19329
19330     // private
19331     // Implements the default empty TriggerField.onTriggerClick function
19332     onTriggerClick : function(){
19333         if(this.disabled){
19334             return;
19335         }
19336         if(this.isExpanded()){
19337             this.collapse();
19338             if (!this.blockFocus) {
19339                 this.el.focus();
19340             }
19341             
19342         }else {
19343             this.hasFocus = true;
19344             if(this.triggerAction == 'all') {
19345                 this.doQuery(this.allQuery, true);
19346             } else {
19347                 this.doQuery(this.getRawValue());
19348             }
19349             if (!this.blockFocus) {
19350                 this.el.focus();
19351             }
19352         }
19353     },
19354     listKeyPress : function(e)
19355     {
19356         //Roo.log('listkeypress');
19357         // scroll to first matching element based on key pres..
19358         if (e.isSpecialKey()) {
19359             return false;
19360         }
19361         var k = String.fromCharCode(e.getKey()).toUpperCase();
19362         //Roo.log(k);
19363         var match  = false;
19364         var csel = this.view.getSelectedNodes();
19365         var cselitem = false;
19366         if (csel.length) {
19367             var ix = this.view.indexOf(csel[0]);
19368             cselitem  = this.store.getAt(ix);
19369             if (!cselitem.get(this.displayField) || cselitem.get(this.displayField).substring(0,1).toUpperCase() != k) {
19370                 cselitem = false;
19371             }
19372             
19373         }
19374         
19375         this.store.each(function(v) { 
19376             if (cselitem) {
19377                 // start at existing selection.
19378                 if (cselitem.id == v.id) {
19379                     cselitem = false;
19380                 }
19381                 return;
19382             }
19383                 
19384             if (v.get(this.displayField) && v.get(this.displayField).substring(0,1).toUpperCase() == k) {
19385                 match = this.store.indexOf(v);
19386                 return false;
19387             }
19388         }, this);
19389         
19390         if (match === false) {
19391             return true; // no more action?
19392         }
19393         // scroll to?
19394         this.view.select(match);
19395         var sn = Roo.get(this.view.getSelectedNodes()[0]);
19396         sn.scrollIntoView(sn.dom.parentNode, false);
19397     } 
19398
19399     /** 
19400     * @cfg {Boolean} grow 
19401     * @hide 
19402     */
19403     /** 
19404     * @cfg {Number} growMin 
19405     * @hide 
19406     */
19407     /** 
19408     * @cfg {Number} growMax 
19409     * @hide 
19410     */
19411     /**
19412      * @hide
19413      * @method autoSize
19414      */
19415 });/*
19416  * Copyright(c) 2010-2012, Roo J Solutions Limited
19417  *
19418  * Licence LGPL
19419  *
19420  */
19421
19422 /**
19423  * @class Roo.form.ComboBoxArray
19424  * @extends Roo.form.TextField
19425  * A facebook style adder... for lists of email / people / countries  etc...
19426  * pick multiple items from a combo box, and shows each one.
19427  *
19428  *  Fred [x]  Brian [x]  [Pick another |v]
19429  *
19430  *
19431  *  For this to work: it needs various extra information
19432  *    - normal combo problay has
19433  *      name, hiddenName
19434  *    + displayField, valueField
19435  *
19436  *    For our purpose...
19437  *
19438  *
19439  *   If we change from 'extends' to wrapping...
19440  *   
19441  *  
19442  *
19443  
19444  
19445  * @constructor
19446  * Create a new ComboBoxArray.
19447  * @param {Object} config Configuration options
19448  */
19449  
19450
19451 Roo.form.ComboBoxArray = function(config)
19452 {
19453     this.addEvents({
19454         /**
19455          * @event beforeremove
19456          * Fires before remove the value from the list
19457              * @param {Roo.form.ComboBoxArray} _self This combo box array
19458              * @param {Roo.form.ComboBoxArray.Item} item removed item
19459              */
19460         'beforeremove' : true,
19461         /**
19462          * @event remove
19463          * Fires when remove the value from the list
19464              * @param {Roo.form.ComboBoxArray} _self This combo box array
19465              * @param {Roo.form.ComboBoxArray.Item} item removed item
19466              */
19467         'remove' : true
19468         
19469         
19470     });
19471     
19472     Roo.form.ComboBoxArray.superclass.constructor.call(this, config);
19473     
19474     this.items = new Roo.util.MixedCollection(false);
19475     
19476     // construct the child combo...
19477     
19478     
19479     
19480     
19481    
19482     
19483 }
19484
19485  
19486 Roo.extend(Roo.form.ComboBoxArray, Roo.form.TextField,
19487
19488     /**
19489      * @cfg {Roo.form.ComboBox} combo [required] The combo box that is wrapped
19490      */
19491     
19492     lastData : false,
19493     
19494     // behavies liek a hiddne field
19495     inputType:      'hidden',
19496     /**
19497      * @cfg {Number} width The width of the box that displays the selected element
19498      */ 
19499     width:          300,
19500
19501     
19502     
19503     /**
19504      * @cfg {String} name    The name of the visable items on this form (eg. titles not ids)
19505      */
19506     name : false,
19507     /**
19508      * @cfg {String} hiddenName    The hidden name of the field, often contains an comma seperated list of names
19509      */
19510     hiddenName : false,
19511       /**
19512      * @cfg {String} seperator    The value seperator normally ',' 
19513      */
19514     seperator : ',',
19515     
19516     // private the array of items that are displayed..
19517     items  : false,
19518     // private - the hidden field el.
19519     hiddenEl : false,
19520     // private - the filed el..
19521     el : false,
19522     
19523     //validateValue : function() { return true; }, // all values are ok!
19524     //onAddClick: function() { },
19525     
19526     onRender : function(ct, position) 
19527     {
19528         
19529         // create the standard hidden element
19530         //Roo.form.ComboBoxArray.superclass.onRender.call(this, ct, position);
19531         
19532         
19533         // give fake names to child combo;
19534         this.combo.hiddenName = this.hiddenName ? (this.hiddenName+'-subcombo') : this.hiddenName;
19535         this.combo.name = this.name ? (this.name+'-subcombo') : this.name;
19536         
19537         this.combo = Roo.factory(this.combo, Roo.form);
19538         this.combo.onRender(ct, position);
19539         if (typeof(this.combo.width) != 'undefined') {
19540             this.combo.onResize(this.combo.width,0);
19541         }
19542         
19543         this.combo.initEvents();
19544         
19545         // assigned so form know we need to do this..
19546         this.store          = this.combo.store;
19547         this.valueField     = this.combo.valueField;
19548         this.displayField   = this.combo.displayField ;
19549         
19550         
19551         this.combo.wrap.addClass('x-cbarray-grp');
19552         
19553         var cbwrap = this.combo.wrap.createChild(
19554             {tag: 'div', cls: 'x-cbarray-cb'},
19555             this.combo.el.dom
19556         );
19557         
19558              
19559         this.hiddenEl = this.combo.wrap.createChild({
19560             tag: 'input',  type:'hidden' , name: this.hiddenName, value : ''
19561         });
19562         this.el = this.combo.wrap.createChild({
19563             tag: 'input',  type:'hidden' , name: this.name, value : ''
19564         });
19565          //   this.el.dom.removeAttribute("name");
19566         
19567         
19568         this.outerWrap = this.combo.wrap;
19569         this.wrap = cbwrap;
19570         
19571         this.outerWrap.setWidth(this.width);
19572         this.outerWrap.dom.removeChild(this.el.dom);
19573         
19574         this.wrap.dom.appendChild(this.el.dom);
19575         this.outerWrap.dom.removeChild(this.combo.trigger.dom);
19576         this.combo.wrap.dom.appendChild(this.combo.trigger.dom);
19577         
19578         this.combo.trigger.setStyle('position','relative');
19579         this.combo.trigger.setStyle('left', '0px');
19580         this.combo.trigger.setStyle('top', '2px');
19581         
19582         this.combo.el.setStyle('vertical-align', 'text-bottom');
19583         
19584         //this.trigger.setStyle('vertical-align', 'top');
19585         
19586         // this should use the code from combo really... on('add' ....)
19587         if (this.adder) {
19588             
19589         
19590             this.adder = this.outerWrap.createChild(
19591                 {tag: 'img', src: Roo.BLANK_IMAGE_URL, cls: 'x-form-adder', style: 'margin-left:2px'});  
19592             var _t = this;
19593             this.adder.on('click', function(e) {
19594                 _t.fireEvent('adderclick', this, e);
19595             }, _t);
19596         }
19597         //var _t = this;
19598         //this.adder.on('click', this.onAddClick, _t);
19599         
19600         
19601         this.combo.on('select', function(cb, rec, ix) {
19602             this.addItem(rec.data);
19603             
19604             cb.setValue('');
19605             cb.el.dom.value = '';
19606             //cb.lastData = rec.data;
19607             // add to list
19608             
19609         }, this);
19610         
19611         
19612     },
19613     
19614     
19615     getName: function()
19616     {
19617         // returns hidden if it's set..
19618         if (!this.rendered) {return ''};
19619         return  this.hiddenName ? this.hiddenName : this.name;
19620         
19621     },
19622     
19623     
19624     onResize: function(w, h){
19625         
19626         return;
19627         // not sure if this is needed..
19628         //this.combo.onResize(w,h);
19629         
19630         if(typeof w != 'number'){
19631             // we do not handle it!?!?
19632             return;
19633         }
19634         var tw = this.combo.trigger.getWidth();
19635         tw += this.addicon ? this.addicon.getWidth() : 0;
19636         tw += this.editicon ? this.editicon.getWidth() : 0;
19637         var x = w - tw;
19638         this.combo.el.setWidth( this.combo.adjustWidth('input', x));
19639             
19640         this.combo.trigger.setStyle('left', '0px');
19641         
19642         if(this.list && this.listWidth === undefined){
19643             var lw = Math.max(x + this.combo.trigger.getWidth(), this.combo.minListWidth);
19644             this.list.setWidth(lw);
19645             this.innerList.setWidth(lw - this.list.getFrameWidth('lr'));
19646         }
19647         
19648     
19649         
19650     },
19651     
19652     addItem: function(rec)
19653     {
19654         var valueField = this.combo.valueField;
19655         var displayField = this.combo.displayField;
19656         
19657         if (this.items.indexOfKey(rec[valueField]) > -1) {
19658             //console.log("GOT " + rec.data.id);
19659             return;
19660         }
19661         
19662         var x = new Roo.form.ComboBoxArray.Item({
19663             //id : rec[this.idField],
19664             data : rec,
19665             displayField : displayField ,
19666             tipField : displayField ,
19667             cb : this
19668         });
19669         // use the 
19670         this.items.add(rec[valueField],x);
19671         // add it before the element..
19672         this.updateHiddenEl();
19673         x.render(this.outerWrap, this.wrap.dom);
19674         // add the image handler..
19675     },
19676     
19677     updateHiddenEl : function()
19678     {
19679         this.validate();
19680         if (!this.hiddenEl) {
19681             return;
19682         }
19683         var ar = [];
19684         var idField = this.combo.valueField;
19685         
19686         this.items.each(function(f) {
19687             ar.push(f.data[idField]);
19688         });
19689         this.hiddenEl.dom.value = ar.join(this.seperator);
19690         this.validate();
19691     },
19692     
19693     reset : function()
19694     {
19695         this.items.clear();
19696         
19697         Roo.each(this.outerWrap.select('.x-cbarray-item', true).elements, function(el){
19698            el.remove();
19699         });
19700         
19701         this.el.dom.value = '';
19702         if (this.hiddenEl) {
19703             this.hiddenEl.dom.value = '';
19704         }
19705         
19706     },
19707     getValue: function()
19708     {
19709         return this.hiddenEl ? this.hiddenEl.dom.value : '';
19710     },
19711     setValue: function(v) // not a valid action - must use addItems..
19712     {
19713         
19714         this.reset();
19715          
19716         if (this.store.isLocal && (typeof(v) == 'string')) {
19717             // then we can use the store to find the values..
19718             // comma seperated at present.. this needs to allow JSON based encoding..
19719             this.hiddenEl.value  = v;
19720             var v_ar = [];
19721             Roo.each(v.split(this.seperator), function(k) {
19722                 Roo.log("CHECK " + this.valueField + ',' + k);
19723                 var li = this.store.query(this.valueField, k);
19724                 if (!li.length) {
19725                     return;
19726                 }
19727                 var add = {};
19728                 add[this.valueField] = k;
19729                 add[this.displayField] = li.item(0).data[this.displayField];
19730                 
19731                 this.addItem(add);
19732             }, this) 
19733              
19734         }
19735         if (typeof(v) == 'object' ) {
19736             // then let's assume it's an array of objects..
19737             Roo.each(v, function(l) {
19738                 var add = l;
19739                 if (typeof(l) == 'string') {
19740                     add = {};
19741                     add[this.valueField] = l;
19742                     add[this.displayField] = l
19743                 }
19744                 this.addItem(add);
19745             }, this);
19746              
19747         }
19748         
19749         
19750     },
19751     setFromData: function(v)
19752     {
19753         // this recieves an object, if setValues is called.
19754         this.reset();
19755         this.el.dom.value = v[this.displayField];
19756         this.hiddenEl.dom.value = v[this.valueField];
19757         if (typeof(v[this.valueField]) != 'string' || !v[this.valueField].length) {
19758             return;
19759         }
19760         var kv = v[this.valueField];
19761         var dv = v[this.displayField];
19762         kv = typeof(kv) != 'string' ? '' : kv;
19763         dv = typeof(dv) != 'string' ? '' : dv;
19764         
19765         
19766         var keys = kv.split(this.seperator);
19767         var display = dv.split(this.seperator);
19768         for (var i = 0 ; i < keys.length; i++) {
19769             add = {};
19770             add[this.valueField] = keys[i];
19771             add[this.displayField] = display[i];
19772             this.addItem(add);
19773         }
19774       
19775         
19776     },
19777     
19778     /**
19779      * Validates the combox array value
19780      * @return {Boolean} True if the value is valid, else false
19781      */
19782     validate : function(){
19783         if(this.disabled || this.validateValue(this.processValue(this.getValue()))){
19784             this.clearInvalid();
19785             return true;
19786         }
19787         return false;
19788     },
19789     
19790     validateValue : function(value){
19791         return Roo.form.ComboBoxArray.superclass.validateValue.call(this, this.getValue());
19792         
19793     },
19794     
19795     /*@
19796      * overide
19797      * 
19798      */
19799     isDirty : function() {
19800         if(this.disabled) {
19801             return false;
19802         }
19803         
19804         try {
19805             var d = Roo.decode(String(this.originalValue));
19806         } catch (e) {
19807             return String(this.getValue()) !== String(this.originalValue);
19808         }
19809         
19810         var originalValue = [];
19811         
19812         for (var i = 0; i < d.length; i++){
19813             originalValue.push(d[i][this.valueField]);
19814         }
19815         
19816         return String(this.getValue()) !== String(originalValue.join(this.seperator));
19817         
19818     }
19819     
19820 });
19821
19822
19823
19824 /**
19825  * @class Roo.form.ComboBoxArray.Item
19826  * @extends Roo.BoxComponent
19827  * A selected item in the list
19828  *  Fred [x]  Brian [x]  [Pick another |v]
19829  * 
19830  * @constructor
19831  * Create a new item.
19832  * @param {Object} config Configuration options
19833  */
19834  
19835 Roo.form.ComboBoxArray.Item = function(config) {
19836     config.id = Roo.id();
19837     Roo.form.ComboBoxArray.Item.superclass.constructor.call(this, config);
19838 }
19839
19840 Roo.extend(Roo.form.ComboBoxArray.Item, Roo.BoxComponent, {
19841     data : {},
19842     cb: false,
19843     displayField : false,
19844     tipField : false,
19845     
19846     
19847     defaultAutoCreate : {
19848         tag: 'div',
19849         cls: 'x-cbarray-item',
19850         cn : [ 
19851             { tag: 'div' },
19852             {
19853                 tag: 'img',
19854                 width:16,
19855                 height : 16,
19856                 src : Roo.BLANK_IMAGE_URL ,
19857                 align: 'center'
19858             }
19859         ]
19860         
19861     },
19862     
19863  
19864     onRender : function(ct, position)
19865     {
19866         Roo.form.Field.superclass.onRender.call(this, ct, position);
19867         
19868         if(!this.el){
19869             var cfg = this.getAutoCreate();
19870             this.el = ct.createChild(cfg, position);
19871         }
19872         
19873         this.el.child('img').dom.setAttribute('src', Roo.BLANK_IMAGE_URL);
19874         
19875         this.el.child('div').dom.innerHTML = this.cb.renderer ? 
19876             this.cb.renderer(this.data) :
19877             String.format('{0}',this.data[this.displayField]);
19878         
19879             
19880         this.el.child('div').dom.setAttribute('qtip',
19881                         String.format('{0}',this.data[this.tipField])
19882         );
19883         
19884         this.el.child('img').on('click', this.remove, this);
19885         
19886     },
19887    
19888     remove : function()
19889     {
19890         if(this.cb.disabled){
19891             return;
19892         }
19893         
19894         if(false !== this.cb.fireEvent('beforeremove', this.cb, this)){
19895             this.cb.items.remove(this);
19896             this.el.child('img').un('click', this.remove, this);
19897             this.el.remove();
19898             this.cb.updateHiddenEl();
19899
19900             this.cb.fireEvent('remove', this.cb, this);
19901         }
19902         
19903     }
19904 });/*
19905  * RooJS Library 1.1.1
19906  * Copyright(c) 2008-2011  Alan Knowles
19907  *
19908  * License - LGPL
19909  */
19910  
19911
19912 /**
19913  * @class Roo.form.ComboNested
19914  * @extends Roo.form.ComboBox
19915  * A combobox for that allows selection of nested items in a list,
19916  * eg.
19917  *
19918  *  Book
19919  *    -> red
19920  *    -> green
19921  *  Table
19922  *    -> square
19923  *      ->red
19924  *      ->green
19925  *    -> rectangle
19926  *      ->green
19927  *      
19928  * 
19929  * @constructor
19930  * Create a new ComboNested
19931  * @param {Object} config Configuration options
19932  */
19933 Roo.form.ComboNested = function(config){
19934     Roo.form.ComboCheck.superclass.constructor.call(this, config);
19935     // should verify some data...
19936     // like
19937     // hiddenName = required..
19938     // displayField = required
19939     // valudField == required
19940     var req= [ 'hiddenName', 'displayField', 'valueField' ];
19941     var _t = this;
19942     Roo.each(req, function(e) {
19943         if ((typeof(_t[e]) == 'undefined' ) || !_t[e].length) {
19944             throw "Roo.form.ComboNested : missing value for: " + e;
19945         }
19946     });
19947      
19948     
19949 };
19950
19951 Roo.extend(Roo.form.ComboNested, Roo.form.ComboBox, {
19952    
19953     /*
19954      * @config {Number} max Number of columns to show
19955      */
19956     
19957     maxColumns : 3,
19958    
19959     list : null, // the outermost div..
19960     innerLists : null, // the
19961     views : null,
19962     stores : null,
19963     // private
19964     loadingChildren : false,
19965     
19966     onRender : function(ct, position)
19967     {
19968         Roo.form.ComboBox.superclass.onRender.call(this, ct, position); // skip parent call - got to above..
19969         
19970         if(this.hiddenName){
19971             this.hiddenField = this.el.insertSibling({tag:'input', type:'hidden', name: this.hiddenName, id:  (this.hiddenId||this.hiddenName)},
19972                     'before', true);
19973             this.hiddenField.value =
19974                 this.hiddenValue !== undefined ? this.hiddenValue :
19975                 this.value !== undefined ? this.value : '';
19976
19977             // prevent input submission
19978             this.el.dom.removeAttribute('name');
19979              
19980              
19981         }
19982         
19983         if(Roo.isGecko){
19984             this.el.dom.setAttribute('autocomplete', 'off');
19985         }
19986
19987         var cls = 'x-combo-list';
19988
19989         this.list = new Roo.Layer({
19990             shadow: this.shadow, cls: [cls, this.listClass].join(' '), constrain:false
19991         });
19992
19993         var lw = this.listWidth || Math.max(this.wrap.getWidth(), this.minListWidth);
19994         this.list.setWidth(lw);
19995         this.list.swallowEvent('mousewheel');
19996         this.assetHeight = 0;
19997
19998         if(this.title){
19999             this.header = this.list.createChild({cls:cls+'-hd', html: this.title});
20000             this.assetHeight += this.header.getHeight();
20001         }
20002         this.innerLists = [];
20003         this.views = [];
20004         this.stores = [];
20005         for (var i =0 ; i < this.maxColumns; i++) {
20006             this.onRenderList( cls, i);
20007         }
20008         
20009         // always needs footer, as we are going to have an 'OK' button.
20010         this.footer = this.list.createChild({cls:cls+'-ft'});
20011         this.pageTb = new Roo.Toolbar(this.footer);  
20012         var _this = this;
20013         this.pageTb.add(  {
20014             
20015             text: 'Done',
20016             handler: function()
20017             {
20018                 _this.collapse();
20019             }
20020         });
20021         
20022         if ( this.allowBlank && !this.disableClear) {
20023             
20024             this.pageTb.add(new Roo.Toolbar.Fill(), {
20025                 cls: 'x-btn-icon x-btn-clear',
20026                 text: '&#160;',
20027                 handler: function()
20028                 {
20029                     _this.collapse();
20030                     _this.clearValue();
20031                     _this.onSelect(false, -1);
20032                 }
20033             });
20034         }
20035         if (this.footer) {
20036             this.assetHeight += this.footer.getHeight();
20037         }
20038         
20039     },
20040     onRenderList : function (  cls, i)
20041     {
20042         
20043         var lw = Math.floor(
20044                 ((this.listWidth * this.maxColumns || Math.max(this.wrap.getWidth(), this.minListWidth)) - this.list.getFrameWidth('lr')) / this.maxColumns
20045         );
20046         
20047         this.list.setWidth(lw); // default to '1'
20048
20049         var il = this.innerLists[i] = this.list.createChild({cls:cls+'-inner'});
20050         //il.on('mouseover', this.onViewOver, this, { list:  i });
20051         //il.on('mousemove', this.onViewMove, this, { list:  i });
20052         il.setWidth(lw);
20053         il.setStyle({ 'overflow-x' : 'hidden'});
20054
20055         if(!this.tpl){
20056             this.tpl = new Roo.Template({
20057                 html :  '<div class="'+cls+'-item '+cls+'-item-{cn:this.isEmpty}">{' + this.displayField + '}</div>',
20058                 isEmpty: function (value, allValues) {
20059                     //Roo.log(value);
20060                     var dl = typeof(value.data) != 'undefined' ? value.data.length : value.length; ///json is a nested response..
20061                     return dl ? 'has-children' : 'no-children'
20062                 }
20063             });
20064         }
20065         
20066         var store  = this.store;
20067         if (i > 0) {
20068             store  = new Roo.data.SimpleStore({
20069                 //fields : this.store.reader.meta.fields,
20070                 reader : this.store.reader,
20071                 data : [ ]
20072             });
20073         }
20074         this.stores[i]  = store;
20075                   
20076         var view = this.views[i] = new Roo.View(
20077             il,
20078             this.tpl,
20079             {
20080                 singleSelect:true,
20081                 store: store,
20082                 selectedClass: this.selectedClass
20083             }
20084         );
20085         view.getEl().setWidth(lw);
20086         view.getEl().setStyle({
20087             position: i < 1 ? 'relative' : 'absolute',
20088             top: 0,
20089             left: (i * lw ) + 'px',
20090             display : i > 0 ? 'none' : 'block'
20091         });
20092         view.on('selectionchange', this.onSelectChange.createDelegate(this, {list : i }, true));
20093         view.on('dblclick', this.onDoubleClick.createDelegate(this, {list : i }, true));
20094         //view.on('click', this.onViewClick, this, { list : i });
20095
20096         store.on('beforeload', this.onBeforeLoad, this);
20097         store.on('load',  this.onLoad, this, { list  : i});
20098         store.on('loadexception', this.onLoadException, this);
20099
20100         // hide the other vies..
20101         
20102         
20103         
20104     },
20105       
20106     restrictHeight : function()
20107     {
20108         var mh = 0;
20109         Roo.each(this.innerLists, function(il,i) {
20110             var el = this.views[i].getEl();
20111             el.dom.style.height = '';
20112             var inner = el.dom;
20113             var h = Math.max(il.clientHeight, il.offsetHeight, il.scrollHeight);
20114             // only adjust heights on other ones..
20115             mh = Math.max(h, mh);
20116             if (i < 1) {
20117                 
20118                 el.setHeight(h < this.maxHeight ? 'auto' : this.maxHeight);
20119                 il.setHeight(h < this.maxHeight ? 'auto' : this.maxHeight);
20120                
20121             }
20122             
20123             
20124         }, this);
20125         
20126         this.list.beginUpdate();
20127         this.list.setHeight(mh+this.list.getFrameWidth('tb')+this.assetHeight);
20128         this.list.alignTo(this.el, this.listAlign);
20129         this.list.endUpdate();
20130         
20131     },
20132      
20133     
20134     // -- store handlers..
20135     // private
20136     onBeforeLoad : function()
20137     {
20138         if(!this.hasFocus){
20139             return;
20140         }
20141         this.innerLists[0].update(this.loadingText ?
20142                '<div class="loading-indicator">'+this.loadingText+'</div>' : '');
20143         this.restrictHeight();
20144         this.selectedIndex = -1;
20145     },
20146     // private
20147     onLoad : function(a,b,c,d)
20148     {
20149         if (!this.loadingChildren) {
20150             // then we are loading the top level. - hide the children
20151             for (var i = 1;i < this.views.length; i++) {
20152                 this.views[i].getEl().setStyle({ display : 'none' });
20153             }
20154             var lw = Math.floor(
20155                 ((this.listWidth * this.maxColumns || Math.max(this.wrap.getWidth(), this.minListWidth)) - this.list.getFrameWidth('lr')) / this.maxColumns
20156             );
20157         
20158              this.list.setWidth(lw); // default to '1'
20159
20160             
20161         }
20162         if(!this.hasFocus){
20163             return;
20164         }
20165         
20166         if(this.store.getCount() > 0) {
20167             this.expand();
20168             this.restrictHeight();   
20169         } else {
20170             this.onEmptyResults();
20171         }
20172         
20173         if (!this.loadingChildren) {
20174             this.selectActive();
20175         }
20176         /*
20177         this.stores[1].loadData([]);
20178         this.stores[2].loadData([]);
20179         this.views
20180         */    
20181     
20182         //this.el.focus();
20183     },
20184     
20185     
20186     // private
20187     onLoadException : function()
20188     {
20189         this.collapse();
20190         Roo.log(this.store.reader.jsonData);
20191         if (this.store && typeof(this.store.reader.jsonData.errorMsg) != 'undefined') {
20192             Roo.MessageBox.alert("Error loading",this.store.reader.jsonData.errorMsg);
20193         }
20194         
20195         
20196     },
20197     // no cleaning of leading spaces on blur here.
20198     cleanLeadingSpace : function(e) { },
20199     
20200
20201     onSelectChange : function (view, sels, opts )
20202     {
20203         var ix = view.getSelectedIndexes();
20204          
20205         if (opts.list > this.maxColumns - 2) {
20206             if (view.store.getCount()<  1) {
20207                 this.views[opts.list ].getEl().setStyle({ display :   'none' });
20208
20209             } else  {
20210                 if (ix.length) {
20211                     // used to clear ?? but if we are loading unselected 
20212                     this.setFromData(view.store.getAt(ix[0]).data);
20213                 }
20214                 
20215             }
20216             
20217             return;
20218         }
20219         
20220         if (!ix.length) {
20221             // this get's fired when trigger opens..
20222            // this.setFromData({});
20223             var str = this.stores[opts.list+1];
20224             str.data.clear(); // removeall wihtout the fire events..
20225             return;
20226         }
20227         
20228         var rec = view.store.getAt(ix[0]);
20229          
20230         this.setFromData(rec.data);
20231         this.fireEvent('select', this, rec, ix[0]);
20232         
20233         var lw = Math.floor(
20234              (
20235                 (this.listWidth * this.maxColumns || Math.max(this.wrap.getWidth(), this.minListWidth)) - this.list.getFrameWidth('lr')
20236              ) / this.maxColumns
20237         );
20238         this.loadingChildren = true;
20239         this.stores[opts.list+1].loadDataFromChildren( rec );
20240         this.loadingChildren = false;
20241         var dl = this.stores[opts.list+1]. getTotalCount();
20242         
20243         this.views[opts.list+1].getEl().setHeight( this.innerLists[0].getHeight());
20244         
20245         this.views[opts.list+1].getEl().setStyle({ display : dl ? 'block' : 'none' });
20246         for (var i = opts.list+2; i < this.views.length;i++) {
20247             this.views[i].getEl().setStyle({ display : 'none' });
20248         }
20249         
20250         this.innerLists[opts.list+1].setHeight( this.innerLists[0].getHeight());
20251         this.list.setWidth(lw * (opts.list + (dl ? 2 : 1)));
20252         
20253         if (this.isLoading) {
20254            // this.selectActive(opts.list);
20255         }
20256          
20257     },
20258     
20259     
20260     
20261     
20262     onDoubleClick : function()
20263     {
20264         this.collapse(); //??
20265     },
20266     
20267      
20268     
20269     
20270     
20271     // private
20272     recordToStack : function(store, prop, value, stack)
20273     {
20274         var cstore = new Roo.data.SimpleStore({
20275             //fields : this.store.reader.meta.fields, // we need array reader.. for
20276             reader : this.store.reader,
20277             data : [ ]
20278         });
20279         var _this = this;
20280         var record  = false;
20281         var srec = false;
20282         if(store.getCount() < 1){
20283             return false;
20284         }
20285         store.each(function(r){
20286             if(r.data[prop] == value){
20287                 record = r;
20288             srec = r;
20289                 return false;
20290             }
20291             if (r.data.cn && r.data.cn.length) {
20292                 cstore.loadDataFromChildren( r);
20293                 var cret = _this.recordToStack(cstore, prop, value, stack);
20294                 if (cret !== false) {
20295                     record = cret;
20296                     srec = r;
20297                     return false;
20298                 }
20299             }
20300              
20301             return true;
20302         });
20303         if (record == false) {
20304             return false
20305         }
20306         stack.unshift(srec);
20307         return record;
20308     },
20309     
20310     /*
20311      * find the stack of stores that match our value.
20312      *
20313      * 
20314      */
20315     
20316     selectActive : function ()
20317     {
20318         // if store is not loaded, then we will need to wait for that to happen first.
20319         var stack = [];
20320         this.recordToStack(this.store, this.valueField, this.getValue(), stack);
20321         for (var i = 0; i < stack.length; i++ ) {
20322             this.views[i].select(stack[i].store.indexOf(stack[i]), false, false );
20323         }
20324         
20325     }
20326         
20327          
20328     
20329     
20330     
20331     
20332 });/*
20333  * Based on:
20334  * Ext JS Library 1.1.1
20335  * Copyright(c) 2006-2007, Ext JS, LLC.
20336  *
20337  * Originally Released Under LGPL - original licence link has changed is not relivant.
20338  *
20339  * Fork - LGPL
20340  * <script type="text/javascript">
20341  */
20342 /**
20343  * @class Roo.form.Checkbox
20344  * @extends Roo.form.Field
20345  * Single checkbox field.  Can be used as a direct replacement for traditional checkbox fields.
20346  * @constructor
20347  * Creates a new Checkbox
20348  * @param {Object} config Configuration options
20349  */
20350 Roo.form.Checkbox = function(config){
20351     Roo.form.Checkbox.superclass.constructor.call(this, config);
20352     this.addEvents({
20353         /**
20354          * @event check
20355          * Fires when the checkbox is checked or unchecked.
20356              * @param {Roo.form.Checkbox} this This checkbox
20357              * @param {Boolean} checked The new checked value
20358              */
20359         check : true
20360     });
20361 };
20362
20363 Roo.extend(Roo.form.Checkbox, Roo.form.Field,  {
20364     /**
20365      * @cfg {String} focusClass The CSS class to use when the checkbox receives focus (defaults to undefined)
20366      */
20367     focusClass : undefined,
20368     /**
20369      * @cfg {String} fieldClass The default CSS class for the checkbox (defaults to "x-form-field")
20370      */
20371     fieldClass: "x-form-field",
20372     /**
20373      * @cfg {Boolean} checked True if the the checkbox should render already checked (defaults to false)
20374      */
20375     checked: false,
20376     /**
20377      * @cfg {String/Object} autoCreate A DomHelper element spec, or true for a default element spec (defaults to
20378      * {tag: "input", type: "checkbox", autocomplete: "off"})
20379      */
20380     defaultAutoCreate : { tag: "input", type: 'hidden', autocomplete: "off"},
20381     /**
20382      * @cfg {String} boxLabel The text that appears beside the checkbox
20383      */
20384     boxLabel : "",
20385     /**
20386      * @cfg {String} inputValue The value that should go into the generated input element's value attribute
20387      */  
20388     inputValue : '1',
20389     /**
20390      * @cfg {String} valueOff The value that should go into the generated input element's value when unchecked.
20391      */
20392      valueOff: '0', // value when not checked..
20393
20394     actionMode : 'viewEl', 
20395     //
20396     // private
20397     itemCls : 'x-menu-check-item x-form-item',
20398     groupClass : 'x-menu-group-item',
20399     inputType : 'hidden',
20400     
20401     
20402     inSetChecked: false, // check that we are not calling self...
20403     
20404     inputElement: false, // real input element?
20405     basedOn: false, // ????
20406     
20407     isFormField: true, // not sure where this is needed!!!!
20408
20409     onResize : function(){
20410         Roo.form.Checkbox.superclass.onResize.apply(this, arguments);
20411         if(!this.boxLabel){
20412             this.el.alignTo(this.wrap, 'c-c');
20413         }
20414     },
20415
20416     initEvents : function(){
20417         Roo.form.Checkbox.superclass.initEvents.call(this);
20418         this.el.on("click", this.onClick,  this);
20419         this.el.on("change", this.onClick,  this);
20420     },
20421
20422
20423     getResizeEl : function(){
20424         return this.wrap;
20425     },
20426
20427     getPositionEl : function(){
20428         return this.wrap;
20429     },
20430
20431     // private
20432     onRender : function(ct, position){
20433         Roo.form.Checkbox.superclass.onRender.call(this, ct, position);
20434         /*
20435         if(this.inputValue !== undefined){
20436             this.el.dom.value = this.inputValue;
20437         }
20438         */
20439         //this.wrap = this.el.wrap({cls: "x-form-check-wrap"});
20440         this.wrap = this.el.wrap({cls: 'x-menu-check-item '});
20441         var viewEl = this.wrap.createChild({ 
20442             tag: 'img', cls: 'x-menu-item-icon', style: 'margin: 0px;' ,src : Roo.BLANK_IMAGE_URL });
20443         this.viewEl = viewEl;   
20444         this.wrap.on('click', this.onClick,  this); 
20445         
20446         this.el.on('DOMAttrModified', this.setFromHidden,  this); //ff
20447         this.el.on('propertychange', this.setFromHidden,  this);  //ie
20448         
20449         
20450         
20451         if(this.boxLabel){
20452             this.wrap.createChild({tag: 'label', htmlFor: this.el.id, cls: 'x-form-cb-label', html: this.boxLabel});
20453         //    viewEl.on('click', this.onClick,  this); 
20454         }
20455         //if(this.checked){
20456             this.setChecked(this.checked);
20457         //}else{
20458             //this.checked = this.el.dom;
20459         //}
20460
20461     },
20462
20463     // private
20464     initValue : Roo.emptyFn,
20465
20466     /**
20467      * Returns the checked state of the checkbox.
20468      * @return {Boolean} True if checked, else false
20469      */
20470     getValue : function(){
20471         if(this.el){
20472             return String(this.el.dom.value) == String(this.inputValue ) ? this.inputValue : this.valueOff;
20473         }
20474         return this.valueOff;
20475         
20476     },
20477
20478         // private
20479     onClick : function(){ 
20480         if (this.disabled) {
20481             return;
20482         }
20483         this.setChecked(!this.checked);
20484
20485         //if(this.el.dom.checked != this.checked){
20486         //    this.setValue(this.el.dom.checked);
20487        // }
20488     },
20489
20490     /**
20491      * Sets the checked state of the checkbox.
20492      * On is always based on a string comparison between inputValue and the param.
20493      * @param {Boolean/String} value - the value to set 
20494      * @param {Boolean/String} suppressEvent - whether to suppress the checkchange event.
20495      */
20496     setValue : function(v,suppressEvent){
20497         
20498         
20499         //this.checked = (v === true || v === 'true' || v == '1' || String(v).toLowerCase() == 'on');
20500         //if(this.el && this.el.dom){
20501         //    this.el.dom.checked = this.checked;
20502         //    this.el.dom.defaultChecked = this.checked;
20503         //}
20504         this.setChecked(String(v) === String(this.inputValue), suppressEvent);
20505         //this.fireEvent("check", this, this.checked);
20506     },
20507     // private..
20508     setChecked : function(state,suppressEvent)
20509     {
20510         if (this.inSetChecked) {
20511             this.checked = state;
20512             return;
20513         }
20514         
20515     
20516         if(this.wrap){
20517             this.wrap[state ? 'addClass' : 'removeClass']('x-menu-item-checked');
20518         }
20519         this.checked = state;
20520         if(suppressEvent !== true){
20521             this.fireEvent('check', this, state);
20522         }
20523         this.inSetChecked = true;
20524         this.el.dom.value = state ? this.inputValue : this.valueOff;
20525         this.inSetChecked = false;
20526         
20527     },
20528     // handle setting of hidden value by some other method!!?!?
20529     setFromHidden: function()
20530     {
20531         if(!this.el){
20532             return;
20533         }
20534         //console.log("SET FROM HIDDEN");
20535         //alert('setFrom hidden');
20536         this.setValue(this.el.dom.value);
20537     },
20538     
20539     onDestroy : function()
20540     {
20541         if(this.viewEl){
20542             Roo.get(this.viewEl).remove();
20543         }
20544          
20545         Roo.form.Checkbox.superclass.onDestroy.call(this);
20546     },
20547     
20548     setBoxLabel : function(str)
20549     {
20550         this.wrap.select('.x-form-cb-label', true).first().dom.innerHTML = str;
20551     }
20552
20553 });/*
20554  * Based on:
20555  * Ext JS Library 1.1.1
20556  * Copyright(c) 2006-2007, Ext JS, LLC.
20557  *
20558  * Originally Released Under LGPL - original licence link has changed is not relivant.
20559  *
20560  * Fork - LGPL
20561  * <script type="text/javascript">
20562  */
20563  
20564 /**
20565  * @class Roo.form.Radio
20566  * @extends Roo.form.Checkbox
20567  * Single radio field.  Same as Checkbox, but provided as a convenience for automatically setting the input type.
20568  * Radio grouping is handled automatically by the browser if you give each radio in a group the same name.
20569  * @constructor
20570  * Creates a new Radio
20571  * @param {Object} config Configuration options
20572  */
20573 Roo.form.Radio = function(){
20574     Roo.form.Radio.superclass.constructor.apply(this, arguments);
20575 };
20576 Roo.extend(Roo.form.Radio, Roo.form.Checkbox, {
20577     inputType: 'radio',
20578
20579     /**
20580      * If this radio is part of a group, it will return the selected value
20581      * @return {String}
20582      */
20583     getGroupValue : function(){
20584         return this.el.up('form').child('input[name='+this.el.dom.name+']:checked', true).value;
20585     },
20586     
20587     
20588     onRender : function(ct, position){
20589         Roo.form.Checkbox.superclass.onRender.call(this, ct, position);
20590         
20591         if(this.inputValue !== undefined){
20592             this.el.dom.value = this.inputValue;
20593         }
20594          
20595         this.wrap = this.el.wrap({cls: "x-form-check-wrap"});
20596         //this.wrap = this.el.wrap({cls: 'x-menu-check-item '});
20597         //var viewEl = this.wrap.createChild({ 
20598         //    tag: 'img', cls: 'x-menu-item-icon', style: 'margin: 0px;' ,src : Roo.BLANK_IMAGE_URL });
20599         //this.viewEl = viewEl;   
20600         //this.wrap.on('click', this.onClick,  this); 
20601         
20602         //this.el.on('DOMAttrModified', this.setFromHidden,  this); //ff
20603         //this.el.on('propertychange', this.setFromHidden,  this);  //ie
20604         
20605         
20606         
20607         if(this.boxLabel){
20608             this.wrap.createChild({tag: 'label', htmlFor: this.el.id, cls: 'x-form-cb-label', html: this.boxLabel});
20609         //    viewEl.on('click', this.onClick,  this); 
20610         }
20611          if(this.checked){
20612             this.el.dom.checked =   'checked' ;
20613         }
20614          
20615     } 
20616     
20617     
20618 });Roo.rtf = {}; // namespace
20619 Roo.rtf.Hex = function(hex)
20620 {
20621     this.hexstr = hex;
20622 };
20623 Roo.rtf.Paragraph = function(opts)
20624 {
20625     this.content = []; ///??? is that used?
20626 };Roo.rtf.Span = function(opts)
20627 {
20628     this.value = opts.value;
20629 };
20630
20631 Roo.rtf.Group = function(parent)
20632 {
20633     // we dont want to acutally store parent - it will make debug a nightmare..
20634     this.content = [];
20635     this.cn  = [];
20636      
20637        
20638     
20639 };
20640
20641 Roo.rtf.Group.prototype = {
20642     ignorable : false,
20643     content: false,
20644     cn: false,
20645     addContent : function(node) {
20646         // could set styles...
20647         this.content.push(node);
20648     },
20649     addChild : function(cn)
20650     {
20651         this.cn.push(cn);
20652     },
20653     // only for images really...
20654     toDataURL : function()
20655     {
20656         var mimetype = false;
20657         switch(true) {
20658             case this.content.filter(function(a) { return a.value == 'pngblip' } ).length > 0: 
20659                 mimetype = "image/png";
20660                 break;
20661              case this.content.filter(function(a) { return a.value == 'jpegblip' } ).length > 0:
20662                 mimetype = "image/jpeg";
20663                 break;
20664             default :
20665                 return 'about:blank'; // ?? error?
20666         }
20667         
20668         
20669         var hexstring = this.content[this.content.length-1].value;
20670         
20671         return 'data:' + mimetype + ';base64,' + btoa(hexstring.match(/\w{2}/g).map(function(a) {
20672             return String.fromCharCode(parseInt(a, 16));
20673         }).join(""));
20674     }
20675     
20676 };
20677 // this looks like it's normally the {rtf{ .... }}
20678 Roo.rtf.Document = function()
20679 {
20680     // we dont want to acutally store parent - it will make debug a nightmare..
20681     this.rtlch  = [];
20682     this.content = [];
20683     this.cn = [];
20684     
20685 };
20686 Roo.extend(Roo.rtf.Document, Roo.rtf.Group, { 
20687     addChild : function(cn)
20688     {
20689         this.cn.push(cn);
20690         switch(cn.type) {
20691             case 'rtlch': // most content seems to be inside this??
20692             case 'listtext':
20693             case 'shpinst':
20694                 this.rtlch.push(cn);
20695                 return;
20696             default:
20697                 this[cn.type] = cn;
20698         }
20699         
20700     },
20701     
20702     getElementsByType : function(type)
20703     {
20704         var ret =  [];
20705         this._getElementsByType(type, ret, this.cn, 'rtf');
20706         return ret;
20707     },
20708     _getElementsByType : function (type, ret, search_array, path)
20709     {
20710         search_array.forEach(function(n,i) {
20711             if (n.type == type) {
20712                 n.path = path + '/' + n.type + ':' + i;
20713                 ret.push(n);
20714             }
20715             if (n.cn.length > 0) {
20716                 this._getElementsByType(type, ret, n.cn, path + '/' + n.type+':'+i);
20717             }
20718         },this);
20719     }
20720     
20721 });
20722  
20723 Roo.rtf.Ctrl = function(opts)
20724 {
20725     this.value = opts.value;
20726     this.param = opts.param;
20727 };
20728 /**
20729  *
20730  *
20731  * based on this https://github.com/iarna/rtf-parser
20732  * it's really only designed to extract pict from pasted RTF 
20733  *
20734  * usage:
20735  *
20736  *  var images = new Roo.rtf.Parser().parse(a_string).filter(function(g) { return g.type == 'pict'; });
20737  *  
20738  *
20739  */
20740
20741  
20742
20743
20744
20745 Roo.rtf.Parser = function(text) {
20746     //super({objectMode: true})
20747     this.text = '';
20748     this.parserState = this.parseText;
20749     
20750     // these are for interpeter...
20751     this.doc = {};
20752     ///this.parserState = this.parseTop
20753     this.groupStack = [];
20754     this.hexStore = [];
20755     this.doc = false;
20756     
20757     this.groups = []; // where we put the return.
20758     
20759     for (var ii = 0; ii < text.length; ++ii) {
20760         ++this.cpos;
20761         
20762         if (text[ii] === '\n') {
20763             ++this.row;
20764             this.col = 1;
20765         } else {
20766             ++this.col;
20767         }
20768         this.parserState(text[ii]);
20769     }
20770     
20771     
20772     
20773 };
20774 Roo.rtf.Parser.prototype = {
20775     text : '', // string being parsed..
20776     controlWord : '',
20777     controlWordParam :  '',
20778     hexChar : '',
20779     doc : false,
20780     group: false,
20781     groupStack : false,
20782     hexStore : false,
20783     
20784     
20785     cpos : 0, 
20786     row : 1, // reportin?
20787     col : 1, //
20788
20789      
20790     push : function (el)
20791     {
20792         var m = 'cmd'+ el.type;
20793         if (typeof(this[m]) == 'undefined') {
20794             Roo.log('invalid cmd:' + el.type);
20795             return;
20796         }
20797         this[m](el);
20798         //Roo.log(el);
20799     },
20800     flushHexStore : function()
20801     {
20802         if (this.hexStore.length < 1) {
20803             return;
20804         }
20805         var hexstr = this.hexStore.map(
20806             function(cmd) {
20807                 return cmd.value;
20808         }).join('');
20809         
20810         this.group.addContent( new Roo.rtf.Hex( hexstr ));
20811               
20812             
20813         this.hexStore.splice(0)
20814         
20815     },
20816     
20817     cmdgroupstart : function()
20818     {
20819         this.flushHexStore();
20820         if (this.group) {
20821             this.groupStack.push(this.group);
20822         }
20823          // parent..
20824         if (this.doc === false) {
20825             this.group = this.doc = new Roo.rtf.Document();
20826             return;
20827             
20828         }
20829         this.group = new Roo.rtf.Group(this.group);
20830     },
20831     cmdignorable : function()
20832     {
20833         this.flushHexStore();
20834         this.group.ignorable = true;
20835     },
20836     cmdendparagraph : function()
20837     {
20838         this.flushHexStore();
20839         this.group.addContent(new Roo.rtf.Paragraph());
20840     },
20841     cmdgroupend : function ()
20842     {
20843         this.flushHexStore();
20844         var endingGroup = this.group;
20845         
20846         
20847         this.group = this.groupStack.pop();
20848         if (this.group) {
20849             this.group.addChild(endingGroup);
20850         }
20851         
20852         
20853         
20854         var doc = this.group || this.doc;
20855         //if (endingGroup instanceof FontTable) {
20856         //  doc.fonts = endingGroup.table
20857         //} else if (endingGroup instanceof ColorTable) {
20858         //  doc.colors = endingGroup.table
20859         //} else if (endingGroup !== this.doc && !endingGroup.get('ignorable')) {
20860         if (endingGroup.ignorable === false) {
20861             //code
20862             this.groups.push(endingGroup);
20863            // Roo.log( endingGroup );
20864         }
20865             //Roo.each(endingGroup.content, function(item)) {
20866             //    doc.addContent(item);
20867             //}
20868             //process.emit('debug', 'GROUP END', endingGroup.type, endingGroup.get('ignorable'))
20869         //}
20870     },
20871     cmdtext : function (cmd)
20872     {
20873         this.flushHexStore();
20874         if (!this.group) { // an RTF fragment, missing the {\rtf1 header
20875             //this.group = this.doc
20876             return;  // we really don't care about stray text...
20877         }
20878         this.group.addContent(new Roo.rtf.Span(cmd));
20879     },
20880     cmdcontrolword : function (cmd)
20881     {
20882         this.flushHexStore();
20883         if (!this.group.type) {
20884             this.group.type = cmd.value;
20885             return;
20886         }
20887         this.group.addContent(new Roo.rtf.Ctrl(cmd));
20888         // we actually don't care about ctrl words...
20889         return ;
20890         /*
20891         var method = 'ctrl$' + cmd.value.replace(/-(.)/g, (_, char) => char.toUpperCase())
20892         if (this[method]) {
20893             this[method](cmd.param)
20894         } else {
20895             if (!this.group.get('ignorable')) process.emit('debug', method, cmd.param)
20896         }
20897         */
20898     },
20899     cmdhexchar : function(cmd) {
20900         this.hexStore.push(cmd);
20901     },
20902     cmderror : function(cmd) {
20903         throw new Exception (cmd.value);
20904     },
20905     
20906     /*
20907       _flush (done) {
20908         if (this.text !== '\u0000') this.emitText()
20909         done()
20910       }
20911       */
20912       
20913       
20914     parseText : function(c)
20915     {
20916         if (c === '\\') {
20917             this.parserState = this.parseEscapes;
20918         } else if (c === '{') {
20919             this.emitStartGroup();
20920         } else if (c === '}') {
20921             this.emitEndGroup();
20922         } else if (c === '\x0A' || c === '\x0D') {
20923             // cr/lf are noise chars
20924         } else {
20925             this.text += c;
20926         }
20927     },
20928     
20929     parseEscapes: function (c)
20930     {
20931         if (c === '\\' || c === '{' || c === '}') {
20932             this.text += c;
20933             this.parserState = this.parseText;
20934         } else {
20935             this.parserState = this.parseControlSymbol;
20936             this.parseControlSymbol(c);
20937         }
20938     },
20939     parseControlSymbol: function(c)
20940     {
20941         if (c === '~') {
20942             this.text += '\u00a0'; // nbsp
20943             this.parserState = this.parseText
20944         } else if (c === '-') {
20945              this.text += '\u00ad'; // soft hyphen
20946         } else if (c === '_') {
20947             this.text += '\u2011'; // non-breaking hyphen
20948         } else if (c === '*') {
20949             this.emitIgnorable();
20950             this.parserState = this.parseText;
20951         } else if (c === "'") {
20952             this.parserState = this.parseHexChar;
20953         } else if (c === '|') { // formula cacter
20954             this.emitFormula();
20955             this.parserState = this.parseText;
20956         } else if (c === ':') { // subentry in an index entry
20957             this.emitIndexSubEntry();
20958             this.parserState = this.parseText;
20959         } else if (c === '\x0a') {
20960             this.emitEndParagraph();
20961             this.parserState = this.parseText;
20962         } else if (c === '\x0d') {
20963             this.emitEndParagraph();
20964             this.parserState = this.parseText;
20965         } else {
20966             this.parserState = this.parseControlWord;
20967             this.parseControlWord(c);
20968         }
20969     },
20970     parseHexChar: function (c)
20971     {
20972         if (/^[A-Fa-f0-9]$/.test(c)) {
20973             this.hexChar += c;
20974             if (this.hexChar.length >= 2) {
20975               this.emitHexChar();
20976               this.parserState = this.parseText;
20977             }
20978             return;
20979         }
20980         this.emitError("Invalid character \"" + c + "\" in hex literal.");
20981         this.parserState = this.parseText;
20982         
20983     },
20984     parseControlWord : function(c)
20985     {
20986         if (c === ' ') {
20987             this.emitControlWord();
20988             this.parserState = this.parseText;
20989         } else if (/^[-\d]$/.test(c)) {
20990             this.parserState = this.parseControlWordParam;
20991             this.controlWordParam += c;
20992         } else if (/^[A-Za-z]$/.test(c)) {
20993           this.controlWord += c;
20994         } else {
20995           this.emitControlWord();
20996           this.parserState = this.parseText;
20997           this.parseText(c);
20998         }
20999     },
21000     parseControlWordParam : function (c) {
21001         if (/^\d$/.test(c)) {
21002           this.controlWordParam += c;
21003         } else if (c === ' ') {
21004           this.emitControlWord();
21005           this.parserState = this.parseText;
21006         } else {
21007           this.emitControlWord();
21008           this.parserState = this.parseText;
21009           this.parseText(c);
21010         }
21011     },
21012     
21013     
21014     
21015     
21016     emitText : function () {
21017         if (this.text === '') {
21018             return;
21019         }
21020         this.push({
21021             type: 'text',
21022             value: this.text,
21023             pos: this.cpos,
21024             row: this.row,
21025             col: this.col
21026         });
21027         this.text = ''
21028     },
21029     emitControlWord : function ()
21030     {
21031         this.emitText();
21032         if (this.controlWord === '') {
21033             this.emitError('empty control word');
21034         } else {
21035             this.push({
21036                   type: 'controlword',
21037                   value: this.controlWord,
21038                   param: this.controlWordParam !== '' && Number(this.controlWordParam),
21039                   pos: this.cpos,
21040                   row: this.row,
21041                   col: this.col
21042             });
21043         }
21044         this.controlWord = '';
21045         this.controlWordParam = '';
21046     },
21047     emitStartGroup : function ()
21048     {
21049         this.emitText();
21050         this.push({
21051             type: 'groupstart',
21052             pos: this.cpos,
21053             row: this.row,
21054             col: this.col
21055         });
21056     },
21057     emitEndGroup : function ()
21058     {
21059         this.emitText();
21060         this.push({
21061             type: 'groupend',
21062             pos: this.cpos,
21063             row: this.row,
21064             col: this.col
21065         });
21066     },
21067     emitIgnorable : function ()
21068     {
21069         this.emitText();
21070         this.push({
21071             type: 'ignorable',
21072             pos: this.cpos,
21073             row: this.row,
21074             col: this.col
21075         });
21076     },
21077     emitHexChar : function ()
21078     {
21079         this.emitText();
21080         this.push({
21081             type: 'hexchar',
21082             value: this.hexChar,
21083             pos: this.cpos,
21084             row: this.row,
21085             col: this.col
21086         });
21087         this.hexChar = ''
21088     },
21089     emitError : function (message)
21090     {
21091       this.emitText();
21092       this.push({
21093             type: 'error',
21094             value: message,
21095             row: this.row,
21096             col: this.col,
21097             char: this.cpos //,
21098             //stack: new Error().stack
21099         });
21100     },
21101     emitEndParagraph : function () {
21102         this.emitText();
21103         this.push({
21104             type: 'endparagraph',
21105             pos: this.cpos,
21106             row: this.row,
21107             col: this.col
21108         });
21109     }
21110      
21111 } ;
21112 Roo.htmleditor = {};
21113  
21114 /**
21115  * @class Roo.htmleditor.Filter
21116  * Base Class for filtering htmleditor stuff. - do not use this directly - extend it.
21117  * @cfg {DomElement} node The node to iterate and filter
21118  * @cfg {boolean|String|Array} tag Tags to replace 
21119  * @constructor
21120  * Create a new Filter.
21121  * @param {Object} config Configuration options
21122  */
21123
21124
21125
21126 Roo.htmleditor.Filter = function(cfg) {
21127     Roo.apply(this.cfg);
21128     // this does not actually call walk as it's really just a abstract class
21129 }
21130
21131
21132 Roo.htmleditor.Filter.prototype = {
21133     
21134     node: false,
21135     
21136     tag: false,
21137
21138     // overrride to do replace comments.
21139     replaceComment : false,
21140     
21141     // overrride to do replace or do stuff with tags..
21142     replaceTag : false,
21143     
21144     walk : function(dom)
21145     {
21146         Roo.each( Array.from(dom.childNodes), function( e ) {
21147             switch(true) {
21148                 
21149                 case e.nodeType == 8 &&  this.replaceComment  !== false: // comment
21150                     this.replaceComment(e);
21151                     return;
21152                 
21153                 case e.nodeType != 1: //not a node.
21154                     return;
21155                 
21156                 case this.tag === true: // everything
21157                 case typeof(this.tag) == 'object' && this.tag.indexOf(e.tagName) > -1: // array and it matches.
21158                 case typeof(this.tag) == 'string' && this.tag == e.tagName: // array and it matches.
21159                     if (this.replaceTag && false === this.replaceTag(e)) {
21160                         return;
21161                     }
21162                     if (e.hasChildNodes()) {
21163                         this.walk(e);
21164                     }
21165                     return;
21166                 
21167                 default:    // tags .. that do not match.
21168                     if (e.hasChildNodes()) {
21169                         this.walk(e);
21170                     }
21171             }
21172             
21173         }, this);
21174         
21175     }
21176 }; 
21177
21178 /**
21179  * @class Roo.htmleditor.FilterAttributes
21180  * clean attributes and  styles including http:// etc.. in attribute
21181  * @constructor
21182 * Run a new Attribute Filter
21183 * @param {Object} config Configuration options
21184  */
21185 Roo.htmleditor.FilterAttributes = function(cfg)
21186 {
21187     Roo.apply(this, cfg);
21188     this.attrib_black = this.attrib_black || [];
21189     this.attrib_white = this.attrib_white || [];
21190
21191     this.attrib_clean = this.attrib_clean || [];
21192     this.style_white = this.style_white || [];
21193     this.style_black = this.style_black || [];
21194     this.walk(cfg.node);
21195 }
21196
21197 Roo.extend(Roo.htmleditor.FilterAttributes, Roo.htmleditor.Filter,
21198 {
21199     tag: true, // all tags
21200     
21201     attrib_black : false, // array
21202     attrib_clean : false,
21203     attrib_white : false,
21204
21205     style_white : false,
21206     style_black : false,
21207      
21208      
21209     replaceTag : function(node)
21210     {
21211         if (!node.attributes || !node.attributes.length) {
21212             return true;
21213         }
21214         
21215         for (var i = node.attributes.length-1; i > -1 ; i--) {
21216             var a = node.attributes[i];
21217             //console.log(a);
21218             if (this.attrib_white.length && this.attrib_white.indexOf(a.name.toLowerCase()) < 0) {
21219                 node.removeAttribute(a.name);
21220                 continue;
21221             }
21222             
21223             
21224             
21225             if (a.name.toLowerCase().substr(0,2)=='on')  {
21226                 node.removeAttribute(a.name);
21227                 continue;
21228             }
21229             
21230             
21231             if (this.attrib_black.indexOf(a.name.toLowerCase()) > -1) {
21232                 node.removeAttribute(a.name);
21233                 continue;
21234             }
21235             if (this.attrib_clean.indexOf(a.name.toLowerCase()) > -1) {
21236                 this.cleanAttr(node,a.name,a.value); // fixme..
21237                 continue;
21238             }
21239             if (a.name == 'style') {
21240                 this.cleanStyle(node,a.name,a.value);
21241                 continue;
21242             }
21243             /// clean up MS crap..
21244             // tecnically this should be a list of valid class'es..
21245             
21246             
21247             if (a.name == 'class') {
21248                 if (a.value.match(/^Mso/)) {
21249                     node.removeAttribute('class');
21250                 }
21251                 
21252                 if (a.value.match(/^body$/)) {
21253                     node.removeAttribute('class');
21254                 }
21255                 continue;
21256             }
21257             
21258             
21259             // style cleanup!?
21260             // class cleanup?
21261             
21262         }
21263         return true; // clean children
21264     },
21265         
21266     cleanAttr: function(node, n,v)
21267     {
21268         
21269         if (v.match(/^\./) || v.match(/^\//)) {
21270             return;
21271         }
21272         if (v.match(/^(http|https):\/\//)
21273             || v.match(/^mailto:/) 
21274             || v.match(/^ftp:/)
21275             || v.match(/^data:/)
21276             ) {
21277             return;
21278         }
21279         if (v.match(/^#/)) {
21280             return;
21281         }
21282         if (v.match(/^\{/)) { // allow template editing.
21283             return;
21284         }
21285 //            Roo.log("(REMOVE TAG)"+ node.tagName +'.' + n + '=' + v);
21286         node.removeAttribute(n);
21287         
21288     },
21289     cleanStyle : function(node,  n,v)
21290     {
21291         if (v.match(/expression/)) { //XSS?? should we even bother..
21292             node.removeAttribute(n);
21293             return;
21294         }
21295         
21296         var parts = v.split(/;/);
21297         var clean = [];
21298         
21299         Roo.each(parts, function(p) {
21300             p = p.replace(/^\s+/g,'').replace(/\s+$/g,'');
21301             if (!p.length) {
21302                 return true;
21303             }
21304             var l = p.split(':').shift().replace(/\s+/g,'');
21305             l = l.replace(/^\s+/g,'').replace(/\s+$/g,'');
21306             
21307             if ( this.style_black.length && (this.style_black.indexOf(l) > -1 || this.style_black.indexOf(l.toLowerCase()) > -1)) {
21308                 return true;
21309             }
21310             //Roo.log()
21311             // only allow 'c whitelisted system attributes'
21312             if ( this.style_white.length &&  style_white.indexOf(l) < 0 && style_white.indexOf(l.toLowerCase()) < 0 ) {
21313                 return true;
21314             }
21315             
21316             
21317             clean.push(p);
21318             return true;
21319         },this);
21320         if (clean.length) { 
21321             node.setAttribute(n, clean.join(';'));
21322         } else {
21323             node.removeAttribute(n);
21324         }
21325         
21326     }
21327         
21328         
21329         
21330     
21331 });/**
21332  * @class Roo.htmleditor.FilterBlack
21333  * remove blacklisted elements.
21334  * @constructor
21335  * Run a new Blacklisted Filter
21336  * @param {Object} config Configuration options
21337  */
21338
21339 Roo.htmleditor.FilterBlack = function(cfg)
21340 {
21341     Roo.apply(this, cfg);
21342     this.walk(cfg.node);
21343 }
21344
21345 Roo.extend(Roo.htmleditor.FilterBlack, Roo.htmleditor.Filter,
21346 {
21347     tag : true, // all elements.
21348    
21349     replaceTag : function(n)
21350     {
21351         n.parentNode.removeChild(n);
21352     }
21353 });
21354 /**
21355  * @class Roo.htmleditor.FilterComment
21356  * remove comments.
21357  * @constructor
21358 * Run a new Comments Filter
21359 * @param {Object} config Configuration options
21360  */
21361 Roo.htmleditor.FilterComment = function(cfg)
21362 {
21363     this.walk(cfg.node);
21364 }
21365
21366 Roo.extend(Roo.htmleditor.FilterComment, Roo.htmleditor.Filter,
21367 {
21368   
21369     replaceComment : function(n)
21370     {
21371         n.parentNode.removeChild(n);
21372     }
21373 });/**
21374  * @class Roo.htmleditor.FilterKeepChildren
21375  * remove tags but keep children
21376  * @constructor
21377  * Run a new Keep Children Filter
21378  * @param {Object} config Configuration options
21379  */
21380
21381 Roo.htmleditor.FilterKeepChildren = function(cfg)
21382 {
21383     Roo.apply(this, cfg);
21384     if (this.tag === false) {
21385         return; // dont walk.. (you can use this to use this just to do a child removal on a single tag )
21386     }
21387     this.walk(cfg.node);
21388 }
21389
21390 Roo.extend(Roo.htmleditor.FilterKeepChildren, Roo.htmleditor.FilterBlack,
21391 {
21392     
21393   
21394     replaceTag : function(node)
21395     {
21396         // walk children...
21397         //Roo.log(node);
21398         var ar = Array.from(node.childNodes);
21399         //remove first..
21400         for (var i = 0; i < ar.length; i++) {
21401             if (ar[i].nodeType == 1) {
21402                 if (
21403                     (typeof(this.tag) == 'object' && this.tag.indexOf(ar[i].tagName) > -1)
21404                     || // array and it matches
21405                     (typeof(this.tag) == 'string' && this.tag == ar[i].tagName)
21406                 ) {
21407                     this.replaceTag(ar[i]); // child is blacklisted as well...
21408                     continue;
21409                 }
21410             }
21411         }  
21412         ar = Array.from(node.childNodes);
21413         for (var i = 0; i < ar.length; i++) {
21414          
21415             node.removeChild(ar[i]);
21416             // what if we need to walk these???
21417             node.parentNode.insertBefore(ar[i], node);
21418             if (this.tag !== false) {
21419                 this.walk(ar[i]);
21420                 
21421             }
21422         }
21423         node.parentNode.removeChild(node);
21424         return false; // don't walk children
21425         
21426         
21427     }
21428 });/**
21429  * @class Roo.htmleditor.FilterParagraph
21430  * paragraphs cause a nightmare for shared content - this filter is designed to be called ? at various points when editing
21431  * like on 'push' to remove the <p> tags and replace them with line breaks.
21432  * @constructor
21433  * Run a new Paragraph Filter
21434  * @param {Object} config Configuration options
21435  */
21436
21437 Roo.htmleditor.FilterParagraph = function(cfg)
21438 {
21439     // no need to apply config.
21440     this.walk(cfg.node);
21441 }
21442
21443 Roo.extend(Roo.htmleditor.FilterParagraph, Roo.htmleditor.Filter,
21444 {
21445     
21446      
21447     tag : 'P',
21448     
21449      
21450     replaceTag : function(node)
21451     {
21452         
21453         if (node.childNodes.length == 1 &&
21454             node.childNodes[0].nodeType == 3 &&
21455             node.childNodes[0].textContent.trim().length < 1
21456             ) {
21457             // remove and replace with '<BR>';
21458             node.parentNode.replaceChild(node.ownerDocument.createElement('BR'),node);
21459             return false; // no need to walk..
21460         }
21461         var ar = Array.from(node.childNodes);
21462         for (var i = 0; i < ar.length; i++) {
21463             node.removeChild(ar[i]);
21464             // what if we need to walk these???
21465             node.parentNode.insertBefore(ar[i], node);
21466         }
21467         // now what about this?
21468         // <p> &nbsp; </p>
21469         
21470         // double BR.
21471         node.parentNode.insertBefore(node.ownerDocument.createElement('BR'), node);
21472         node.parentNode.insertBefore(node.ownerDocument.createElement('BR'), node);
21473         node.parentNode.removeChild(node);
21474         
21475         return false;
21476
21477     }
21478     
21479 });/**
21480  * @class Roo.htmleditor.FilterSpan
21481  * filter span's with no attributes out..
21482  * @constructor
21483  * Run a new Span Filter
21484  * @param {Object} config Configuration options
21485  */
21486
21487 Roo.htmleditor.FilterSpan = function(cfg)
21488 {
21489     // no need to apply config.
21490     this.walk(cfg.node);
21491 }
21492
21493 Roo.extend(Roo.htmleditor.FilterSpan, Roo.htmleditor.FilterKeepChildren,
21494 {
21495      
21496     tag : 'SPAN',
21497      
21498  
21499     replaceTag : function(node)
21500     {
21501         if (node.attributes && node.attributes.length > 0) {
21502             return true; // walk if there are any.
21503         }
21504         Roo.htmleditor.FilterKeepChildren.prototype.replaceTag.call(this, node);
21505         return false;
21506      
21507     }
21508     
21509 });/**
21510  * @class Roo.htmleditor.FilterTableWidth
21511   try and remove table width data - as that frequently messes up other stuff.
21512  * 
21513  *      was cleanTableWidths.
21514  *
21515  * Quite often pasting from word etc.. results in tables with column and widths.
21516  * This does not work well on fluid HTML layouts - like emails. - so this code should hunt an destroy them..
21517  *
21518  * @constructor
21519  * Run a new Table Filter
21520  * @param {Object} config Configuration options
21521  */
21522
21523 Roo.htmleditor.FilterTableWidth = function(cfg)
21524 {
21525     // no need to apply config.
21526     this.tag = ['TABLE', 'TD', 'TR', 'TH', 'THEAD', 'TBODY' ];
21527     this.walk(cfg.node);
21528 }
21529
21530 Roo.extend(Roo.htmleditor.FilterTableWidth, Roo.htmleditor.Filter,
21531 {
21532      
21533      
21534     
21535     replaceTag: function(node) {
21536         
21537         
21538       
21539         if (node.hasAttribute('width')) {
21540             node.removeAttribute('width');
21541         }
21542         
21543          
21544         if (node.hasAttribute("style")) {
21545             // pretty basic...
21546             
21547             var styles = node.getAttribute("style").split(";");
21548             var nstyle = [];
21549             Roo.each(styles, function(s) {
21550                 if (!s.match(/:/)) {
21551                     return;
21552                 }
21553                 var kv = s.split(":");
21554                 if (kv[0].match(/^\s*(width|min-width)\s*$/)) {
21555                     return;
21556                 }
21557                 // what ever is left... we allow.
21558                 nstyle.push(s);
21559             });
21560             node.setAttribute("style", nstyle.length ? nstyle.join(';') : '');
21561             if (!nstyle.length) {
21562                 node.removeAttribute('style');
21563             }
21564         }
21565         
21566         return true; // continue doing children..
21567     }
21568 });/**
21569  * @class Roo.htmleditor.FilterWord
21570  * try and clean up all the mess that Word generates.
21571  * 
21572  * This is the 'nice version' - see 'Heavy' that white lists a very short list of elements, and multi-filters 
21573  
21574  * @constructor
21575  * Run a new Span Filter
21576  * @param {Object} config Configuration options
21577  */
21578
21579 Roo.htmleditor.FilterWord = function(cfg)
21580 {
21581     // no need to apply config.
21582     this.walk(cfg.node);
21583 }
21584
21585 Roo.extend(Roo.htmleditor.FilterWord, Roo.htmleditor.Filter,
21586 {
21587     tag: true,
21588      
21589     
21590     /**
21591      * Clean up MS wordisms...
21592      */
21593     replaceTag : function(node)
21594     {
21595          
21596         // no idea what this does - span with text, replaceds with just text.
21597         if(
21598                 node.nodeName == 'SPAN' &&
21599                 !node.hasAttributes() &&
21600                 node.childNodes.length == 1 &&
21601                 node.firstChild.nodeName == "#text"  
21602         ) {
21603             var textNode = node.firstChild;
21604             node.removeChild(textNode);
21605             if (node.getAttribute('lang') != 'zh-CN') {   // do not space pad on chinese characters..
21606                 node.parentNode.insertBefore(node.ownerDocument.createTextNode(" "), node);
21607             }
21608             node.parentNode.insertBefore(textNode, node);
21609             if (node.getAttribute('lang') != 'zh-CN') {   // do not space pad on chinese characters..
21610                 node.parentNode.insertBefore(node.ownerDocument.createTextNode(" ") , node);
21611             }
21612             
21613             node.parentNode.removeChild(node);
21614             return false; // dont do chidren - we have remove our node - so no need to do chdhilren?
21615         }
21616         
21617    
21618         
21619         if (node.tagName.toLowerCase().match(/^(style|script|applet|embed|noframes|noscript)$/)) {
21620             node.parentNode.removeChild(node);
21621             return false; // dont do chidlren
21622         }
21623         //Roo.log(node.tagName);
21624         // remove - but keep children..
21625         if (node.tagName.toLowerCase().match(/^(meta|link|\\?xml:|st1:|o:|v:|font)/)) {
21626             //Roo.log('-- removed');
21627             while (node.childNodes.length) {
21628                 var cn = node.childNodes[0];
21629                 node.removeChild(cn);
21630                 node.parentNode.insertBefore(cn, node);
21631                 // move node to parent - and clean it..
21632                 this.replaceTag(cn);
21633             }
21634             node.parentNode.removeChild(node);
21635             /// no need to iterate chidlren = it's got none..
21636             //this.iterateChildren(node, this.cleanWord);
21637             return false; // no need to iterate children.
21638         }
21639         // clean styles
21640         if (node.className.length) {
21641             
21642             var cn = node.className.split(/\W+/);
21643             var cna = [];
21644             Roo.each(cn, function(cls) {
21645                 if (cls.match(/Mso[a-zA-Z]+/)) {
21646                     return;
21647                 }
21648                 cna.push(cls);
21649             });
21650             node.className = cna.length ? cna.join(' ') : '';
21651             if (!cna.length) {
21652                 node.removeAttribute("class");
21653             }
21654         }
21655         
21656         if (node.hasAttribute("lang")) {
21657             node.removeAttribute("lang");
21658         }
21659         
21660         if (node.hasAttribute("style")) {
21661             
21662             var styles = node.getAttribute("style").split(";");
21663             var nstyle = [];
21664             Roo.each(styles, function(s) {
21665                 if (!s.match(/:/)) {
21666                     return;
21667                 }
21668                 var kv = s.split(":");
21669                 if (kv[0].match(/^(mso-|line|font|background|margin|padding|color)/)) {
21670                     return;
21671                 }
21672                 // what ever is left... we allow.
21673                 nstyle.push(s);
21674             });
21675             node.setAttribute("style", nstyle.length ? nstyle.join(';') : '');
21676             if (!nstyle.length) {
21677                 node.removeAttribute('style');
21678             }
21679         }
21680         return true; // do children
21681         
21682         
21683         
21684     }
21685 });
21686 /**
21687  * @class Roo.htmleditor.FilterStyleToTag
21688  * part of the word stuff... - certain 'styles' should be converted to tags.
21689  * eg.
21690  *   font-weight: bold -> bold
21691  *   ?? super / subscrit etc..
21692  * 
21693  * @constructor
21694 * Run a new style to tag filter.
21695 * @param {Object} config Configuration options
21696  */
21697 Roo.htmleditor.FilterStyleToTag = function(cfg)
21698 {
21699     
21700     this.tags = {
21701         B  : [ 'fontWeight' , 'bold'],
21702         I :  [ 'fontStyle' , 'italic'],
21703         //pre :  [ 'font-style' , 'italic'],
21704         // h1.. h6 ?? font-size?
21705         SUP : [ 'verticalAlign' , 'super' ],
21706         SUB : [ 'verticalAlign' , 'sub' ]
21707         
21708         
21709     };
21710     
21711     Roo.apply(this, cfg);
21712      
21713     
21714     this.walk(cfg.node);
21715     
21716     
21717     
21718 }
21719
21720
21721 Roo.extend(Roo.htmleditor.FilterStyleToTag, Roo.htmleditor.Filter,
21722 {
21723     tag: true, // all tags
21724     
21725     tags : false,
21726     
21727     
21728     replaceTag : function(node)
21729     {
21730         
21731         
21732         if (node.getAttribute("style") === null) {
21733             return true;
21734         }
21735         var inject = [];
21736         for (var k in this.tags) {
21737             if (node.style[this.tags[k][0]] == this.tags[k][1]) {
21738                 inject.push(k);
21739                 node.style.removeProperty(this.tags[k][0]);
21740             }
21741         }
21742         if (!inject.length) {
21743             return true; 
21744         }
21745         var cn = Array.from(node.childNodes);
21746         var nn = node;
21747         Roo.each(inject, function(t) {
21748             var nc = node.ownerDocument.createElement(t);
21749             nn.appendChild(nc);
21750             nn = nc;
21751         });
21752         for(var i = 0;i < cn.length;cn++) {
21753             node.removeChild(cn[i]);
21754             nn.appendChild(cn[i]);
21755         }
21756         return true /// iterate thru
21757     }
21758     
21759 })/**
21760  * @class Roo.htmleditor.FilterLongBr
21761  * BR/BR/BR - keep a maximum of 2...
21762  * @constructor
21763  * Run a new Long BR Filter
21764  * @param {Object} config Configuration options
21765  */
21766
21767 Roo.htmleditor.FilterLongBr = function(cfg)
21768 {
21769     // no need to apply config.
21770     this.walk(cfg.node);
21771 }
21772
21773 Roo.extend(Roo.htmleditor.FilterLongBr, Roo.htmleditor.Filter,
21774 {
21775     
21776      
21777     tag : 'BR',
21778     
21779      
21780     replaceTag : function(node)
21781     {
21782         
21783         var ps = node.nextSibling;
21784         while (ps && ps.nodeType == 3 && ps.nodeValue.trim().length < 1) {
21785             ps = ps.nextSibling;
21786         }
21787         
21788         if (!ps &&  [ 'TD', 'TH', 'LI', 'H1', 'H2', 'H3', 'H4', 'H5', 'H6' ].indexOf(node.parentNode.tagName) > -1) { 
21789             node.parentNode.removeChild(node); // remove last BR inside one fo these tags
21790             return false;
21791         }
21792         
21793         if (!ps || ps.nodeType != 1) {
21794             return false;
21795         }
21796         
21797         if (!ps || ps.tagName != 'BR') {
21798            
21799             return false;
21800         }
21801         
21802         
21803         
21804         
21805         
21806         if (!node.previousSibling) {
21807             return false;
21808         }
21809         var ps = node.previousSibling;
21810         
21811         while (ps && ps.nodeType == 3 && ps.nodeValue.trim().length < 1) {
21812             ps = ps.previousSibling;
21813         }
21814         if (!ps || ps.nodeType != 1) {
21815             return false;
21816         }
21817         // if header or BR before.. then it's a candidate for removal.. - as we only want '2' of these..
21818         if (!ps || [ 'BR', 'H1', 'H2', 'H3', 'H4', 'H5', 'H6' ].indexOf(ps.tagName) < 0) {
21819             return false;
21820         }
21821         
21822         node.parentNode.removeChild(node); // remove me...
21823         
21824         return false; // no need to do children
21825
21826     }
21827     
21828 }); 
21829
21830 /**
21831  * @class Roo.htmleditor.FilterBlock
21832  * removes id / data-block and contenteditable that are associated with blocks
21833  * usage should be done on a cloned copy of the dom
21834  * @constructor
21835 * Run a new Attribute Filter { node : xxxx }}
21836 * @param {Object} config Configuration options
21837  */
21838 Roo.htmleditor.FilterBlock = function(cfg)
21839 {
21840     Roo.apply(this, cfg);
21841     var qa = cfg.node.querySelectorAll;
21842     this.removeAttributes('data-block');
21843     this.removeAttributes('contenteditable');
21844     this.removeAttributes('id');
21845     
21846 }
21847
21848 Roo.apply(Roo.htmleditor.FilterBlock.prototype,
21849 {
21850     node: true, // all tags
21851      
21852      
21853     removeAttributes : function(attr)
21854     {
21855         var ar = this.node.querySelectorAll('*[' + attr + ']');
21856         for (var i =0;i<ar.length;i++) {
21857             ar[i].removeAttribute(attr);
21858         }
21859     }
21860         
21861         
21862         
21863     
21864 });
21865 /***
21866  * This is based loosely on tinymce 
21867  * @class Roo.htmleditor.TidySerializer
21868  * https://github.com/thorn0/tinymce.html/blob/master/tinymce.html.js
21869  * @constructor
21870  * @method Serializer
21871  * @param {Object} settings Name/value settings object.
21872  */
21873
21874
21875 Roo.htmleditor.TidySerializer = function(settings)
21876 {
21877     Roo.apply(this, settings);
21878     
21879     this.writer = new Roo.htmleditor.TidyWriter(settings);
21880     
21881     
21882
21883 };
21884 Roo.htmleditor.TidySerializer.prototype = {
21885     
21886     /**
21887      * @param {boolean} inner do the inner of the node.
21888      */
21889     inner : false,
21890     
21891     writer : false,
21892     
21893     /**
21894     * Serializes the specified node into a string.
21895     *
21896     * @example
21897     * new tinymce.html.Serializer().serialize(new tinymce.html.DomParser().parse('<p>text</p>'));
21898     * @method serialize
21899     * @param {DomElement} node Node instance to serialize.
21900     * @return {String} String with HTML based on DOM tree.
21901     */
21902     serialize : function(node) {
21903         
21904         // = settings.validate;
21905         var writer = this.writer;
21906         var self  = this;
21907         this.handlers = {
21908             // #text
21909             3: function(node) {
21910                 
21911                 writer.text(node.nodeValue, node);
21912             },
21913             // #comment
21914             8: function(node) {
21915                 writer.comment(node.nodeValue);
21916             },
21917             // Processing instruction
21918             7: function(node) {
21919                 writer.pi(node.name, node.nodeValue);
21920             },
21921             // Doctype
21922             10: function(node) {
21923                 writer.doctype(node.nodeValue);
21924             },
21925             // CDATA
21926             4: function(node) {
21927                 writer.cdata(node.nodeValue);
21928             },
21929             // Document fragment
21930             11: function(node) {
21931                 node = node.firstChild;
21932                 if (!node) {
21933                     return;
21934                 }
21935                 while(node) {
21936                     self.walk(node);
21937                     node = node.nextSibling
21938                 }
21939             }
21940         };
21941         writer.reset();
21942         1 != node.nodeType || this.inner ? this.handlers[11](node) : this.walk(node);
21943         return writer.getContent();
21944     },
21945
21946     walk: function(node)
21947     {
21948         var attrName, attrValue, sortedAttrs, i, l, elementRule,
21949             handler = this.handlers[node.nodeType];
21950             
21951         if (handler) {
21952             handler(node);
21953             return;
21954         }
21955     
21956         var name = node.nodeName;
21957         var isEmpty = node.childNodes.length < 1;
21958       
21959         var writer = this.writer;
21960         var attrs = node.attributes;
21961         // Sort attributes
21962         
21963         writer.start(node.nodeName, attrs, isEmpty, node);
21964         if (isEmpty) {
21965             return;
21966         }
21967         node = node.firstChild;
21968         if (!node) {
21969             writer.end(name);
21970             return;
21971         }
21972         while (node) {
21973             this.walk(node);
21974             node = node.nextSibling;
21975         }
21976         writer.end(name);
21977         
21978     
21979     }
21980     // Serialize element and treat all non elements as fragments
21981    
21982 }; 
21983
21984 /***
21985  * This is based loosely on tinymce 
21986  * @class Roo.htmleditor.TidyWriter
21987  * https://github.com/thorn0/tinymce.html/blob/master/tinymce.html.js
21988  *
21989  * Known issues?
21990  * - not tested much with 'PRE' formated elements.
21991  * 
21992  *
21993  *
21994  */
21995
21996 Roo.htmleditor.TidyWriter = function(settings)
21997 {
21998     
21999     // indent, indentBefore, indentAfter, encode, htmlOutput, html = [];
22000     Roo.apply(this, settings);
22001     this.html = [];
22002     this.state = [];
22003      
22004     this.encode = Roo.htmleditor.TidyEntities.getEncodeFunc(settings.entity_encoding || 'raw', settings.entities);
22005   
22006 }
22007 Roo.htmleditor.TidyWriter.prototype = {
22008
22009  
22010     state : false,
22011     
22012     indent :  '  ',
22013     
22014     // part of state...
22015     indentstr : '',
22016     in_pre: false,
22017     in_inline : false,
22018     last_inline : false,
22019     encode : false,
22020      
22021     
22022             /**
22023     * Writes the a start element such as <p id="a">.
22024     *
22025     * @method start
22026     * @param {String} name Name of the element.
22027     * @param {Array} attrs Optional attribute array or undefined if it hasn't any.
22028     * @param {Boolean} empty Optional empty state if the tag should end like <br />.
22029     */
22030     start: function(name, attrs, empty, node)
22031     {
22032         var i, l, attr, value;
22033         
22034         // there are some situations where adding line break && indentation will not work. will not work.
22035         // <span / b / i ... formating?
22036         
22037         var in_inline = this.in_inline || Roo.htmleditor.TidyWriter.inline_elements.indexOf(name) > -1;
22038         var in_pre    = this.in_pre    || Roo.htmleditor.TidyWriter.whitespace_elements.indexOf(name) > -1;
22039         
22040         var is_short   = empty ? Roo.htmleditor.TidyWriter.shortend_elements.indexOf(name) > -1 : false;
22041         
22042         var add_lb = name == 'BR' ? false : in_inline;
22043         
22044         if (!add_lb && !this.in_pre && this.lastElementEndsWS()) {
22045             i_inline = false;
22046         }
22047
22048         var indentstr =  this.indentstr;
22049         
22050         // e_inline = elements that can be inline, but still allow \n before and after?
22051         // only 'BR' ??? any others?
22052         
22053         // ADD LINE BEFORE tage
22054         if (!this.in_pre) {
22055             if (in_inline) {
22056                 //code
22057                 if (name == 'BR') {
22058                     this.addLine();
22059                 } else if (this.lastElementEndsWS()) {
22060                     this.addLine();
22061                 } else{
22062                     // otherwise - no new line. (and dont indent.)
22063                     indentstr = '';
22064                 }
22065                 
22066             } else {
22067                 this.addLine();
22068             }
22069         } else {
22070             indentstr = '';
22071         }
22072         
22073         this.html.push(indentstr + '<', name.toLowerCase());
22074         
22075         if (attrs) {
22076             for (i = 0, l = attrs.length; i < l; i++) {
22077                 attr = attrs[i];
22078                 this.html.push(' ', attr.name, '="', this.encode(attr.value, true), '"');
22079             }
22080         }
22081      
22082         if (empty) {
22083             if (is_short) {
22084                 this.html[this.html.length] = '/>';
22085             } else {
22086                 this.html[this.html.length] = '></' + name.toLowerCase() + '>';
22087             }
22088             var e_inline = name == 'BR' ? false : this.in_inline;
22089             
22090             if (!e_inline && !this.in_pre) {
22091                 this.addLine();
22092             }
22093             return;
22094         
22095         }
22096         // not empty..
22097         this.html[this.html.length] = '>';
22098         
22099         // there is a special situation, where we need to turn on in_inline - if any of the imediate chidlren are one of these.
22100         /*
22101         if (!in_inline && !in_pre) {
22102             var cn = node.firstChild;
22103             while(cn) {
22104                 if (Roo.htmleditor.TidyWriter.inline_elements.indexOf(cn.nodeName) > -1) {
22105                     in_inline = true
22106                     break;
22107                 }
22108                 cn = cn.nextSibling;
22109             }
22110              
22111         }
22112         */
22113         
22114         
22115         this.pushState({
22116             indentstr : in_pre   ? '' : (this.indentstr + this.indent),
22117             in_pre : in_pre,
22118             in_inline :  in_inline
22119         });
22120         // add a line after if we are not in a
22121         
22122         if (!in_inline && !in_pre) {
22123             this.addLine();
22124         }
22125         
22126             
22127          
22128         
22129     },
22130     
22131     lastElementEndsWS : function()
22132     {
22133         var value = this.html.length > 0 ? this.html[this.html.length-1] : false;
22134         if (value === false) {
22135             return true;
22136         }
22137         return value.match(/\s+$/);
22138         
22139     },
22140     
22141     /**
22142      * Writes the a end element such as </p>.
22143      *
22144      * @method end
22145      * @param {String} name Name of the element.
22146      */
22147     end: function(name) {
22148         var value;
22149         this.popState();
22150         var indentstr = '';
22151         var in_inline = this.in_inline || Roo.htmleditor.TidyWriter.inline_elements.indexOf(name) > -1;
22152         
22153         if (!this.in_pre && !in_inline) {
22154             this.addLine();
22155             indentstr  = this.indentstr;
22156         }
22157         this.html.push(indentstr + '</', name.toLowerCase(), '>');
22158         this.last_inline = in_inline;
22159         
22160         // pop the indent state..
22161     },
22162     /**
22163      * Writes a text node.
22164      *
22165      * In pre - we should not mess with the contents.
22166      * 
22167      *
22168      * @method text
22169      * @param {String} text String to write out.
22170      * @param {Boolean} raw Optional raw state if true the contents wont get encoded.
22171      */
22172     text: function(text, node)
22173     {
22174         // if not in whitespace critical
22175         if (text.length < 1) {
22176             return;
22177         }
22178         if (this.in_pre) {
22179             this.html[this.html.length] =  text;
22180             return;   
22181         }
22182         
22183         if (this.in_inline) {
22184             text = text.replace(/\s+/g,' '); // all white space inc line breaks to a slingle' '
22185             if (text != ' ') {
22186                 text = text.replace(/\s+/,' ');  // all white space to single white space
22187                 
22188                     
22189                 // if next tag is '<BR>', then we can trim right..
22190                 if (node.nextSibling &&
22191                     node.nextSibling.nodeType == 1 &&
22192                     node.nextSibling.nodeName == 'BR' )
22193                 {
22194                     text = text.replace(/\s+$/g,'');
22195                 }
22196                 // if previous tag was a BR, we can also trim..
22197                 if (node.previousSibling &&
22198                     node.previousSibling.nodeType == 1 &&
22199                     node.previousSibling.nodeName == 'BR' )
22200                 {
22201                     text = this.indentstr +  text.replace(/^\s+/g,'');
22202                 }
22203                 if (text.match(/\n/)) {
22204                     text = text.replace(
22205                         /(?![^\n]{1,64}$)([^\n]{1,64})\s/g, '$1\n' + this.indentstr
22206                     );
22207                     // remoeve the last whitespace / line break.
22208                     text = text.replace(/\n\s+$/,'');
22209                 }
22210                 // repace long lines
22211                 
22212             }
22213              
22214             this.html[this.html.length] =  text;
22215             return;   
22216         }
22217         // see if previous element was a inline element.
22218         var indentstr = this.indentstr;
22219    
22220         text = text.replace(/\s+/g," "); // all whitespace into single white space.
22221         
22222         // should trim left?
22223         if (node.previousSibling &&
22224             node.previousSibling.nodeType == 1 &&
22225             Roo.htmleditor.TidyWriter.inline_elements.indexOf(node.previousSibling.nodeName) > -1)
22226         {
22227             indentstr = '';
22228             
22229         } else {
22230             this.addLine();
22231             text = text.replace(/^\s+/,''); // trim left
22232           
22233         }
22234         // should trim right?
22235         if (node.nextSibling &&
22236             node.nextSibling.nodeType == 1 &&
22237             Roo.htmleditor.TidyWriter.inline_elements.indexOf(node.nextSibling.nodeName) > -1)
22238         {
22239           // noop
22240             
22241         }  else {
22242             text = text.replace(/\s+$/,''); // trim right
22243         }
22244          
22245               
22246         
22247         
22248         
22249         if (text.length < 1) {
22250             return;
22251         }
22252         if (!text.match(/\n/)) {
22253             this.html.push(indentstr + text);
22254             return;
22255         }
22256         
22257         text = this.indentstr + text.replace(
22258             /(?![^\n]{1,64}$)([^\n]{1,64})\s/g, '$1\n' + this.indentstr
22259         );
22260         // remoeve the last whitespace / line break.
22261         text = text.replace(/\s+$/,''); 
22262         
22263         this.html.push(text);
22264         
22265         // split and indent..
22266         
22267         
22268     },
22269     /**
22270      * Writes a cdata node such as <![CDATA[data]]>.
22271      *
22272      * @method cdata
22273      * @param {String} text String to write out inside the cdata.
22274      */
22275     cdata: function(text) {
22276         this.html.push('<![CDATA[', text, ']]>');
22277     },
22278     /**
22279     * Writes a comment node such as <!-- Comment -->.
22280     *
22281     * @method cdata
22282     * @param {String} text String to write out inside the comment.
22283     */
22284    comment: function(text) {
22285        this.html.push('<!--', text, '-->');
22286    },
22287     /**
22288      * Writes a PI node such as <?xml attr="value" ?>.
22289      *
22290      * @method pi
22291      * @param {String} name Name of the pi.
22292      * @param {String} text String to write out inside the pi.
22293      */
22294     pi: function(name, text) {
22295         text ? this.html.push('<?', name, ' ', this.encode(text), '?>') : this.html.push('<?', name, '?>');
22296         this.indent != '' && this.html.push('\n');
22297     },
22298     /**
22299      * Writes a doctype node such as <!DOCTYPE data>.
22300      *
22301      * @method doctype
22302      * @param {String} text String to write out inside the doctype.
22303      */
22304     doctype: function(text) {
22305         this.html.push('<!DOCTYPE', text, '>', this.indent != '' ? '\n' : '');
22306     },
22307     /**
22308      * Resets the internal buffer if one wants to reuse the writer.
22309      *
22310      * @method reset
22311      */
22312     reset: function() {
22313         this.html.length = 0;
22314         this.state = [];
22315         this.pushState({
22316             indentstr : '',
22317             in_pre : false, 
22318             in_inline : false
22319         })
22320     },
22321     /**
22322      * Returns the contents that got serialized.
22323      *
22324      * @method getContent
22325      * @return {String} HTML contents that got written down.
22326      */
22327     getContent: function() {
22328         return this.html.join('').replace(/\n$/, '');
22329     },
22330     
22331     pushState : function(cfg)
22332     {
22333         this.state.push(cfg);
22334         Roo.apply(this, cfg);
22335     },
22336     
22337     popState : function()
22338     {
22339         if (this.state.length < 1) {
22340             return; // nothing to push
22341         }
22342         var cfg = {
22343             in_pre: false,
22344             indentstr : ''
22345         };
22346         this.state.pop();
22347         if (this.state.length > 0) {
22348             cfg = this.state[this.state.length-1]; 
22349         }
22350         Roo.apply(this, cfg);
22351     },
22352     
22353     addLine: function()
22354     {
22355         if (this.html.length < 1) {
22356             return;
22357         }
22358         
22359         
22360         var value = this.html[this.html.length - 1];
22361         if (value.length > 0 && '\n' !== value) {
22362             this.html.push('\n');
22363         }
22364     }
22365     
22366     
22367 //'pre script noscript style textarea video audio iframe object code'
22368 // shortended... 'area base basefont br col frame hr img input isindex link  meta param embed source wbr track');
22369 // inline 
22370 };
22371
22372 Roo.htmleditor.TidyWriter.inline_elements = [
22373         'SPAN','STRONG','B','EM','I','FONT','STRIKE','U','VAR',
22374         'CITE','DFN','CODE','MARK','Q','SUP','SUB','SAMP', 'A'
22375 ];
22376 Roo.htmleditor.TidyWriter.shortend_elements = [
22377     'AREA','BASE','BASEFONT','BR','COL','FRAME','HR','IMG','INPUT',
22378     'ISINDEX','LINK','','META','PARAM','EMBED','SOURCE','WBR','TRACK'
22379 ];
22380
22381 Roo.htmleditor.TidyWriter.whitespace_elements = [
22382     'PRE','SCRIPT','NOSCRIPT','STYLE','TEXTAREA','VIDEO','AUDIO','IFRAME','OBJECT','CODE'
22383 ];/***
22384  * This is based loosely on tinymce 
22385  * @class Roo.htmleditor.TidyEntities
22386  * @static
22387  * https://github.com/thorn0/tinymce.html/blob/master/tinymce.html.js
22388  *
22389  * Not 100% sure this is actually used or needed.
22390  */
22391
22392 Roo.htmleditor.TidyEntities = {
22393     
22394     /**
22395      * initialize data..
22396      */
22397     init : function (){
22398      
22399         this.namedEntities = this.buildEntitiesLookup(this.namedEntitiesData, 32);
22400        
22401     },
22402
22403
22404     buildEntitiesLookup: function(items, radix) {
22405         var i, chr, entity, lookup = {};
22406         if (!items) {
22407             return {};
22408         }
22409         items = typeof(items) == 'string' ? items.split(',') : items;
22410         radix = radix || 10;
22411         // Build entities lookup table
22412         for (i = 0; i < items.length; i += 2) {
22413             chr = String.fromCharCode(parseInt(items[i], radix));
22414             // Only add non base entities
22415             if (!this.baseEntities[chr]) {
22416                 entity = '&' + items[i + 1] + ';';
22417                 lookup[chr] = entity;
22418                 lookup[entity] = chr;
22419             }
22420         }
22421         return lookup;
22422         
22423     },
22424     
22425     asciiMap : {
22426             128: '€',
22427             130: '‚',
22428             131: 'ƒ',
22429             132: '„',
22430             133: '…',
22431             134: '†',
22432             135: '‡',
22433             136: 'ˆ',
22434             137: '‰',
22435             138: 'Š',
22436             139: '‹',
22437             140: 'Œ',
22438             142: 'Ž',
22439             145: '‘',
22440             146: '’',
22441             147: '“',
22442             148: '”',
22443             149: '•',
22444             150: '–',
22445             151: '—',
22446             152: '˜',
22447             153: '™',
22448             154: 'š',
22449             155: '›',
22450             156: 'œ',
22451             158: 'ž',
22452             159: 'Ÿ'
22453     },
22454     // Raw entities
22455     baseEntities : {
22456         '"': '&quot;',
22457         // Needs to be escaped since the YUI compressor would otherwise break the code
22458         '\'': '&#39;',
22459         '<': '&lt;',
22460         '>': '&gt;',
22461         '&': '&amp;',
22462         '`': '&#96;'
22463     },
22464     // Reverse lookup table for raw entities
22465     reverseEntities : {
22466         '&lt;': '<',
22467         '&gt;': '>',
22468         '&amp;': '&',
22469         '&quot;': '"',
22470         '&apos;': '\''
22471     },
22472     
22473     attrsCharsRegExp : /[&<>\"\u0060\u007E-\uD7FF\uE000-\uFFEF]|[\uD800-\uDBFF][\uDC00-\uDFFF]/g,
22474     textCharsRegExp : /[<>&\u007E-\uD7FF\uE000-\uFFEF]|[\uD800-\uDBFF][\uDC00-\uDFFF]/g,
22475     rawCharsRegExp : /[<>&\"\']/g,
22476     entityRegExp : /&#([a-z0-9]+);?|&([a-z0-9]+);/gi,
22477     namedEntities  : false,
22478     namedEntitiesData : [ 
22479         '50',
22480         'nbsp',
22481         '51',
22482         'iexcl',
22483         '52',
22484         'cent',
22485         '53',
22486         'pound',
22487         '54',
22488         'curren',
22489         '55',
22490         'yen',
22491         '56',
22492         'brvbar',
22493         '57',
22494         'sect',
22495         '58',
22496         'uml',
22497         '59',
22498         'copy',
22499         '5a',
22500         'ordf',
22501         '5b',
22502         'laquo',
22503         '5c',
22504         'not',
22505         '5d',
22506         'shy',
22507         '5e',
22508         'reg',
22509         '5f',
22510         'macr',
22511         '5g',
22512         'deg',
22513         '5h',
22514         'plusmn',
22515         '5i',
22516         'sup2',
22517         '5j',
22518         'sup3',
22519         '5k',
22520         'acute',
22521         '5l',
22522         'micro',
22523         '5m',
22524         'para',
22525         '5n',
22526         'middot',
22527         '5o',
22528         'cedil',
22529         '5p',
22530         'sup1',
22531         '5q',
22532         'ordm',
22533         '5r',
22534         'raquo',
22535         '5s',
22536         'frac14',
22537         '5t',
22538         'frac12',
22539         '5u',
22540         'frac34',
22541         '5v',
22542         'iquest',
22543         '60',
22544         'Agrave',
22545         '61',
22546         'Aacute',
22547         '62',
22548         'Acirc',
22549         '63',
22550         'Atilde',
22551         '64',
22552         'Auml',
22553         '65',
22554         'Aring',
22555         '66',
22556         'AElig',
22557         '67',
22558         'Ccedil',
22559         '68',
22560         'Egrave',
22561         '69',
22562         'Eacute',
22563         '6a',
22564         'Ecirc',
22565         '6b',
22566         'Euml',
22567         '6c',
22568         'Igrave',
22569         '6d',
22570         'Iacute',
22571         '6e',
22572         'Icirc',
22573         '6f',
22574         'Iuml',
22575         '6g',
22576         'ETH',
22577         '6h',
22578         'Ntilde',
22579         '6i',
22580         'Ograve',
22581         '6j',
22582         'Oacute',
22583         '6k',
22584         'Ocirc',
22585         '6l',
22586         'Otilde',
22587         '6m',
22588         'Ouml',
22589         '6n',
22590         'times',
22591         '6o',
22592         'Oslash',
22593         '6p',
22594         'Ugrave',
22595         '6q',
22596         'Uacute',
22597         '6r',
22598         'Ucirc',
22599         '6s',
22600         'Uuml',
22601         '6t',
22602         'Yacute',
22603         '6u',
22604         'THORN',
22605         '6v',
22606         'szlig',
22607         '70',
22608         'agrave',
22609         '71',
22610         'aacute',
22611         '72',
22612         'acirc',
22613         '73',
22614         'atilde',
22615         '74',
22616         'auml',
22617         '75',
22618         'aring',
22619         '76',
22620         'aelig',
22621         '77',
22622         'ccedil',
22623         '78',
22624         'egrave',
22625         '79',
22626         'eacute',
22627         '7a',
22628         'ecirc',
22629         '7b',
22630         'euml',
22631         '7c',
22632         'igrave',
22633         '7d',
22634         'iacute',
22635         '7e',
22636         'icirc',
22637         '7f',
22638         'iuml',
22639         '7g',
22640         'eth',
22641         '7h',
22642         'ntilde',
22643         '7i',
22644         'ograve',
22645         '7j',
22646         'oacute',
22647         '7k',
22648         'ocirc',
22649         '7l',
22650         'otilde',
22651         '7m',
22652         'ouml',
22653         '7n',
22654         'divide',
22655         '7o',
22656         'oslash',
22657         '7p',
22658         'ugrave',
22659         '7q',
22660         'uacute',
22661         '7r',
22662         'ucirc',
22663         '7s',
22664         'uuml',
22665         '7t',
22666         'yacute',
22667         '7u',
22668         'thorn',
22669         '7v',
22670         'yuml',
22671         'ci',
22672         'fnof',
22673         'sh',
22674         'Alpha',
22675         'si',
22676         'Beta',
22677         'sj',
22678         'Gamma',
22679         'sk',
22680         'Delta',
22681         'sl',
22682         'Epsilon',
22683         'sm',
22684         'Zeta',
22685         'sn',
22686         'Eta',
22687         'so',
22688         'Theta',
22689         'sp',
22690         'Iota',
22691         'sq',
22692         'Kappa',
22693         'sr',
22694         'Lambda',
22695         'ss',
22696         'Mu',
22697         'st',
22698         'Nu',
22699         'su',
22700         'Xi',
22701         'sv',
22702         'Omicron',
22703         't0',
22704         'Pi',
22705         't1',
22706         'Rho',
22707         't3',
22708         'Sigma',
22709         't4',
22710         'Tau',
22711         't5',
22712         'Upsilon',
22713         't6',
22714         'Phi',
22715         't7',
22716         'Chi',
22717         't8',
22718         'Psi',
22719         't9',
22720         'Omega',
22721         'th',
22722         'alpha',
22723         'ti',
22724         'beta',
22725         'tj',
22726         'gamma',
22727         'tk',
22728         'delta',
22729         'tl',
22730         'epsilon',
22731         'tm',
22732         'zeta',
22733         'tn',
22734         'eta',
22735         'to',
22736         'theta',
22737         'tp',
22738         'iota',
22739         'tq',
22740         'kappa',
22741         'tr',
22742         'lambda',
22743         'ts',
22744         'mu',
22745         'tt',
22746         'nu',
22747         'tu',
22748         'xi',
22749         'tv',
22750         'omicron',
22751         'u0',
22752         'pi',
22753         'u1',
22754         'rho',
22755         'u2',
22756         'sigmaf',
22757         'u3',
22758         'sigma',
22759         'u4',
22760         'tau',
22761         'u5',
22762         'upsilon',
22763         'u6',
22764         'phi',
22765         'u7',
22766         'chi',
22767         'u8',
22768         'psi',
22769         'u9',
22770         'omega',
22771         'uh',
22772         'thetasym',
22773         'ui',
22774         'upsih',
22775         'um',
22776         'piv',
22777         '812',
22778         'bull',
22779         '816',
22780         'hellip',
22781         '81i',
22782         'prime',
22783         '81j',
22784         'Prime',
22785         '81u',
22786         'oline',
22787         '824',
22788         'frasl',
22789         '88o',
22790         'weierp',
22791         '88h',
22792         'image',
22793         '88s',
22794         'real',
22795         '892',
22796         'trade',
22797         '89l',
22798         'alefsym',
22799         '8cg',
22800         'larr',
22801         '8ch',
22802         'uarr',
22803         '8ci',
22804         'rarr',
22805         '8cj',
22806         'darr',
22807         '8ck',
22808         'harr',
22809         '8dl',
22810         'crarr',
22811         '8eg',
22812         'lArr',
22813         '8eh',
22814         'uArr',
22815         '8ei',
22816         'rArr',
22817         '8ej',
22818         'dArr',
22819         '8ek',
22820         'hArr',
22821         '8g0',
22822         'forall',
22823         '8g2',
22824         'part',
22825         '8g3',
22826         'exist',
22827         '8g5',
22828         'empty',
22829         '8g7',
22830         'nabla',
22831         '8g8',
22832         'isin',
22833         '8g9',
22834         'notin',
22835         '8gb',
22836         'ni',
22837         '8gf',
22838         'prod',
22839         '8gh',
22840         'sum',
22841         '8gi',
22842         'minus',
22843         '8gn',
22844         'lowast',
22845         '8gq',
22846         'radic',
22847         '8gt',
22848         'prop',
22849         '8gu',
22850         'infin',
22851         '8h0',
22852         'ang',
22853         '8h7',
22854         'and',
22855         '8h8',
22856         'or',
22857         '8h9',
22858         'cap',
22859         '8ha',
22860         'cup',
22861         '8hb',
22862         'int',
22863         '8hk',
22864         'there4',
22865         '8hs',
22866         'sim',
22867         '8i5',
22868         'cong',
22869         '8i8',
22870         'asymp',
22871         '8j0',
22872         'ne',
22873         '8j1',
22874         'equiv',
22875         '8j4',
22876         'le',
22877         '8j5',
22878         'ge',
22879         '8k2',
22880         'sub',
22881         '8k3',
22882         'sup',
22883         '8k4',
22884         'nsub',
22885         '8k6',
22886         'sube',
22887         '8k7',
22888         'supe',
22889         '8kl',
22890         'oplus',
22891         '8kn',
22892         'otimes',
22893         '8l5',
22894         'perp',
22895         '8m5',
22896         'sdot',
22897         '8o8',
22898         'lceil',
22899         '8o9',
22900         'rceil',
22901         '8oa',
22902         'lfloor',
22903         '8ob',
22904         'rfloor',
22905         '8p9',
22906         'lang',
22907         '8pa',
22908         'rang',
22909         '9ea',
22910         'loz',
22911         '9j0',
22912         'spades',
22913         '9j3',
22914         'clubs',
22915         '9j5',
22916         'hearts',
22917         '9j6',
22918         'diams',
22919         'ai',
22920         'OElig',
22921         'aj',
22922         'oelig',
22923         'b0',
22924         'Scaron',
22925         'b1',
22926         'scaron',
22927         'bo',
22928         'Yuml',
22929         'm6',
22930         'circ',
22931         'ms',
22932         'tilde',
22933         '802',
22934         'ensp',
22935         '803',
22936         'emsp',
22937         '809',
22938         'thinsp',
22939         '80c',
22940         'zwnj',
22941         '80d',
22942         'zwj',
22943         '80e',
22944         'lrm',
22945         '80f',
22946         'rlm',
22947         '80j',
22948         'ndash',
22949         '80k',
22950         'mdash',
22951         '80o',
22952         'lsquo',
22953         '80p',
22954         'rsquo',
22955         '80q',
22956         'sbquo',
22957         '80s',
22958         'ldquo',
22959         '80t',
22960         'rdquo',
22961         '80u',
22962         'bdquo',
22963         '810',
22964         'dagger',
22965         '811',
22966         'Dagger',
22967         '81g',
22968         'permil',
22969         '81p',
22970         'lsaquo',
22971         '81q',
22972         'rsaquo',
22973         '85c',
22974         'euro'
22975     ],
22976
22977          
22978     /**
22979      * Encodes the specified string using raw entities. This means only the required XML base entities will be encoded.
22980      *
22981      * @method encodeRaw
22982      * @param {String} text Text to encode.
22983      * @param {Boolean} attr Optional flag to specify if the text is attribute contents.
22984      * @return {String} Entity encoded text.
22985      */
22986     encodeRaw: function(text, attr)
22987     {
22988         var t = this;
22989         return text.replace(attr ? this.attrsCharsRegExp : this.textCharsRegExp, function(chr) {
22990             return t.baseEntities[chr] || chr;
22991         });
22992     },
22993     /**
22994      * Encoded the specified text with both the attributes and text entities. This function will produce larger text contents
22995      * since it doesn't know if the context is within a attribute or text node. This was added for compatibility
22996      * and is exposed as the DOMUtils.encode function.
22997      *
22998      * @method encodeAllRaw
22999      * @param {String} text Text to encode.
23000      * @return {String} Entity encoded text.
23001      */
23002     encodeAllRaw: function(text) {
23003         var t = this;
23004         return ('' + text).replace(this.rawCharsRegExp, function(chr) {
23005             return t.baseEntities[chr] || chr;
23006         });
23007     },
23008     /**
23009      * Encodes the specified string using numeric entities. The core entities will be
23010      * encoded as named ones but all non lower ascii characters will be encoded into numeric entities.
23011      *
23012      * @method encodeNumeric
23013      * @param {String} text Text to encode.
23014      * @param {Boolean} attr Optional flag to specify if the text is attribute contents.
23015      * @return {String} Entity encoded text.
23016      */
23017     encodeNumeric: function(text, attr) {
23018         var t = this;
23019         return text.replace(attr ? this.attrsCharsRegExp : this.textCharsRegExp, function(chr) {
23020             // Multi byte sequence convert it to a single entity
23021             if (chr.length > 1) {
23022                 return '&#' + (1024 * (chr.charCodeAt(0) - 55296) + (chr.charCodeAt(1) - 56320) + 65536) + ';';
23023             }
23024             return t.baseEntities[chr] || '&#' + chr.charCodeAt(0) + ';';
23025         });
23026     },
23027     /**
23028      * Encodes the specified string using named entities. The core entities will be encoded
23029      * as named ones but all non lower ascii characters will be encoded into named entities.
23030      *
23031      * @method encodeNamed
23032      * @param {String} text Text to encode.
23033      * @param {Boolean} attr Optional flag to specify if the text is attribute contents.
23034      * @param {Object} entities Optional parameter with entities to use.
23035      * @return {String} Entity encoded text.
23036      */
23037     encodeNamed: function(text, attr, entities) {
23038         var t = this;
23039         entities = entities || this.namedEntities;
23040         return text.replace(attr ? this.attrsCharsRegExp : this.textCharsRegExp, function(chr) {
23041             return t.baseEntities[chr] || entities[chr] || chr;
23042         });
23043     },
23044     /**
23045      * Returns an encode function based on the name(s) and it's optional entities.
23046      *
23047      * @method getEncodeFunc
23048      * @param {String} name Comma separated list of encoders for example named,numeric.
23049      * @param {String} entities Optional parameter with entities to use instead of the built in set.
23050      * @return {function} Encode function to be used.
23051      */
23052     getEncodeFunc: function(name, entities) {
23053         entities = this.buildEntitiesLookup(entities) || this.namedEntities;
23054         var t = this;
23055         function encodeNamedAndNumeric(text, attr) {
23056             return text.replace(attr ? t.attrsCharsRegExp : t.textCharsRegExp, function(chr) {
23057                 return t.baseEntities[chr] || entities[chr] || '&#' + chr.charCodeAt(0) + ';' || chr;
23058             });
23059         }
23060
23061         function encodeCustomNamed(text, attr) {
23062             return t.encodeNamed(text, attr, entities);
23063         }
23064         // Replace + with , to be compatible with previous TinyMCE versions
23065         name = this.makeMap(name.replace(/\+/g, ','));
23066         // Named and numeric encoder
23067         if (name.named && name.numeric) {
23068             return this.encodeNamedAndNumeric;
23069         }
23070         // Named encoder
23071         if (name.named) {
23072             // Custom names
23073             if (entities) {
23074                 return encodeCustomNamed;
23075             }
23076             return this.encodeNamed;
23077         }
23078         // Numeric
23079         if (name.numeric) {
23080             return this.encodeNumeric;
23081         }
23082         // Raw encoder
23083         return this.encodeRaw;
23084     },
23085     /**
23086      * Decodes the specified string, this will replace entities with raw UTF characters.
23087      *
23088      * @method decode
23089      * @param {String} text Text to entity decode.
23090      * @return {String} Entity decoded string.
23091      */
23092     decode: function(text)
23093     {
23094         var  t = this;
23095         return text.replace(this.entityRegExp, function(all, numeric) {
23096             if (numeric) {
23097                 numeric = 'x' === numeric.charAt(0).toLowerCase() ? parseInt(numeric.substr(1), 16) : parseInt(numeric, 10);
23098                 // Support upper UTF
23099                 if (numeric > 65535) {
23100                     numeric -= 65536;
23101                     return String.fromCharCode(55296 + (numeric >> 10), 56320 + (1023 & numeric));
23102                 }
23103                 return t.asciiMap[numeric] || String.fromCharCode(numeric);
23104             }
23105             return t.reverseEntities[all] || t.namedEntities[all] || t.nativeDecode(all);
23106         });
23107     },
23108     nativeDecode : function (text) {
23109         return text;
23110     },
23111     makeMap : function (items, delim, map) {
23112                 var i;
23113                 items = items || [];
23114                 delim = delim || ',';
23115                 if (typeof items == "string") {
23116                         items = items.split(delim);
23117                 }
23118                 map = map || {};
23119                 i = items.length;
23120                 while (i--) {
23121                         map[items[i]] = {};
23122                 }
23123                 return map;
23124         }
23125 };
23126     
23127     
23128     
23129 Roo.htmleditor.TidyEntities.init();
23130 /**
23131  * @class Roo.htmleditor.KeyEnter
23132  * Handle Enter press..
23133  * @cfg {Roo.HtmlEditorCore} core the editor.
23134  * @constructor
23135  * Create a new Filter.
23136  * @param {Object} config Configuration options
23137  */
23138
23139
23140
23141
23142
23143 Roo.htmleditor.KeyEnter = function(cfg) {
23144     Roo.apply(this, cfg);
23145     // this does not actually call walk as it's really just a abstract class
23146  
23147     Roo.get(this.core.doc.body).on('keypress', this.keypress, this);
23148 }
23149
23150 //Roo.htmleditor.KeyEnter.i = 0;
23151
23152
23153 Roo.htmleditor.KeyEnter.prototype = {
23154     
23155     core : false,
23156     
23157     keypress : function(e)
23158     {
23159         if (e.charCode != 13 && e.charCode != 10) {
23160             Roo.log([e.charCode,e]);
23161             return true;
23162         }
23163         e.preventDefault();
23164         // https://stackoverflow.com/questions/18552336/prevent-contenteditable-adding-div-on-enter-chrome
23165         var doc = this.core.doc;
23166           //add a new line
23167        
23168     
23169         var sel = this.core.getSelection();
23170         var range = sel.getRangeAt(0);
23171         var n = range.commonAncestorContainer;
23172         var pc = range.closest([ 'ol', 'ul']);
23173         var pli = range.closest('li');
23174         if (!pc || e.ctrlKey) {
23175             sel.insertNode('br', 'after'); 
23176          
23177             this.core.undoManager.addEvent();
23178             this.core.fireEditorEvent(e);
23179             return false;
23180         }
23181         
23182         // deal with <li> insetion
23183         if (pli.innerText.trim() == '' &&
23184             pli.previousSibling &&
23185             pli.previousSibling.nodeName == 'LI' &&
23186             pli.previousSibling.innerText.trim() ==  '') {
23187             pli.parentNode.removeChild(pli.previousSibling);
23188             sel.cursorAfter(pc);
23189             this.core.undoManager.addEvent();
23190             this.core.fireEditorEvent(e);
23191             return false;
23192         }
23193     
23194         var li = doc.createElement('LI');
23195         li.innerHTML = '&nbsp;';
23196         if (!pli || !pli.firstSibling) {
23197             pc.appendChild(li);
23198         } else {
23199             pli.parentNode.insertBefore(li, pli.firstSibling);
23200         }
23201         sel.cursorText (li.firstChild);
23202       
23203         this.core.undoManager.addEvent();
23204         this.core.fireEditorEvent(e);
23205
23206         return false;
23207         
23208     
23209         
23210         
23211          
23212     }
23213 };
23214      
23215 /**
23216  * @class Roo.htmleditor.Block
23217  * Base class for html editor blocks - do not use it directly .. extend it..
23218  * @cfg {DomElement} node The node to apply stuff to.
23219  * @cfg {String} friendly_name the name that appears in the context bar about this block
23220  * @cfg {Object} Context menu - see Roo.form.HtmlEditor.ToolbarContext
23221  
23222  * @constructor
23223  * Create a new Filter.
23224  * @param {Object} config Configuration options
23225  */
23226
23227 Roo.htmleditor.Block  = function(cfg)
23228 {
23229     // do nothing .. should not be called really.
23230 }
23231 /**
23232  * factory method to get the block from an element (using cache if necessary)
23233  * @static
23234  * @param {HtmlElement} the dom element
23235  */
23236 Roo.htmleditor.Block.factory = function(node)
23237 {
23238     var cc = Roo.htmleditor.Block.cache;
23239     var id = Roo.get(node).id;
23240     if (typeof(cc[id]) != 'undefined' && (!cc[id].node || cc[id].node.closest('body'))) {
23241         Roo.htmleditor.Block.cache[id].readElement(node);
23242         return Roo.htmleditor.Block.cache[id];
23243     }
23244     var db  = node.getAttribute('data-block');
23245     if (!db) {
23246         db = node.nodeName.toLowerCase().toUpperCaseFirst();
23247     }
23248     var cls = Roo.htmleditor['Block' + db];
23249     if (typeof(cls) == 'undefined') {
23250         //Roo.log(node.getAttribute('data-block'));
23251         Roo.log("OOps missing block : " + 'Block' + db);
23252         return false;
23253     }
23254     Roo.htmleditor.Block.cache[id] = new cls({ node: node });
23255     return Roo.htmleditor.Block.cache[id];  /// should trigger update element
23256 };
23257
23258 /**
23259  * initalize all Elements from content that are 'blockable'
23260  * @static
23261  * @param the body element
23262  */
23263 Roo.htmleditor.Block.initAll = function(body, type)
23264 {
23265     if (typeof(type) == 'undefined') {
23266         var ia = Roo.htmleditor.Block.initAll;
23267         ia(body,'table');
23268         ia(body,'td');
23269         ia(body,'figure');
23270         return;
23271     }
23272     Roo.each(Roo.get(body).query(type), function(e) {
23273         Roo.htmleditor.Block.factory(e);    
23274     },this);
23275 };
23276 // question goes here... do we need to clear out this cache sometimes?
23277 // or show we make it relivant to the htmleditor.
23278 Roo.htmleditor.Block.cache = {};
23279
23280 Roo.htmleditor.Block.prototype = {
23281     
23282     node : false,
23283     
23284      // used by context menu
23285     friendly_name : 'Based Block',
23286     
23287     // text for button to delete this element
23288     deleteTitle : false,
23289     
23290     context : false,
23291     /**
23292      * Update a node with values from this object
23293      * @param {DomElement} node
23294      */
23295     updateElement : function(node)
23296     {
23297         Roo.DomHelper.update(node === undefined ? this.node : node, this.toObject());
23298     },
23299      /**
23300      * convert to plain HTML for calling insertAtCursor..
23301      */
23302     toHTML : function()
23303     {
23304         return Roo.DomHelper.markup(this.toObject());
23305     },
23306     /**
23307      * used by readEleemnt to extract data from a node
23308      * may need improving as it's pretty basic
23309      
23310      * @param {DomElement} node
23311      * @param {String} tag - tag to find, eg. IMG ?? might be better to use DomQuery ?
23312      * @param {String} attribute (use html - for contents, style for using next param as style, or false to return the node)
23313      * @param {String} style the style property - eg. text-align
23314      */
23315     getVal : function(node, tag, attr, style)
23316     {
23317         var n = node;
23318         if (tag !== true && n.tagName != tag.toUpperCase()) {
23319             // in theory we could do figure[3] << 3rd figure? or some more complex search..?
23320             // but kiss for now.
23321             n = node.getElementsByTagName(tag).item(0);
23322         }
23323         if (!n) {
23324             return '';
23325         }
23326         if (attr === false) {
23327             return n;
23328         }
23329         if (attr == 'html') {
23330             return n.innerHTML;
23331         }
23332         if (attr == 'style') {
23333             return n.style[style]; 
23334         }
23335         
23336         return n.hasAttribute(attr) ? n.getAttribute(attr) : '';
23337             
23338     },
23339     /**
23340      * create a DomHelper friendly object - for use with 
23341      * Roo.DomHelper.markup / overwrite / etc..
23342      * (override this)
23343      */
23344     toObject : function()
23345     {
23346         return {};
23347     },
23348       /**
23349      * Read a node that has a 'data-block' property - and extract the values from it.
23350      * @param {DomElement} node - the node
23351      */
23352     readElement : function(node)
23353     {
23354         
23355     } 
23356     
23357     
23358 };
23359
23360  
23361
23362 /**
23363  * @class Roo.htmleditor.BlockFigure
23364  * Block that has an image and a figcaption
23365  * @cfg {String} image_src the url for the image
23366  * @cfg {String} align (left|right) alignment for the block default left
23367  * @cfg {String} caption the text to appear below  (and in the alt tag)
23368  * @cfg {String} caption_display (block|none) display or not the caption
23369  * @cfg {String|number} image_width the width of the image number or %?
23370  * @cfg {String|number} image_height the height of the image number or %?
23371  * 
23372  * @constructor
23373  * Create a new Filter.
23374  * @param {Object} config Configuration options
23375  */
23376
23377 Roo.htmleditor.BlockFigure = function(cfg)
23378 {
23379     if (cfg.node) {
23380         this.readElement(cfg.node);
23381         this.updateElement(cfg.node);
23382     }
23383     Roo.apply(this, cfg);
23384 }
23385 Roo.extend(Roo.htmleditor.BlockFigure, Roo.htmleditor.Block, {
23386  
23387     
23388     // setable values.
23389     image_src: '',
23390     align: 'center',
23391     caption : '',
23392     caption_display : 'block',
23393     width : '100%',
23394     cls : '',
23395     href: '',
23396     video_url : '',
23397     
23398     // margin: '2%', not used
23399     
23400     text_align: 'left', //   (left|right) alignment for the text caption default left. - not used at present
23401
23402     
23403     // used by context menu
23404     friendly_name : 'Image with caption',
23405     deleteTitle : "Delete Image and Caption",
23406     
23407     contextMenu : function(toolbar)
23408     {
23409         
23410         var block = function() {
23411             return Roo.htmleditor.Block.factory(toolbar.tb.selectedNode);
23412         };
23413         
23414         
23415         var rooui =  typeof(Roo.bootstrap) == 'undefined' ? Roo : Roo.bootstrap;
23416         
23417         var syncValue = toolbar.editorcore.syncValue;
23418         
23419         var fields = {};
23420         
23421         return [
23422              {
23423                 xtype : 'TextItem',
23424                 text : "Source: ",
23425                 xns : rooui.Toolbar  //Boostrap?
23426             },
23427             {
23428                 xtype : 'Button',
23429                 text: 'Change Image URL',
23430                  
23431                 listeners : {
23432                     click: function (btn, state)
23433                     {
23434                         var b = block();
23435                         
23436                         Roo.MessageBox.show({
23437                             title : "Image Source URL",
23438                             msg : "Enter the url for the image",
23439                             buttons: Roo.MessageBox.OKCANCEL,
23440                             fn: function(btn, val){
23441                                 if (btn != 'ok') {
23442                                     return;
23443                                 }
23444                                 b.image_src = val;
23445                                 b.updateElement();
23446                                 syncValue();
23447                                 toolbar.editorcore.onEditorEvent();
23448                             },
23449                             minWidth:250,
23450                             prompt:true,
23451                             //multiline: multiline,
23452                             modal : true,
23453                             value : b.image_src
23454                         });
23455                     }
23456                 },
23457                 xns : rooui.Toolbar
23458             },
23459          
23460             {
23461                 xtype : 'Button',
23462                 text: 'Change Link URL',
23463                  
23464                 listeners : {
23465                     click: function (btn, state)
23466                     {
23467                         var b = block();
23468                         
23469                         Roo.MessageBox.show({
23470                             title : "Link URL",
23471                             msg : "Enter the url for the link - leave blank to have no link",
23472                             buttons: Roo.MessageBox.OKCANCEL,
23473                             fn: function(btn, val){
23474                                 if (btn != 'ok') {
23475                                     return;
23476                                 }
23477                                 b.href = val;
23478                                 b.updateElement();
23479                                 syncValue();
23480                                 toolbar.editorcore.onEditorEvent();
23481                             },
23482                             minWidth:250,
23483                             prompt:true,
23484                             //multiline: multiline,
23485                             modal : true,
23486                             value : b.href
23487                         });
23488                     }
23489                 },
23490                 xns : rooui.Toolbar
23491             },
23492             {
23493                 xtype : 'Button',
23494                 text: 'Show Video URL',
23495                  
23496                 listeners : {
23497                     click: function (btn, state)
23498                     {
23499                         Roo.MessageBox.alert("Video URL",
23500                             block().video_url == '' ? 'This image is not linked ot a video' :
23501                                 'The image is linked to: <a target="_new" href="' + block().video_url + '">' + block().video_url + '</a>');
23502                     }
23503                 },
23504                 xns : rooui.Toolbar
23505             },
23506             
23507             
23508             {
23509                 xtype : 'TextItem',
23510                 text : "Width: ",
23511                 xns : rooui.Toolbar  //Boostrap?
23512             },
23513             {
23514                 xtype : 'ComboBox',
23515                 allowBlank : false,
23516                 displayField : 'val',
23517                 editable : true,
23518                 listWidth : 100,
23519                 triggerAction : 'all',
23520                 typeAhead : true,
23521                 valueField : 'val',
23522                 width : 70,
23523                 name : 'width',
23524                 listeners : {
23525                     select : function (combo, r, index)
23526                     {
23527                         toolbar.editorcore.selectNode(toolbar.tb.selectedNode);
23528                         var b = block();
23529                         b.width = r.get('val');
23530                         b.updateElement();
23531                         syncValue();
23532                         toolbar.editorcore.onEditorEvent();
23533                     }
23534                 },
23535                 xns : rooui.form,
23536                 store : {
23537                     xtype : 'SimpleStore',
23538                     data : [
23539                         ['auto'],
23540                         ['50%'],
23541                         ['80%'],
23542                         ['100%']
23543                     ],
23544                     fields : [ 'val'],
23545                     xns : Roo.data
23546                 }
23547             },
23548             {
23549                 xtype : 'TextItem',
23550                 text : "Align: ",
23551                 xns : rooui.Toolbar  //Boostrap?
23552             },
23553             {
23554                 xtype : 'ComboBox',
23555                 allowBlank : false,
23556                 displayField : 'val',
23557                 editable : true,
23558                 listWidth : 100,
23559                 triggerAction : 'all',
23560                 typeAhead : true,
23561                 valueField : 'val',
23562                 width : 70,
23563                 name : 'align',
23564                 listeners : {
23565                     select : function (combo, r, index)
23566                     {
23567                         toolbar.editorcore.selectNode(toolbar.tb.selectedNode);
23568                         var b = block();
23569                         b.align = r.get('val');
23570                         b.updateElement();
23571                         syncValue();
23572                         toolbar.editorcore.onEditorEvent();
23573                     }
23574                 },
23575                 xns : rooui.form,
23576                 store : {
23577                     xtype : 'SimpleStore',
23578                     data : [
23579                         ['left'],
23580                         ['right'],
23581                         ['center']
23582                     ],
23583                     fields : [ 'val'],
23584                     xns : Roo.data
23585                 }
23586             },
23587             
23588             
23589             {
23590                 xtype : 'Button',
23591                 text: 'Hide Caption',
23592                 name : 'caption_display',
23593                 pressed : false,
23594                 enableToggle : true,
23595                 setValue : function(v) {
23596                     // this trigger toggle.
23597                      
23598                     this.setText(v ? "Hide Caption" : "Show Caption");
23599                     this.setPressed(!v);
23600                 },
23601                 listeners : {
23602                     toggle: function (btn, state)
23603                     {
23604                         var b  = block();
23605                         b.caption_display = b.caption_display == 'block' ? 'none' : 'block';
23606                         this.setText(b.caption_display == 'block' ? "Hide Caption" : "Show Caption");
23607                         b.updateElement();
23608                         syncValue();
23609                         toolbar.editorcore.selectNode(toolbar.tb.selectedNode);
23610                         toolbar.editorcore.onEditorEvent();
23611                     }
23612                 },
23613                 xns : rooui.Toolbar
23614             }
23615         ];
23616         
23617     },
23618     /**
23619      * create a DomHelper friendly object - for use with
23620      * Roo.DomHelper.markup / overwrite / etc..
23621      */
23622     toObject : function()
23623     {
23624         var d = document.createElement('div');
23625         d.innerHTML = this.caption;
23626         
23627         var m = this.width != '100%' && this.align == 'center' ? '0 auto' : 0; 
23628         
23629         var iw = this.align == 'center' ? this.width : '100%';
23630         var img =   {
23631             tag : 'img',
23632             contenteditable : 'false',
23633             src : this.image_src,
23634             alt : d.innerText.replace(/\n/g, " ").replace(/\s+/g, ' ').trim(), // removeHTML and reduce spaces..
23635             style: {
23636                 width : iw,
23637                 maxWidth : iw + ' !important', // this is not getting rendered?
23638                 margin : m  
23639                 
23640             }
23641         };
23642         /*
23643         '<div class="{0}" width="420" height="315" src="{1}" frameborder="0" allowfullscreen>' +
23644                     '<a href="{2}">' + 
23645                         '<img class="{0}-thumbnail" src="{3}/Images/{4}/{5}#image-{4}" />' + 
23646                     '</a>' + 
23647                 '</div>',
23648         */
23649                 
23650         if (this.href.length > 0) {
23651             img = {
23652                 tag : 'a',
23653                 href: this.href,
23654                 contenteditable : 'true',
23655                 cn : [
23656                     img
23657                 ]
23658             };
23659         }
23660         
23661         
23662         if (this.video_url.length > 0) {
23663             img = {
23664                 tag : 'div',
23665                 cls : this.cls,
23666                 frameborder : 0,
23667                 allowfullscreen : true,
23668                 width : 420,  // these are for video tricks - that we replace the outer
23669                 height : 315,
23670                 src : this.video_url,
23671                 cn : [
23672                     img
23673                 ]
23674             };
23675         }
23676         // we remove caption totally if its hidden... - will delete data.. but otherwise we end up with fake caption
23677         var captionhtml = this.caption_display == 'none' ? '' : (this.caption.length ? this.caption : "Caption");
23678         
23679   
23680         var ret =   {
23681             tag: 'figure',
23682             'data-block' : 'Figure',
23683             
23684             contenteditable : 'false',
23685             
23686             style : {
23687                 display: 'block',
23688                 float :  this.align ,
23689                 maxWidth :  this.align == 'center' ? '100% !important' : (this.width + ' !important'),
23690                 width : this.align == 'center' ? '100%' : this.width,
23691                 margin:  '0px',
23692                 padding: this.align == 'center' ? '0' : '0 10px' ,
23693                 textAlign : this.align   // seems to work for email..
23694                 
23695             },
23696            
23697             
23698             align : this.align,
23699             cn : [
23700                 img,
23701               
23702                 {
23703                     tag: 'figcaption',
23704                     'data-display' : this.caption_display,
23705                     style : {
23706                         textAlign : 'left',
23707                         fontSize : '16px',
23708                         lineHeight : '24px',
23709                         display : this.caption_display,
23710                         maxWidth : this.width + ' !important',
23711                         margin: m,
23712                         width: this.width
23713                     
23714                          
23715                     },
23716                     cls : this.cls.length > 0 ? (this.cls  + '-thumbnail' ) : '',
23717                     cn : [
23718                         {
23719                             tag: 'div',
23720                             style  : {
23721                                 marginTop : '16px',
23722                                 textAlign : 'left'
23723                             },
23724                             align: 'left',
23725                             cn : [
23726                                 {
23727                                     // we can not rely on yahoo syndication to use CSS elements - so have to use  '<i>' to encase stuff.
23728                                     tag : 'i',
23729                                     contenteditable : true,
23730                                     html : captionhtml
23731                                 }
23732                                 
23733                             ]
23734                         }
23735                         
23736                     ]
23737                     
23738                 }
23739             ]
23740         };
23741         return ret;
23742          
23743     },
23744     
23745     readElement : function(node)
23746     {
23747         // this should not really come from the link...
23748         this.video_url = this.getVal(node, 'div', 'src');
23749         this.cls = this.getVal(node, 'div', 'class');
23750         this.href = this.getVal(node, 'a', 'href');
23751         
23752         
23753         this.image_src = this.getVal(node, 'img', 'src');
23754          
23755         this.align = this.getVal(node, 'figure', 'align');
23756         var figcaption = this.getVal(node, 'figcaption', false);
23757         this.caption = this.getVal(figcaption, 'i', 'html');
23758
23759         this.caption_display = this.getVal(node, 'figcaption', 'data-display');
23760         //this.text_align = this.getVal(node, 'figcaption', 'style','text-align');
23761         this.width = this.getVal(node, 'figcaption', 'style', 'width');
23762         //this.margin = this.getVal(node, 'figure', 'style', 'margin');
23763         
23764     },
23765     removeNode : function()
23766     {
23767         return this.node;
23768     }
23769     
23770   
23771    
23772      
23773     
23774     
23775     
23776     
23777 })
23778
23779  
23780
23781 /**
23782  * @class Roo.htmleditor.BlockTable
23783  * Block that manages a table
23784  * 
23785  * @constructor
23786  * Create a new Filter.
23787  * @param {Object} config Configuration options
23788  */
23789
23790 Roo.htmleditor.BlockTable = function(cfg)
23791 {
23792     if (cfg.node) {
23793         this.readElement(cfg.node);
23794         this.updateElement(cfg.node);
23795     }
23796     Roo.apply(this, cfg);
23797     if (!cfg.node) {
23798         this.rows = [];
23799         for(var r = 0; r < this.no_row; r++) {
23800             this.rows[r] = [];
23801             for(var c = 0; c < this.no_col; c++) {
23802                 this.rows[r][c] = this.emptyCell();
23803             }
23804         }
23805     }
23806     
23807     
23808 }
23809 Roo.extend(Roo.htmleditor.BlockTable, Roo.htmleditor.Block, {
23810  
23811     rows : false,
23812     no_col : 1,
23813     no_row : 1,
23814     
23815     
23816     width: '100%',
23817     
23818     // used by context menu
23819     friendly_name : 'Table',
23820     deleteTitle : 'Delete Table',
23821     // context menu is drawn once..
23822     
23823     contextMenu : function(toolbar)
23824     {
23825         
23826         var block = function() {
23827             return Roo.htmleditor.Block.factory(toolbar.tb.selectedNode);
23828         };
23829         
23830         
23831         var rooui =  typeof(Roo.bootstrap) == 'undefined' ? Roo : Roo.bootstrap;
23832         
23833         var syncValue = toolbar.editorcore.syncValue;
23834         
23835         var fields = {};
23836         
23837         return [
23838             {
23839                 xtype : 'TextItem',
23840                 text : "Width: ",
23841                 xns : rooui.Toolbar  //Boostrap?
23842             },
23843             {
23844                 xtype : 'ComboBox',
23845                 allowBlank : false,
23846                 displayField : 'val',
23847                 editable : true,
23848                 listWidth : 100,
23849                 triggerAction : 'all',
23850                 typeAhead : true,
23851                 valueField : 'val',
23852                 width : 100,
23853                 name : 'width',
23854                 listeners : {
23855                     select : function (combo, r, index)
23856                     {
23857                         toolbar.editorcore.selectNode(toolbar.tb.selectedNode);
23858                         var b = block();
23859                         b.width = r.get('val');
23860                         b.updateElement();
23861                         syncValue();
23862                         toolbar.editorcore.onEditorEvent();
23863                     }
23864                 },
23865                 xns : rooui.form,
23866                 store : {
23867                     xtype : 'SimpleStore',
23868                     data : [
23869                         ['100%'],
23870                         ['auto']
23871                     ],
23872                     fields : [ 'val'],
23873                     xns : Roo.data
23874                 }
23875             },
23876             // -------- Cols
23877             
23878             {
23879                 xtype : 'TextItem',
23880                 text : "Columns: ",
23881                 xns : rooui.Toolbar  //Boostrap?
23882             },
23883          
23884             {
23885                 xtype : 'Button',
23886                 text: '-',
23887                 listeners : {
23888                     click : function (_self, e)
23889                     {
23890                         toolbar.editorcore.selectNode(toolbar.tb.selectedNode);
23891                         block().removeColumn();
23892                         syncValue();
23893                         toolbar.editorcore.onEditorEvent();
23894                     }
23895                 },
23896                 xns : rooui.Toolbar
23897             },
23898             {
23899                 xtype : 'Button',
23900                 text: '+',
23901                 listeners : {
23902                     click : function (_self, e)
23903                     {
23904                         toolbar.editorcore.selectNode(toolbar.tb.selectedNode);
23905                         block().addColumn();
23906                         syncValue();
23907                         toolbar.editorcore.onEditorEvent();
23908                     }
23909                 },
23910                 xns : rooui.Toolbar
23911             },
23912             // -------- ROWS
23913             {
23914                 xtype : 'TextItem',
23915                 text : "Rows: ",
23916                 xns : rooui.Toolbar  //Boostrap?
23917             },
23918          
23919             {
23920                 xtype : 'Button',
23921                 text: '-',
23922                 listeners : {
23923                     click : function (_self, e)
23924                     {
23925                         toolbar.editorcore.selectNode(toolbar.tb.selectedNode);
23926                         block().removeRow();
23927                         syncValue();
23928                         toolbar.editorcore.onEditorEvent();
23929                     }
23930                 },
23931                 xns : rooui.Toolbar
23932             },
23933             {
23934                 xtype : 'Button',
23935                 text: '+',
23936                 listeners : {
23937                     click : function (_self, e)
23938                     {
23939                         block().addRow();
23940                         syncValue();
23941                         toolbar.editorcore.onEditorEvent();
23942                     }
23943                 },
23944                 xns : rooui.Toolbar
23945             },
23946             // -------- ROWS
23947             {
23948                 xtype : 'Button',
23949                 text: 'Reset Column Widths',
23950                 listeners : {
23951                     
23952                     click : function (_self, e)
23953                     {
23954                         block().resetWidths();
23955                         syncValue();
23956                         toolbar.editorcore.onEditorEvent();
23957                     }
23958                 },
23959                 xns : rooui.Toolbar
23960             } 
23961             
23962             
23963             
23964         ];
23965         
23966     },
23967     
23968     
23969   /**
23970      * create a DomHelper friendly object - for use with
23971      * Roo.DomHelper.markup / overwrite / etc..
23972      * ?? should it be called with option to hide all editing features?
23973      */
23974     toObject : function()
23975     {
23976         
23977         var ret = {
23978             tag : 'table',
23979             contenteditable : 'false', // this stops cell selection from picking the table.
23980             'data-block' : 'Table',
23981             style : {
23982                 width:  this.width,
23983                 border : 'solid 1px #000', // ??? hard coded?
23984                 'border-collapse' : 'collapse' 
23985             },
23986             cn : [
23987                 { tag : 'tbody' , cn : [] }
23988             ]
23989         };
23990         
23991         // do we have a head = not really 
23992         var ncols = 0;
23993         Roo.each(this.rows, function( row ) {
23994             var tr = {
23995                 tag: 'tr',
23996                 style : {
23997                     margin: '6px',
23998                     border : 'solid 1px #000',
23999                     textAlign : 'left' 
24000                 },
24001                 cn : [ ]
24002             };
24003             
24004             ret.cn[0].cn.push(tr);
24005             // does the row have any properties? ?? height?
24006             var nc = 0;
24007             Roo.each(row, function( cell ) {
24008                 
24009                 var td = {
24010                     tag : 'td',
24011                     contenteditable :  'true',
24012                     'data-block' : 'Td',
24013                     html : cell.html,
24014                     style : cell.style
24015                 };
24016                 if (cell.colspan > 1) {
24017                     td.colspan = cell.colspan ;
24018                     nc += cell.colspan;
24019                 } else {
24020                     nc++;
24021                 }
24022                 if (cell.rowspan > 1) {
24023                     td.rowspan = cell.rowspan ;
24024                 }
24025                 
24026                 
24027                 // widths ?
24028                 tr.cn.push(td);
24029                     
24030                 
24031             }, this);
24032             ncols = Math.max(nc, ncols);
24033             
24034             
24035         }, this);
24036         // add the header row..
24037         
24038         ncols++;
24039          
24040         
24041         return ret;
24042          
24043     },
24044     
24045     readElement : function(node)
24046     {
24047         node  = node ? node : this.node ;
24048         this.width = this.getVal(node, true, 'style', 'width') || '100%';
24049         
24050         this.rows = [];
24051         this.no_row = 0;
24052         var trs = Array.from(node.rows);
24053         trs.forEach(function(tr) {
24054             var row =  [];
24055             this.rows.push(row);
24056             
24057             this.no_row++;
24058             var no_column = 0;
24059             Array.from(tr.cells).forEach(function(td) {
24060                 
24061                 var add = {
24062                     colspan : td.hasAttribute('colspan') ? td.getAttribute('colspan')*1 : 1,
24063                     rowspan : td.hasAttribute('rowspan') ? td.getAttribute('rowspan')*1 : 1,
24064                     style : td.hasAttribute('style') ? td.getAttribute('style') : '',
24065                     html : td.innerHTML
24066                 };
24067                 no_column += add.colspan;
24068                      
24069                 
24070                 row.push(add);
24071                 
24072                 
24073             },this);
24074             this.no_col = Math.max(this.no_col, no_column);
24075             
24076             
24077         },this);
24078         
24079         
24080     },
24081     normalizeRows: function()
24082     {
24083         var ret= [];
24084         var rid = -1;
24085         this.rows.forEach(function(row) {
24086             rid++;
24087             ret[rid] = [];
24088             row = this.normalizeRow(row);
24089             var cid = 0;
24090             row.forEach(function(c) {
24091                 while (typeof(ret[rid][cid]) != 'undefined') {
24092                     cid++;
24093                 }
24094                 if (typeof(ret[rid]) == 'undefined') {
24095                     ret[rid] = [];
24096                 }
24097                 ret[rid][cid] = c;
24098                 c.row = rid;
24099                 c.col = cid;
24100                 if (c.rowspan < 2) {
24101                     return;
24102                 }
24103                 
24104                 for(var i = 1 ;i < c.rowspan; i++) {
24105                     if (typeof(ret[rid+i]) == 'undefined') {
24106                         ret[rid+i] = [];
24107                     }
24108                     ret[rid+i][cid] = c;
24109                 }
24110             });
24111         }, this);
24112         return ret;
24113     
24114     },
24115     
24116     normalizeRow: function(row)
24117     {
24118         var ret= [];
24119         row.forEach(function(c) {
24120             if (c.colspan < 2) {
24121                 ret.push(c);
24122                 return;
24123             }
24124             for(var i =0 ;i < c.colspan; i++) {
24125                 ret.push(c);
24126             }
24127         });
24128         return ret;
24129     
24130     },
24131     
24132     deleteColumn : function(sel)
24133     {
24134         if (!sel || sel.type != 'col') {
24135             return;
24136         }
24137         if (this.no_col < 2) {
24138             return;
24139         }
24140         
24141         this.rows.forEach(function(row) {
24142             var cols = this.normalizeRow(row);
24143             var col = cols[sel.col];
24144             if (col.colspan > 1) {
24145                 col.colspan --;
24146             } else {
24147                 row.remove(col);
24148             }
24149             
24150         }, this);
24151         this.no_col--;
24152         
24153     },
24154     removeColumn : function()
24155     {
24156         this.deleteColumn({
24157             type: 'col',
24158             col : this.no_col-1
24159         });
24160         this.updateElement();
24161     },
24162     
24163      
24164     addColumn : function()
24165     {
24166         
24167         this.rows.forEach(function(row) {
24168             row.push(this.emptyCell());
24169            
24170         }, this);
24171         this.updateElement();
24172     },
24173     
24174     deleteRow : function(sel)
24175     {
24176         if (!sel || sel.type != 'row') {
24177             return;
24178         }
24179         
24180         if (this.no_row < 2) {
24181             return;
24182         }
24183         
24184         var rows = this.normalizeRows();
24185         
24186         
24187         rows[sel.row].forEach(function(col) {
24188             if (col.rowspan > 1) {
24189                 col.rowspan--;
24190             } else {
24191                 col.remove = 1; // flage it as removed.
24192             }
24193             
24194         }, this);
24195         var newrows = [];
24196         this.rows.forEach(function(row) {
24197             newrow = [];
24198             row.forEach(function(c) {
24199                 if (typeof(c.remove) == 'undefined') {
24200                     newrow.push(c);
24201                 }
24202                 
24203             });
24204             if (newrow.length > 0) {
24205                 newrows.push(row);
24206             }
24207         });
24208         this.rows =  newrows;
24209         
24210         
24211         
24212         this.no_row--;
24213         this.updateElement();
24214         
24215     },
24216     removeRow : function()
24217     {
24218         this.deleteRow({
24219             type: 'row',
24220             row : this.no_row-1
24221         });
24222         
24223     },
24224     
24225      
24226     addRow : function()
24227     {
24228         
24229         var row = [];
24230         for (var i = 0; i < this.no_col; i++ ) {
24231             
24232             row.push(this.emptyCell());
24233            
24234         }
24235         this.rows.push(row);
24236         this.updateElement();
24237         
24238     },
24239      
24240     // the default cell object... at present...
24241     emptyCell : function() {
24242         return (new Roo.htmleditor.BlockTd({})).toObject();
24243         
24244      
24245     },
24246     
24247     removeNode : function()
24248     {
24249         return this.node;
24250     },
24251     
24252     
24253     
24254     resetWidths : function()
24255     {
24256         Array.from(this.node.getElementsByTagName('td')).forEach(function(n) {
24257             var nn = Roo.htmleditor.Block.factory(n);
24258             nn.width = '';
24259             nn.updateElement(n);
24260         });
24261     }
24262     
24263     
24264     
24265     
24266 })
24267
24268 /**
24269  *
24270  * editing a TD?
24271  *
24272  * since selections really work on the table cell, then editing really should work from there
24273  *
24274  * The original plan was to support merging etc... - but that may not be needed yet..
24275  *
24276  * So this simple version will support:
24277  *   add/remove cols
24278  *   adjust the width +/-
24279  *   reset the width...
24280  *   
24281  *
24282  */
24283
24284
24285  
24286
24287 /**
24288  * @class Roo.htmleditor.BlockTable
24289  * Block that manages a table
24290  * 
24291  * @constructor
24292  * Create a new Filter.
24293  * @param {Object} config Configuration options
24294  */
24295
24296 Roo.htmleditor.BlockTd = function(cfg)
24297 {
24298     if (cfg.node) {
24299         this.readElement(cfg.node);
24300         this.updateElement(cfg.node);
24301     }
24302     Roo.apply(this, cfg);
24303      
24304     
24305     
24306 }
24307 Roo.extend(Roo.htmleditor.BlockTd, Roo.htmleditor.Block, {
24308  
24309     node : false,
24310     
24311     width: '',
24312     textAlign : 'left',
24313     valign : 'top',
24314     
24315     colspan : 1,
24316     rowspan : 1,
24317     
24318     
24319     // used by context menu
24320     friendly_name : 'Table Cell',
24321     deleteTitle : false, // use our customer delete
24322     
24323     // context menu is drawn once..
24324     
24325     contextMenu : function(toolbar)
24326     {
24327         
24328         var cell = function() {
24329             return Roo.htmleditor.Block.factory(toolbar.tb.selectedNode);
24330         };
24331         
24332         var table = function() {
24333             return Roo.htmleditor.Block.factory(toolbar.tb.selectedNode.closest('table'));
24334         };
24335         
24336         var lr = false;
24337         var saveSel = function()
24338         {
24339             lr = toolbar.editorcore.getSelection().getRangeAt(0);
24340         }
24341         var restoreSel = function()
24342         {
24343             if (lr) {
24344                 (function() {
24345                     toolbar.editorcore.focus();
24346                     var cr = toolbar.editorcore.getSelection();
24347                     cr.removeAllRanges();
24348                     cr.addRange(lr);
24349                     toolbar.editorcore.onEditorEvent();
24350                 }).defer(10, this);
24351                 
24352                 
24353             }
24354         }
24355         
24356         var rooui =  typeof(Roo.bootstrap) == 'undefined' ? Roo : Roo.bootstrap;
24357         
24358         var syncValue = toolbar.editorcore.syncValue;
24359         
24360         var fields = {};
24361         
24362         return [
24363             {
24364                 xtype : 'Button',
24365                 text : 'Edit Table',
24366                 listeners : {
24367                     click : function() {
24368                         var t = toolbar.tb.selectedNode.closest('table');
24369                         toolbar.editorcore.selectNode(t);
24370                         toolbar.editorcore.onEditorEvent();                        
24371                     }
24372                 }
24373                 
24374             },
24375               
24376            
24377              
24378             {
24379                 xtype : 'TextItem',
24380                 text : "Column Width: ",
24381                  xns : rooui.Toolbar 
24382                
24383             },
24384             {
24385                 xtype : 'Button',
24386                 text: '-',
24387                 listeners : {
24388                     click : function (_self, e)
24389                     {
24390                         toolbar.editorcore.selectNode(toolbar.tb.selectedNode);
24391                         cell().shrinkColumn();
24392                         syncValue();
24393                          toolbar.editorcore.onEditorEvent();
24394                     }
24395                 },
24396                 xns : rooui.Toolbar
24397             },
24398             {
24399                 xtype : 'Button',
24400                 text: '+',
24401                 listeners : {
24402                     click : function (_self, e)
24403                     {
24404                         toolbar.editorcore.selectNode(toolbar.tb.selectedNode);
24405                         cell().growColumn();
24406                         syncValue();
24407                         toolbar.editorcore.onEditorEvent();
24408                     }
24409                 },
24410                 xns : rooui.Toolbar
24411             },
24412             
24413             {
24414                 xtype : 'TextItem',
24415                 text : "Vertical Align: ",
24416                 xns : rooui.Toolbar  //Boostrap?
24417             },
24418             {
24419                 xtype : 'ComboBox',
24420                 allowBlank : false,
24421                 displayField : 'val',
24422                 editable : true,
24423                 listWidth : 100,
24424                 triggerAction : 'all',
24425                 typeAhead : true,
24426                 valueField : 'val',
24427                 width : 100,
24428                 name : 'valign',
24429                 listeners : {
24430                     select : function (combo, r, index)
24431                     {
24432                         toolbar.editorcore.selectNode(toolbar.tb.selectedNode);
24433                         var b = cell();
24434                         b.valign = r.get('val');
24435                         b.updateElement();
24436                         syncValue();
24437                         toolbar.editorcore.onEditorEvent();
24438                     }
24439                 },
24440                 xns : rooui.form,
24441                 store : {
24442                     xtype : 'SimpleStore',
24443                     data : [
24444                         ['top'],
24445                         ['middle'],
24446                         ['bottom'] // there are afew more... 
24447                     ],
24448                     fields : [ 'val'],
24449                     xns : Roo.data
24450                 }
24451             },
24452             
24453             {
24454                 xtype : 'TextItem',
24455                 text : "Merge Cells: ",
24456                  xns : rooui.Toolbar 
24457                
24458             },
24459             
24460             
24461             {
24462                 xtype : 'Button',
24463                 text: 'Right',
24464                 listeners : {
24465                     click : function (_self, e)
24466                     {
24467                         toolbar.editorcore.selectNode(toolbar.tb.selectedNode);
24468                         cell().mergeRight();
24469                         //block().growColumn();
24470                         syncValue();
24471                         toolbar.editorcore.onEditorEvent();
24472                     }
24473                 },
24474                 xns : rooui.Toolbar
24475             },
24476              
24477             {
24478                 xtype : 'Button',
24479                 text: 'Below',
24480                 listeners : {
24481                     click : function (_self, e)
24482                     {
24483                         toolbar.editorcore.selectNode(toolbar.tb.selectedNode);
24484                         cell().mergeBelow();
24485                         //block().growColumn();
24486                         syncValue();
24487                         toolbar.editorcore.onEditorEvent();
24488                     }
24489                 },
24490                 xns : rooui.Toolbar
24491             },
24492             {
24493                 xtype : 'TextItem',
24494                 text : "| ",
24495                  xns : rooui.Toolbar 
24496                
24497             },
24498             
24499             {
24500                 xtype : 'Button',
24501                 text: 'Split',
24502                 listeners : {
24503                     click : function (_self, e)
24504                     {
24505                         //toolbar.editorcore.selectNode(toolbar.tb.selectedNode);
24506                         cell().split();
24507                         syncValue();
24508                         toolbar.editorcore.selectNode(toolbar.tb.selectedNode);
24509                         toolbar.editorcore.onEditorEvent();
24510                                              
24511                     }
24512                 },
24513                 xns : rooui.Toolbar
24514             },
24515             {
24516                 xtype : 'Fill',
24517                 xns : rooui.Toolbar 
24518                
24519             },
24520         
24521           
24522             {
24523                 xtype : 'Button',
24524                 text: 'Delete',
24525                  
24526                 xns : rooui.Toolbar,
24527                 menu : {
24528                     xtype : 'Menu',
24529                     xns : rooui.menu,
24530                     items : [
24531                         {
24532                             xtype : 'Item',
24533                             html: 'Column',
24534                             listeners : {
24535                                 click : function (_self, e)
24536                                 {
24537                                     var t = table();
24538                                     
24539                                     cell().deleteColumn();
24540                                     syncValue();
24541                                     toolbar.editorcore.selectNode(t.node);
24542                                     toolbar.editorcore.onEditorEvent();   
24543                                 }
24544                             },
24545                             xns : rooui.menu
24546                         },
24547                         {
24548                             xtype : 'Item',
24549                             html: 'Row',
24550                             listeners : {
24551                                 click : function (_self, e)
24552                                 {
24553                                     var t = table();
24554                                     cell().deleteRow();
24555                                     syncValue();
24556                                     
24557                                     toolbar.editorcore.selectNode(t.node);
24558                                     toolbar.editorcore.onEditorEvent();   
24559                                                          
24560                                 }
24561                             },
24562                             xns : rooui.menu
24563                         },
24564                        {
24565                             xtype : 'Separator',
24566                             xns : rooui.menu
24567                         },
24568                         {
24569                             xtype : 'Item',
24570                             html: 'Table',
24571                             listeners : {
24572                                 click : function (_self, e)
24573                                 {
24574                                     var t = table();
24575                                     var nn = t.node.nextSibling || t.node.previousSibling;
24576                                     t.node.parentNode.removeChild(t.node);
24577                                     if (nn) { 
24578                                         toolbar.editorcore.selectNode(nn, true);
24579                                     }
24580                                     toolbar.editorcore.onEditorEvent();   
24581                                                          
24582                                 }
24583                             },
24584                             xns : rooui.menu
24585                         }
24586                     ]
24587                 }
24588             }
24589             
24590             // align... << fixme
24591             
24592         ];
24593         
24594     },
24595     
24596     
24597   /**
24598      * create a DomHelper friendly object - for use with
24599      * Roo.DomHelper.markup / overwrite / etc..
24600      * ?? should it be called with option to hide all editing features?
24601      */
24602  /**
24603      * create a DomHelper friendly object - for use with
24604      * Roo.DomHelper.markup / overwrite / etc..
24605      * ?? should it be called with option to hide all editing features?
24606      */
24607     toObject : function()
24608     {
24609         
24610         var ret = {
24611             tag : 'td',
24612             contenteditable : 'true', // this stops cell selection from picking the table.
24613             'data-block' : 'Td',
24614             valign : this.valign,
24615             style : {  
24616                 'text-align' :  this.textAlign,
24617                 border : 'solid 1px rgb(0, 0, 0)', // ??? hard coded?
24618                 'border-collapse' : 'collapse',
24619                 padding : '6px', // 8 for desktop / 4 for mobile
24620                 'vertical-align': this.valign
24621             },
24622             html : this.html
24623         };
24624         if (this.width != '') {
24625             ret.width = this.width;
24626             ret.style.width = this.width;
24627         }
24628         
24629         
24630         if (this.colspan > 1) {
24631             ret.colspan = this.colspan ;
24632         } 
24633         if (this.rowspan > 1) {
24634             ret.rowspan = this.rowspan ;
24635         }
24636         
24637            
24638         
24639         return ret;
24640          
24641     },
24642     
24643     readElement : function(node)
24644     {
24645         node  = node ? node : this.node ;
24646         this.width = node.style.width;
24647         this.colspan = Math.max(1,1*node.getAttribute('colspan'));
24648         this.rowspan = Math.max(1,1*node.getAttribute('rowspan'));
24649         this.html = node.innerHTML;
24650         
24651         
24652     },
24653      
24654     // the default cell object... at present...
24655     emptyCell : function() {
24656         return {
24657             colspan :  1,
24658             rowspan :  1,
24659             textAlign : 'left',
24660             html : "&nbsp;" // is this going to be editable now?
24661         };
24662      
24663     },
24664     
24665     removeNode : function()
24666     {
24667         return this.node.closest('table');
24668          
24669     },
24670     
24671     cellData : false,
24672     
24673     colWidths : false,
24674     
24675     toTableArray  : function()
24676     {
24677         var ret = [];
24678         var tab = this.node.closest('tr').closest('table');
24679         Array.from(tab.rows).forEach(function(r, ri){
24680             ret[ri] = [];
24681         });
24682         var rn = 0;
24683         this.colWidths = [];
24684         var all_auto = true;
24685         Array.from(tab.rows).forEach(function(r, ri){
24686             
24687             var cn = 0;
24688             Array.from(r.cells).forEach(function(ce, ci){
24689                 var c =  {
24690                     cell : ce,
24691                     row : rn,
24692                     col: cn,
24693                     colspan : ce.colSpan,
24694                     rowspan : ce.rowSpan
24695                 };
24696                 if (ce.isEqualNode(this.node)) {
24697                     this.cellData = c;
24698                 }
24699                 // if we have been filled up by a row?
24700                 if (typeof(ret[rn][cn]) != 'undefined') {
24701                     while(typeof(ret[rn][cn]) != 'undefined') {
24702                         cn++;
24703                     }
24704                     c.col = cn;
24705                 }
24706                 
24707                 if (typeof(this.colWidths[cn]) == 'undefined') {
24708                     this.colWidths[cn] =   ce.style.width;
24709                     if (this.colWidths[cn] != '') {
24710                         all_auto = false;
24711                     }
24712                 }
24713                 
24714                 
24715                 if (c.colspan < 2 && c.rowspan < 2 ) {
24716                     ret[rn][cn] = c;
24717                     cn++;
24718                     return;
24719                 }
24720                 for(var j = 0; j < c.rowspan; j++) {
24721                     if (typeof(ret[rn+j]) == 'undefined') {
24722                         continue; // we have a problem..
24723                     }
24724                     ret[rn+j][cn] = c;
24725                     for(var i = 0; i < c.colspan; i++) {
24726                         ret[rn+j][cn+i] = c;
24727                     }
24728                 }
24729                 
24730                 cn += c.colspan;
24731             }, this);
24732             rn++;
24733         }, this);
24734         
24735         // initalize widths.?
24736         // either all widths or no widths..
24737         if (all_auto) {
24738             this.colWidths[0] = false; // no widths flag.
24739         }
24740         
24741         
24742         return ret;
24743         
24744     },
24745     
24746     
24747     
24748     
24749     mergeRight: function()
24750     {
24751          
24752         // get the contents of the next cell along..
24753         var tr = this.node.closest('tr');
24754         var i = Array.prototype.indexOf.call(tr.childNodes, this.node);
24755         if (i >= tr.childNodes.length - 1) {
24756             return; // no cells on right to merge with.
24757         }
24758         var table = this.toTableArray();
24759         
24760         if (typeof(table[this.cellData.row][this.cellData.col+this.cellData.colspan]) == 'undefined') {
24761             return; // nothing right?
24762         }
24763         var rc = table[this.cellData.row][this.cellData.col+this.cellData.colspan];
24764         // right cell - must be same rowspan and on the same row.
24765         if (rc.rowspan != this.cellData.rowspan || rc.row != this.cellData.row) {
24766             return; // right hand side is not same rowspan.
24767         }
24768         
24769         
24770         
24771         this.node.innerHTML += ' ' + rc.cell.innerHTML;
24772         tr.removeChild(rc.cell);
24773         this.colspan += rc.colspan;
24774         this.node.setAttribute('colspan', this.colspan);
24775
24776     },
24777     
24778     
24779     mergeBelow : function()
24780     {
24781         var table = this.toTableArray();
24782         if (typeof(table[this.cellData.row+this.cellData.rowspan]) == 'undefined') {
24783             return; // no row below
24784         }
24785         if (typeof(table[this.cellData.row+this.cellData.rowspan][this.cellData.col]) == 'undefined') {
24786             return; // nothing right?
24787         }
24788         var rc = table[this.cellData.row+this.cellData.rowspan][this.cellData.col];
24789         
24790         if (rc.colspan != this.cellData.colspan || rc.col != this.cellData.col) {
24791             return; // right hand side is not same rowspan.
24792         }
24793         this.node.innerHTML =  this.node.innerHTML + rc.cell.innerHTML ;
24794         rc.cell.parentNode.removeChild(rc.cell);
24795         this.rowspan += rc.rowspan;
24796         this.node.setAttribute('rowspan', this.rowspan);
24797     },
24798     
24799     split: function()
24800     {
24801         if (this.node.rowSpan < 2 && this.node.colSpan < 2) {
24802             return;
24803         }
24804         var table = this.toTableArray();
24805         var cd = this.cellData;
24806         this.rowspan = 1;
24807         this.colspan = 1;
24808         
24809         for(var r = cd.row; r < cd.row + cd.rowspan; r++) {
24810             
24811             
24812             
24813             for(var c = cd.col; c < cd.col + cd.colspan; c++) {
24814                 if (r == cd.row && c == cd.col) {
24815                     this.node.removeAttribute('rowspan');
24816                     this.node.removeAttribute('colspan');
24817                     continue;
24818                 }
24819                  
24820                 var ntd = this.node.cloneNode(); // which col/row should be 0..
24821                 ntd.removeAttribute('id'); //
24822                 //ntd.style.width  = '';
24823                 ntd.innerHTML = '';
24824                 table[r][c] = { cell : ntd, col : c, row: r , colspan : 1 , rowspan : 1   };
24825             }
24826             
24827         }
24828         this.redrawAllCells(table);
24829         
24830          
24831         
24832     },
24833     
24834     
24835     
24836     redrawAllCells: function(table)
24837     {
24838         
24839          
24840         var tab = this.node.closest('tr').closest('table');
24841         var ctr = tab.rows[0].parentNode;
24842         Array.from(tab.rows).forEach(function(r, ri){
24843             
24844             Array.from(r.cells).forEach(function(ce, ci){
24845                 ce.parentNode.removeChild(ce);
24846             });
24847             r.parentNode.removeChild(r);
24848         });
24849         for(var r = 0 ; r < table.length; r++) {
24850             var re = tab.rows[r];
24851             
24852             var re = tab.ownerDocument.createElement('tr');
24853             ctr.appendChild(re);
24854             for(var c = 0 ; c < table[r].length; c++) {
24855                 if (table[r][c].cell === false) {
24856                     continue;
24857                 }
24858                 
24859                 re.appendChild(table[r][c].cell);
24860                  
24861                 table[r][c].cell = false;
24862             }
24863         }
24864         
24865     },
24866     updateWidths : function(table)
24867     {
24868         for(var r = 0 ; r < table.length; r++) {
24869            
24870             for(var c = 0 ; c < table[r].length; c++) {
24871                 if (table[r][c].cell === false) {
24872                     continue;
24873                 }
24874                 
24875                 if (this.colWidths[0] != false && table[r][c].colspan < 2) {
24876                     var el = Roo.htmleditor.Block.factory(table[r][c].cell);
24877                     el.width = Math.floor(this.colWidths[c])  +'%';
24878                     el.updateElement(el.node);
24879                 }
24880                 table[r][c].cell = false; // done
24881             }
24882         }
24883     },
24884     normalizeWidths : function(table)
24885     {
24886     
24887         if (this.colWidths[0] === false) {
24888             var nw = 100.0 / this.colWidths.length;
24889             this.colWidths.forEach(function(w,i) {
24890                 this.colWidths[i] = nw;
24891             },this);
24892             return;
24893         }
24894     
24895         var t = 0, missing = [];
24896         
24897         this.colWidths.forEach(function(w,i) {
24898             //if you mix % and
24899             this.colWidths[i] = this.colWidths[i] == '' ? 0 : (this.colWidths[i]+'').replace(/[^0-9]+/g,'')*1;
24900             var add =  this.colWidths[i];
24901             if (add > 0) {
24902                 t+=add;
24903                 return;
24904             }
24905             missing.push(i);
24906             
24907             
24908         },this);
24909         var nc = this.colWidths.length;
24910         if (missing.length) {
24911             var mult = (nc - missing.length) / (1.0 * nc);
24912             var t = mult * t;
24913             var ew = (100 -t) / (1.0 * missing.length);
24914             this.colWidths.forEach(function(w,i) {
24915                 if (w > 0) {
24916                     this.colWidths[i] = w * mult;
24917                     return;
24918                 }
24919                 
24920                 this.colWidths[i] = ew;
24921             }, this);
24922             // have to make up numbers..
24923              
24924         }
24925         // now we should have all the widths..
24926         
24927     
24928     },
24929     
24930     shrinkColumn : function()
24931     {
24932         var table = this.toTableArray();
24933         this.normalizeWidths(table);
24934         var col = this.cellData.col;
24935         var nw = this.colWidths[col] * 0.8;
24936         if (nw < 5) {
24937             return;
24938         }
24939         var otherAdd = (this.colWidths[col]  * 0.2) / (this.colWidths.length -1);
24940         this.colWidths.forEach(function(w,i) {
24941             if (i == col) {
24942                  this.colWidths[i] = nw;
24943                 return;
24944             }
24945             this.colWidths[i] += otherAdd
24946         }, this);
24947         this.updateWidths(table);
24948          
24949     },
24950     growColumn : function()
24951     {
24952         var table = this.toTableArray();
24953         this.normalizeWidths(table);
24954         var col = this.cellData.col;
24955         var nw = this.colWidths[col] * 1.2;
24956         if (nw > 90) {
24957             return;
24958         }
24959         var otherSub = (this.colWidths[col]  * 0.2) / (this.colWidths.length -1);
24960         this.colWidths.forEach(function(w,i) {
24961             if (i == col) {
24962                 this.colWidths[i] = nw;
24963                 return;
24964             }
24965             this.colWidths[i] -= otherSub
24966         }, this);
24967         this.updateWidths(table);
24968          
24969     },
24970     deleteRow : function()
24971     {
24972         // delete this rows 'tr'
24973         // if any of the cells in this row have a rowspan > 1 && row!= this row..
24974         // then reduce the rowspan.
24975         var table = this.toTableArray();
24976         // this.cellData.row;
24977         for (var i =0;i< table[this.cellData.row].length ; i++) {
24978             var c = table[this.cellData.row][i];
24979             if (c.row != this.cellData.row) {
24980                 
24981                 c.rowspan--;
24982                 c.cell.setAttribute('rowspan', c.rowspan);
24983                 continue;
24984             }
24985             if (c.rowspan > 1) {
24986                 c.rowspan--;
24987                 c.cell.setAttribute('rowspan', c.rowspan);
24988             }
24989         }
24990         table.splice(this.cellData.row,1);
24991         this.redrawAllCells(table);
24992         
24993     },
24994     deleteColumn : function()
24995     {
24996         var table = this.toTableArray();
24997         
24998         for (var i =0;i< table.length ; i++) {
24999             var c = table[i][this.cellData.col];
25000             if (c.col != this.cellData.col) {
25001                 table[i][this.cellData.col].colspan--;
25002             } else if (c.colspan > 1) {
25003                 c.colspan--;
25004                 c.cell.setAttribute('colspan', c.colspan);
25005             }
25006             table[i].splice(this.cellData.col,1);
25007         }
25008         
25009         this.redrawAllCells(table);
25010     }
25011     
25012     
25013     
25014     
25015 })
25016
25017 //<script type="text/javascript">
25018
25019 /*
25020  * Based  Ext JS Library 1.1.1
25021  * Copyright(c) 2006-2007, Ext JS, LLC.
25022  * LGPL
25023  *
25024  */
25025  
25026 /**
25027  * @class Roo.HtmlEditorCore
25028  * @extends Roo.Component
25029  * Provides a the editing component for the HTML editors in Roo. (bootstrap and Roo.form)
25030  *
25031  * any element that has display set to 'none' can cause problems in Safari and Firefox.<br/><br/>
25032  */
25033
25034 Roo.HtmlEditorCore = function(config){
25035     
25036     
25037     Roo.HtmlEditorCore.superclass.constructor.call(this, config);
25038     
25039     
25040     this.addEvents({
25041         /**
25042          * @event initialize
25043          * Fires when the editor is fully initialized (including the iframe)
25044          * @param {Roo.HtmlEditorCore} this
25045          */
25046         initialize: true,
25047         /**
25048          * @event activate
25049          * Fires when the editor is first receives the focus. Any insertion must wait
25050          * until after this event.
25051          * @param {Roo.HtmlEditorCore} this
25052          */
25053         activate: true,
25054          /**
25055          * @event beforesync
25056          * Fires before the textarea is updated with content from the editor iframe. Return false
25057          * to cancel the sync.
25058          * @param {Roo.HtmlEditorCore} this
25059          * @param {String} html
25060          */
25061         beforesync: true,
25062          /**
25063          * @event beforepush
25064          * Fires before the iframe editor is updated with content from the textarea. Return false
25065          * to cancel the push.
25066          * @param {Roo.HtmlEditorCore} this
25067          * @param {String} html
25068          */
25069         beforepush: true,
25070          /**
25071          * @event sync
25072          * Fires when the textarea is updated with content from the editor iframe.
25073          * @param {Roo.HtmlEditorCore} this
25074          * @param {String} html
25075          */
25076         sync: true,
25077          /**
25078          * @event push
25079          * Fires when the iframe editor is updated with content from the textarea.
25080          * @param {Roo.HtmlEditorCore} this
25081          * @param {String} html
25082          */
25083         push: true,
25084         
25085         /**
25086          * @event editorevent
25087          * Fires when on any editor (mouse up/down cursor movement etc.) - used for toolbar hooks.
25088          * @param {Roo.HtmlEditorCore} this
25089          */
25090         editorevent: true 
25091          
25092         
25093     });
25094     
25095     // at this point this.owner is set, so we can start working out the whitelisted / blacklisted elements
25096     
25097     // defaults : white / black...
25098     this.applyBlacklists();
25099     
25100     
25101     
25102 };
25103
25104
25105 Roo.extend(Roo.HtmlEditorCore, Roo.Component,  {
25106
25107
25108      /**
25109      * @cfg {Roo.form.HtmlEditor|Roo.bootstrap.HtmlEditor} the owner field 
25110      */
25111     
25112     owner : false,
25113     
25114      /**
25115      * @cfg {String} resizable  's' or 'se' or 'e' - wrapps the element in a
25116      *                        Roo.resizable.
25117      */
25118     resizable : false,
25119      /**
25120      * @cfg {Number} height (in pixels)
25121      */   
25122     height: 300,
25123    /**
25124      * @cfg {Number} width (in pixels)
25125      */   
25126     width: 500,
25127      /**
25128      * @cfg {boolean} autoClean - default true - loading and saving will remove quite a bit of formating,
25129      *         if you are doing an email editor, this probably needs disabling, it's designed
25130      */
25131     autoClean: true,
25132     
25133     /**
25134      * @cfg {boolean} enableBlocks - default true - if the block editor (table and figure should be enabled)
25135      */
25136     enableBlocks : true,
25137     /**
25138      * @cfg {Array} stylesheets url of stylesheets. set to [] to disable stylesheets.
25139      * 
25140      */
25141     stylesheets: false,
25142      /**
25143      * @cfg {String} language default en - language of text (usefull for rtl languages)
25144      * 
25145      */
25146     language: 'en',
25147     
25148     /**
25149      * @cfg {boolean} allowComments - default false - allow comments in HTML source
25150      *          - by default they are stripped - if you are editing email you may need this.
25151      */
25152     allowComments: false,
25153     // id of frame..
25154     frameId: false,
25155     
25156     // private properties
25157     validationEvent : false,
25158     deferHeight: true,
25159     initialized : false,
25160     activated : false,
25161     sourceEditMode : false,
25162     onFocus : Roo.emptyFn,
25163     iframePad:3,
25164     hideMode:'offsets',
25165     
25166     clearUp: true,
25167     
25168     // blacklist + whitelisted elements..
25169     black: false,
25170     white: false,
25171      
25172     bodyCls : '',
25173
25174     
25175     undoManager : false,
25176     /**
25177      * Protected method that will not generally be called directly. It
25178      * is called when the editor initializes the iframe with HTML contents. Override this method if you
25179      * want to change the initialization markup of the iframe (e.g. to add stylesheets).
25180      */
25181     getDocMarkup : function(){
25182         // body styles..
25183         var st = '';
25184         
25185         // inherit styels from page...?? 
25186         if (this.stylesheets === false) {
25187             
25188             Roo.get(document.head).select('style').each(function(node) {
25189                 st += node.dom.outerHTML || new XMLSerializer().serializeToString(node.dom);
25190             });
25191             
25192             Roo.get(document.head).select('link').each(function(node) { 
25193                 st += node.dom.outerHTML || new XMLSerializer().serializeToString(node.dom);
25194             });
25195             
25196         } else if (!this.stylesheets.length) {
25197                 // simple..
25198                 st = '<style type="text/css">' +
25199                     'body{border:0;margin:0;padding:3px;height:98%;cursor:text;}' +
25200                    '</style>';
25201         } else {
25202             for (var i in this.stylesheets) {
25203                 if (typeof(this.stylesheets[i]) != 'string') {
25204                     continue;
25205                 }
25206                 st += '<link rel="stylesheet" href="' + this.stylesheets[i] +'" type="text/css">';
25207             }
25208             
25209         }
25210         
25211         st +=  '<style type="text/css">' +
25212             'IMG { cursor: pointer } ' +
25213         '</style>';
25214         
25215         st += '<meta name="google" content="notranslate">';
25216         
25217         var cls = 'notranslate roo-htmleditor-body';
25218         
25219         if(this.bodyCls.length){
25220             cls += ' ' + this.bodyCls;
25221         }
25222         
25223         return '<html  class="notranslate" translate="no"><head>' + st  +
25224             //<style type="text/css">' +
25225             //'body{border:0;margin:0;padding:3px;height:98%;cursor:text;}' +
25226             //'</style>' +
25227             ' </head><body contenteditable="true" data-enable-grammerly="true" class="' +  cls + '"></body></html>';
25228     },
25229
25230     // private
25231     onRender : function(ct, position)
25232     {
25233         var _t = this;
25234         //Roo.HtmlEditorCore.superclass.onRender.call(this, ct, position);
25235         this.el = this.owner.inputEl ? this.owner.inputEl() : this.owner.el;
25236         
25237         
25238         this.el.dom.style.border = '0 none';
25239         this.el.dom.setAttribute('tabIndex', -1);
25240         this.el.addClass('x-hidden hide');
25241         
25242         
25243         
25244         if(Roo.isIE){ // fix IE 1px bogus margin
25245             this.el.applyStyles('margin-top:-1px;margin-bottom:-1px;')
25246         }
25247        
25248         
25249         this.frameId = Roo.id();
25250         
25251          
25252         
25253         var iframe = this.owner.wrap.createChild({
25254             tag: 'iframe',
25255             cls: 'form-control', // bootstrap..
25256             id: this.frameId,
25257             name: this.frameId,
25258             frameBorder : 'no',
25259             'src' : Roo.SSL_SECURE_URL ? Roo.SSL_SECURE_URL  :  "javascript:false"
25260         }, this.el
25261         );
25262         
25263         
25264         this.iframe = iframe.dom;
25265
25266         this.assignDocWin();
25267         
25268         this.doc.designMode = 'on';
25269        
25270         this.doc.open();
25271         this.doc.write(this.getDocMarkup());
25272         this.doc.close();
25273
25274         
25275         var task = { // must defer to wait for browser to be ready
25276             run : function(){
25277                 //console.log("run task?" + this.doc.readyState);
25278                 this.assignDocWin();
25279                 if(this.doc.body || this.doc.readyState == 'complete'){
25280                     try {
25281                         this.doc.designMode="on";
25282                         
25283                     } catch (e) {
25284                         return;
25285                     }
25286                     Roo.TaskMgr.stop(task);
25287                     this.initEditor.defer(10, this);
25288                 }
25289             },
25290             interval : 10,
25291             duration: 10000,
25292             scope: this
25293         };
25294         Roo.TaskMgr.start(task);
25295
25296     },
25297
25298     // private
25299     onResize : function(w, h)
25300     {
25301          Roo.log('resize: ' +w + ',' + h );
25302         //Roo.HtmlEditorCore.superclass.onResize.apply(this, arguments);
25303         if(!this.iframe){
25304             return;
25305         }
25306         if(typeof w == 'number'){
25307             
25308             this.iframe.style.width = w + 'px';
25309         }
25310         if(typeof h == 'number'){
25311             
25312             this.iframe.style.height = h + 'px';
25313             if(this.doc){
25314                 (this.doc.body || this.doc.documentElement).style.height = (h - (this.iframePad*2)) + 'px';
25315             }
25316         }
25317         
25318     },
25319
25320     /**
25321      * Toggles the editor between standard and source edit mode.
25322      * @param {Boolean} sourceEdit (optional) True for source edit, false for standard
25323      */
25324     toggleSourceEdit : function(sourceEditMode){
25325         
25326         this.sourceEditMode = sourceEditMode === true;
25327         
25328         if(this.sourceEditMode){
25329  
25330             Roo.get(this.iframe).addClass(['x-hidden','hide', 'd-none']);     //FIXME - what's the BS styles for these
25331             
25332         }else{
25333             Roo.get(this.iframe).removeClass(['x-hidden','hide', 'd-none']);
25334             //this.iframe.className = '';
25335             this.deferFocus();
25336         }
25337         //this.setSize(this.owner.wrap.getSize());
25338         //this.fireEvent('editmodechange', this, this.sourceEditMode);
25339     },
25340
25341     
25342   
25343
25344     /**
25345      * Protected method that will not generally be called directly. If you need/want
25346      * custom HTML cleanup, this is the method you should override.
25347      * @param {String} html The HTML to be cleaned
25348      * return {String} The cleaned HTML
25349      */
25350     cleanHtml : function(html)
25351     {
25352         html = String(html);
25353         if(html.length > 5){
25354             if(Roo.isSafari){ // strip safari nonsense
25355                 html = html.replace(/\sclass="(?:Apple-style-span|khtml-block-placeholder)"/gi, '');
25356             }
25357         }
25358         if(html == '&nbsp;'){
25359             html = '';
25360         }
25361         return html;
25362     },
25363
25364     /**
25365      * HTML Editor -> Textarea
25366      * Protected method that will not generally be called directly. Syncs the contents
25367      * of the editor iframe with the textarea.
25368      */
25369     syncValue : function()
25370     {
25371         //Roo.log("HtmlEditorCore:syncValue (EDITOR->TEXT)");
25372         if(this.initialized){
25373             
25374             this.undoManager.addEvent();
25375
25376             
25377             var bd = (this.doc.body || this.doc.documentElement);
25378            
25379             
25380             var sel = this.win.getSelection();
25381             
25382             var div = document.createElement('div');
25383             div.innerHTML = bd.innerHTML;
25384             var gtx = div.getElementsByClassName('gtx-trans-icon'); // google translate - really annoying and difficult to get rid of.
25385             if (gtx.length > 0) {
25386                 var rm = gtx.item(0).parentNode;
25387                 rm.parentNode.removeChild(rm);
25388             }
25389             
25390            
25391             if (this.enableBlocks) {
25392                 new Roo.htmleditor.FilterBlock({ node : div });
25393             }
25394             //?? tidy?
25395             var tidy = new Roo.htmleditor.TidySerializer({
25396                 inner:  true
25397             });
25398             var html  = tidy.serialize(div);
25399             
25400             
25401             if(Roo.isSafari){
25402                 var bs = bd.getAttribute('style'); // Safari puts text-align styles on the body element!
25403                 var m = bs ? bs.match(/text-align:(.*?);/i) : false;
25404                 if(m && m[1]){
25405                     html = '<div style="'+m[0]+'">' + html + '</div>';
25406                 }
25407             }
25408             html = this.cleanHtml(html);
25409             // fix up the special chars.. normaly like back quotes in word...
25410             // however we do not want to do this with chinese..
25411             html = html.replace(/[\uD800-\uDBFF][\uDC00-\uDFFF]|[\u0080-\uFFFF]/g, function(match) {
25412                 
25413                 var cc = match.charCodeAt();
25414
25415                 // Get the character value, handling surrogate pairs
25416                 if (match.length == 2) {
25417                     // It's a surrogate pair, calculate the Unicode code point
25418                     var high = match.charCodeAt(0) - 0xD800;
25419                     var low  = match.charCodeAt(1) - 0xDC00;
25420                     cc = (high * 0x400) + low + 0x10000;
25421                 }  else if (
25422                     (cc >= 0x4E00 && cc < 0xA000 ) ||
25423                     (cc >= 0x3400 && cc < 0x4E00 ) ||
25424                     (cc >= 0xf900 && cc < 0xfb00 )
25425                 ) {
25426                         return match;
25427                 }  
25428          
25429                 // No, use a numeric entity. Here we brazenly (and possibly mistakenly)
25430                 return "&#" + cc + ";";
25431                 
25432                 
25433             });
25434             
25435             
25436              
25437             if(this.owner.fireEvent('beforesync', this, html) !== false){
25438                 this.el.dom.value = html;
25439                 this.owner.fireEvent('sync', this, html);
25440             }
25441         }
25442     },
25443
25444     /**
25445      * TEXTAREA -> EDITABLE
25446      * Protected method that will not generally be called directly. Pushes the value of the textarea
25447      * into the iframe editor.
25448      */
25449     pushValue : function()
25450     {
25451         //Roo.log("HtmlEditorCore:pushValue (TEXT->EDITOR)");
25452         if(this.initialized){
25453             var v = this.el.dom.value.trim();
25454             
25455             
25456             if(this.owner.fireEvent('beforepush', this, v) !== false){
25457                 var d = (this.doc.body || this.doc.documentElement);
25458                 d.innerHTML = v;
25459                  
25460                 this.el.dom.value = d.innerHTML;
25461                 this.owner.fireEvent('push', this, v);
25462             }
25463             if (this.autoClean) {
25464                 new Roo.htmleditor.FilterParagraph({node : this.doc.body}); // paragraphs
25465                 new Roo.htmleditor.FilterSpan({node : this.doc.body}); // empty spans
25466             }
25467             if (this.enableBlocks) {
25468                 Roo.htmleditor.Block.initAll(this.doc.body);
25469             }
25470             
25471             this.updateLanguage();
25472             
25473             var lc = this.doc.body.lastChild;
25474             if (lc && lc.nodeType == 1 && lc.getAttribute("contenteditable") == "false") {
25475                 // add an extra line at the end.
25476                 this.doc.body.appendChild(this.doc.createElement('br'));
25477             }
25478             
25479             
25480         }
25481     },
25482
25483     // private
25484     deferFocus : function(){
25485         this.focus.defer(10, this);
25486     },
25487
25488     // doc'ed in Field
25489     focus : function(){
25490         if(this.win && !this.sourceEditMode){
25491             this.win.focus();
25492         }else{
25493             this.el.focus();
25494         }
25495     },
25496     
25497     assignDocWin: function()
25498     {
25499         var iframe = this.iframe;
25500         
25501          if(Roo.isIE){
25502             this.doc = iframe.contentWindow.document;
25503             this.win = iframe.contentWindow;
25504         } else {
25505 //            if (!Roo.get(this.frameId)) {
25506 //                return;
25507 //            }
25508 //            this.doc = (iframe.contentDocument || Roo.get(this.frameId).dom.document);
25509 //            this.win = Roo.get(this.frameId).dom.contentWindow;
25510             
25511             if (!Roo.get(this.frameId) && !iframe.contentDocument) {
25512                 return;
25513             }
25514             
25515             this.doc = (iframe.contentDocument || Roo.get(this.frameId).dom.document);
25516             this.win = (iframe.contentWindow || Roo.get(this.frameId).dom.contentWindow);
25517         }
25518     },
25519     
25520     // private
25521     initEditor : function(){
25522         //console.log("INIT EDITOR");
25523         this.assignDocWin();
25524         
25525         
25526         
25527         this.doc.designMode="on";
25528         this.doc.open();
25529         this.doc.write(this.getDocMarkup());
25530         this.doc.close();
25531         
25532         var dbody = (this.doc.body || this.doc.documentElement);
25533         //var ss = this.el.getStyles('font-size', 'font-family', 'background-image', 'background-repeat');
25534         // this copies styles from the containing element into thsi one..
25535         // not sure why we need all of this..
25536         //var ss = this.el.getStyles('font-size', 'background-image', 'background-repeat');
25537         
25538         //var ss = this.el.getStyles( 'background-image', 'background-repeat');
25539         //ss['background-attachment'] = 'fixed'; // w3c
25540         dbody.bgProperties = 'fixed'; // ie
25541         dbody.setAttribute("translate", "no");
25542         
25543         //Roo.DomHelper.applyStyles(dbody, ss);
25544         Roo.EventManager.on(this.doc, {
25545              
25546             'mouseup': this.onEditorEvent,
25547             'dblclick': this.onEditorEvent,
25548             'click': this.onEditorEvent,
25549             'keyup': this.onEditorEvent,
25550             
25551             buffer:100,
25552             scope: this
25553         });
25554         Roo.EventManager.on(this.doc, {
25555             'paste': this.onPasteEvent,
25556             scope : this
25557         });
25558         if(Roo.isGecko){
25559             Roo.EventManager.on(this.doc, 'keypress', this.mozKeyPress, this);
25560         }
25561         //??? needed???
25562         if(Roo.isIE || Roo.isSafari || Roo.isOpera){
25563             Roo.EventManager.on(this.doc, 'keydown', this.fixKeys, this);
25564         }
25565         this.initialized = true;
25566
25567         
25568         // initialize special key events - enter
25569         new Roo.htmleditor.KeyEnter({core : this});
25570         
25571          
25572         
25573         this.owner.fireEvent('initialize', this);
25574         this.pushValue();
25575     },
25576     // this is to prevent a href clicks resulting in a redirect?
25577    
25578     onPasteEvent : function(e,v)
25579     {
25580         // I think we better assume paste is going to be a dirty load of rubish from word..
25581         
25582         // even pasting into a 'email version' of this widget will have to clean up that mess.
25583         var cd = (e.browserEvent.clipboardData || window.clipboardData);
25584         
25585         // check what type of paste - if it's an image, then handle it differently.
25586         if (cd.files && cd.files.length > 0) {
25587             // pasting images?
25588             var urlAPI = (window.createObjectURL && window) || 
25589                 (window.URL && URL.revokeObjectURL && URL) || 
25590                 (window.webkitURL && webkitURL);
25591     
25592             var url = urlAPI.createObjectURL( cd.files[0]);
25593             this.insertAtCursor('<img src=" + url + ">');
25594             return false;
25595         }
25596         if (cd.types.indexOf('text/html') < 0 ) {
25597             return false;
25598         }
25599         var images = [];
25600         var html = cd.getData('text/html'); // clipboard event
25601         if (cd.types.indexOf('text/rtf') > -1) {
25602             var parser = new Roo.rtf.Parser(cd.getData('text/rtf'));
25603             images = parser.doc ? parser.doc.getElementsByType('pict') : [];
25604         }
25605         Roo.log(images);
25606         //Roo.log(imgs);
25607         // fixme..
25608         images = images.filter(function(g) { return !g.path.match(/^rtf\/(head|pgdsctbl|listtable|footerf)/); }) // ignore headers/footers etc.
25609                        .map(function(g) { return g.toDataURL(); })
25610                        .filter(function(g) { return g != 'about:blank'; });
25611         
25612         
25613         html = this.cleanWordChars(html);
25614         
25615         var d = (new DOMParser().parseFromString(html, 'text/html')).body;
25616         
25617         
25618         var sn = this.getParentElement();
25619         // check if d contains a table, and prevent nesting??
25620         //Roo.log(d.getElementsByTagName('table'));
25621         //Roo.log(sn);
25622         //Roo.log(sn.closest('table'));
25623         if (d.getElementsByTagName('table').length && sn && sn.closest('table')) {
25624             e.preventDefault();
25625             this.insertAtCursor("You can not nest tables");
25626             //Roo.log("prevent?"); // fixme - 
25627             return false;
25628         }
25629         
25630         if (images.length > 0) {
25631             Roo.each(d.getElementsByTagName('img'), function(img, i) {
25632                 img.setAttribute('src', images[i]);
25633             });
25634         }
25635         if (this.autoClean) {
25636             new Roo.htmleditor.FilterStyleToTag({ node : d });
25637             new Roo.htmleditor.FilterAttributes({
25638                 node : d,
25639                 attrib_white : ['href', 'src', 'name', 'align', 'colspan', 'rowspan', 'data-display'],
25640                 attrib_clean : ['href', 'src' ] 
25641             });
25642             new Roo.htmleditor.FilterBlack({ node : d, tag : this.black});
25643             // should be fonts..
25644             new Roo.htmleditor.FilterKeepChildren({node : d, tag : [ 'FONT', 'O:P' ]} );
25645             new Roo.htmleditor.FilterParagraph({ node : d });
25646             new Roo.htmleditor.FilterSpan({ node : d });
25647             new Roo.htmleditor.FilterLongBr({ node : d });
25648         }
25649         if (this.enableBlocks) {
25650                 
25651             Array.from(d.getElementsByTagName('img')).forEach(function(img) {
25652                 if (img.closest('figure')) { // assume!! that it's aready
25653                     return;
25654                 }
25655                 var fig  = new Roo.htmleditor.BlockFigure({
25656                     image_src  : img.src
25657                 });
25658                 fig.updateElement(img); // replace it..
25659                 
25660             });
25661         }
25662         
25663         
25664         this.insertAtCursor(d.innerHTML.replace(/&nbsp;/g,' '));
25665         if (this.enableBlocks) {
25666             Roo.htmleditor.Block.initAll(this.doc.body);
25667         }
25668         
25669         
25670         e.preventDefault();
25671         return false;
25672         // default behaveiour should be our local cleanup paste? (optional?)
25673         // for simple editor - we want to hammer the paste and get rid of everything... - so over-rideable..
25674         //this.owner.fireEvent('paste', e, v);
25675     },
25676     // private
25677     onDestroy : function(){
25678         
25679         
25680         
25681         if(this.rendered){
25682             
25683             //for (var i =0; i < this.toolbars.length;i++) {
25684             //    // fixme - ask toolbars for heights?
25685             //    this.toolbars[i].onDestroy();
25686            // }
25687             
25688             //this.wrap.dom.innerHTML = '';
25689             //this.wrap.remove();
25690         }
25691     },
25692
25693     // private
25694     onFirstFocus : function(){
25695         
25696         this.assignDocWin();
25697         this.undoManager = new Roo.lib.UndoManager(100,(this.doc.body || this.doc.documentElement));
25698         
25699         this.activated = true;
25700          
25701     
25702         if(Roo.isGecko){ // prevent silly gecko errors
25703             this.win.focus();
25704             var s = this.win.getSelection();
25705             if(!s.focusNode || s.focusNode.nodeType != 3){
25706                 var r = s.getRangeAt(0);
25707                 r.selectNodeContents((this.doc.body || this.doc.documentElement));
25708                 r.collapse(true);
25709                 this.deferFocus();
25710             }
25711             try{
25712                 this.execCmd('useCSS', true);
25713                 this.execCmd('styleWithCSS', false);
25714             }catch(e){}
25715         }
25716         this.owner.fireEvent('activate', this);
25717     },
25718
25719     // private
25720     adjustFont: function(btn){
25721         var adjust = btn.cmd == 'increasefontsize' ? 1 : -1;
25722         //if(Roo.isSafari){ // safari
25723         //    adjust *= 2;
25724        // }
25725         var v = parseInt(this.doc.queryCommandValue('FontSize')|| 3, 10);
25726         if(Roo.isSafari){ // safari
25727             var sm = { 10 : 1, 13: 2, 16:3, 18:4, 24: 5, 32:6, 48: 7 };
25728             v =  (v < 10) ? 10 : v;
25729             v =  (v > 48) ? 48 : v;
25730             v = typeof(sm[v]) == 'undefined' ? 1 : sm[v];
25731             
25732         }
25733         
25734         
25735         v = Math.max(1, v+adjust);
25736         
25737         this.execCmd('FontSize', v  );
25738     },
25739
25740     onEditorEvent : function(e)
25741     {
25742          
25743         
25744         if (e && (e.ctrlKey || e.metaKey) && e.keyCode === 90) {
25745             return; // we do not handle this.. (undo manager does..)
25746         }
25747         // in theory this detects if the last element is not a br, then we try and do that.
25748         // its so clicking in space at bottom triggers adding a br and moving the cursor.
25749         if (e &&
25750             e.target.nodeName == 'BODY' &&
25751             e.type == "mouseup" &&
25752             this.doc.body.lastChild
25753            ) {
25754             var lc = this.doc.body.lastChild;
25755             // gtx-trans is google translate plugin adding crap.
25756             while ((lc.nodeType == 3 && lc.nodeValue == '') || lc.id == 'gtx-trans') {
25757                 lc = lc.previousSibling;
25758             }
25759             if (lc.nodeType == 1 && lc.nodeName != 'BR') {
25760             // if last element is <BR> - then dont do anything.
25761             
25762                 var ns = this.doc.createElement('br');
25763                 this.doc.body.appendChild(ns);
25764                 range = this.doc.createRange();
25765                 range.setStartAfter(ns);
25766                 range.collapse(true);
25767                 var sel = this.win.getSelection();
25768                 sel.removeAllRanges();
25769                 sel.addRange(range);
25770             }
25771         }
25772         
25773         
25774         
25775         this.fireEditorEvent(e);
25776       //  this.updateToolbar();
25777         this.syncValue(); //we can not sync so often.. sync cleans, so this breaks stuff
25778     },
25779     
25780     fireEditorEvent: function(e)
25781     {
25782         this.owner.fireEvent('editorevent', this, e);
25783     },
25784
25785     insertTag : function(tg)
25786     {
25787         // could be a bit smarter... -> wrap the current selected tRoo..
25788         if (tg.toLowerCase() == 'span' ||
25789             tg.toLowerCase() == 'code' ||
25790             tg.toLowerCase() == 'sup' ||
25791             tg.toLowerCase() == 'sub' 
25792             ) {
25793             
25794             range = this.createRange(this.getSelection());
25795             var wrappingNode = this.doc.createElement(tg.toLowerCase());
25796             wrappingNode.appendChild(range.extractContents());
25797             range.insertNode(wrappingNode);
25798
25799             return;
25800             
25801             
25802             
25803         }
25804         this.execCmd("formatblock",   tg);
25805         this.undoManager.addEvent(); 
25806     },
25807     
25808     insertText : function(txt)
25809     {
25810         
25811         
25812         var range = this.createRange();
25813         range.deleteContents();
25814                //alert(Sender.getAttribute('label'));
25815                
25816         range.insertNode(this.doc.createTextNode(txt));
25817         this.undoManager.addEvent();
25818     } ,
25819     
25820      
25821
25822     /**
25823      * Executes a Midas editor command on the editor document and performs necessary focus and
25824      * toolbar updates. <b>This should only be called after the editor is initialized.</b>
25825      * @param {String} cmd The Midas command
25826      * @param {String/Boolean} value (optional) The value to pass to the command (defaults to null)
25827      */
25828     relayCmd : function(cmd, value)
25829     {
25830         
25831         switch (cmd) {
25832             case 'justifyleft':
25833             case 'justifyright':
25834             case 'justifycenter':
25835                 // if we are in a cell, then we will adjust the
25836                 var n = this.getParentElement();
25837                 var td = n.closest('td');
25838                 if (td) {
25839                     var bl = Roo.htmleditor.Block.factory(td);
25840                     bl.textAlign = cmd.replace('justify','');
25841                     bl.updateElement();
25842                     this.owner.fireEvent('editorevent', this);
25843                     return;
25844                 }
25845                 this.execCmd('styleWithCSS', true); // 
25846                 break;
25847             case 'bold':
25848             case 'italic':
25849                 // if there is no selection, then we insert, and set the curson inside it..
25850                 this.execCmd('styleWithCSS', false); 
25851                 break;
25852                 
25853         
25854             default:
25855                 break;
25856         }
25857         
25858         
25859         this.win.focus();
25860         this.execCmd(cmd, value);
25861         this.owner.fireEvent('editorevent', this);
25862         //this.updateToolbar();
25863         this.owner.deferFocus();
25864     },
25865
25866     /**
25867      * Executes a Midas editor command directly on the editor document.
25868      * For visual commands, you should use {@link #relayCmd} instead.
25869      * <b>This should only be called after the editor is initialized.</b>
25870      * @param {String} cmd The Midas command
25871      * @param {String/Boolean} value (optional) The value to pass to the command (defaults to null)
25872      */
25873     execCmd : function(cmd, value){
25874         this.doc.execCommand(cmd, false, value === undefined ? null : value);
25875         this.syncValue();
25876     },
25877  
25878  
25879    
25880     /**
25881      * Inserts the passed text at the current cursor position. Note: the editor must be initialized and activated
25882      * to insert tRoo.
25883      * @param {String} text | dom node.. 
25884      */
25885     insertAtCursor : function(text)
25886     {
25887         
25888         if(!this.activated){
25889             return;
25890         }
25891          
25892         if(Roo.isGecko || Roo.isOpera || Roo.isSafari){
25893             this.win.focus();
25894             
25895             
25896             // from jquery ui (MIT licenced)
25897             var range, node;
25898             var win = this.win;
25899             
25900             if (win.getSelection && win.getSelection().getRangeAt) {
25901                 
25902                 // delete the existing?
25903                 
25904                 this.createRange(this.getSelection()).deleteContents();
25905                 range = win.getSelection().getRangeAt(0);
25906                 node = typeof(text) == 'string' ? range.createContextualFragment(text) : text;
25907                 range.insertNode(node);
25908                 range = range.cloneRange();
25909                 range.collapse(false);
25910                  
25911                 win.getSelection().removeAllRanges();
25912                 win.getSelection().addRange(range);
25913                 
25914                 
25915                 
25916             } else if (win.document.selection && win.document.selection.createRange) {
25917                 // no firefox support
25918                 var txt = typeof(text) == 'string' ? text : text.outerHTML;
25919                 win.document.selection.createRange().pasteHTML(txt);
25920             
25921             } else {
25922                 // no firefox support
25923                 var txt = typeof(text) == 'string' ? text : text.outerHTML;
25924                 this.execCmd('InsertHTML', txt);
25925             } 
25926             this.syncValue();
25927             
25928             this.deferFocus();
25929         }
25930     },
25931  // private
25932     mozKeyPress : function(e){
25933         if(e.ctrlKey){
25934             var c = e.getCharCode(), cmd;
25935           
25936             if(c > 0){
25937                 c = String.fromCharCode(c).toLowerCase();
25938                 switch(c){
25939                     case 'b':
25940                         cmd = 'bold';
25941                         break;
25942                     case 'i':
25943                         cmd = 'italic';
25944                         break;
25945                     
25946                     case 'u':
25947                         cmd = 'underline';
25948                         break;
25949                     
25950                     //case 'v':
25951                       //  this.cleanUpPaste.defer(100, this);
25952                       //  return;
25953                         
25954                 }
25955                 if(cmd){
25956                     
25957                     this.relayCmd(cmd);
25958                     //this.win.focus();
25959                     //this.execCmd(cmd);
25960                     //this.deferFocus();
25961                     e.preventDefault();
25962                 }
25963                 
25964             }
25965         }
25966     },
25967
25968     // private
25969     fixKeys : function(){ // load time branching for fastest keydown performance
25970         
25971         
25972         if(Roo.isIE){
25973             return function(e){
25974                 var k = e.getKey(), r;
25975                 if(k == e.TAB){
25976                     e.stopEvent();
25977                     r = this.doc.selection.createRange();
25978                     if(r){
25979                         r.collapse(true);
25980                         r.pasteHTML('&#160;&#160;&#160;&#160;');
25981                         this.deferFocus();
25982                     }
25983                     return;
25984                 }
25985                 /// this is handled by Roo.htmleditor.KeyEnter
25986                  /*
25987                 if(k == e.ENTER){
25988                     r = this.doc.selection.createRange();
25989                     if(r){
25990                         var target = r.parentElement();
25991                         if(!target || target.tagName.toLowerCase() != 'li'){
25992                             e.stopEvent();
25993                             r.pasteHTML('<br/>');
25994                             r.collapse(false);
25995                             r.select();
25996                         }
25997                     }
25998                 }
25999                 */
26000                 //if (String.fromCharCode(k).toLowerCase() == 'v') { // paste
26001                 //    this.cleanUpPaste.defer(100, this);
26002                 //    return;
26003                 //}
26004                 
26005                 
26006             };
26007         }else if(Roo.isOpera){
26008             return function(e){
26009                 var k = e.getKey();
26010                 if(k == e.TAB){
26011                     e.stopEvent();
26012                     this.win.focus();
26013                     this.execCmd('InsertHTML','&#160;&#160;&#160;&#160;');
26014                     this.deferFocus();
26015                 }
26016                
26017                 //if (String.fromCharCode(k).toLowerCase() == 'v') { // paste
26018                 //    this.cleanUpPaste.defer(100, this);
26019                  //   return;
26020                 //}
26021                 
26022             };
26023         }else if(Roo.isSafari){
26024             return function(e){
26025                 var k = e.getKey();
26026                 
26027                 if(k == e.TAB){
26028                     e.stopEvent();
26029                     this.execCmd('InsertText','\t');
26030                     this.deferFocus();
26031                     return;
26032                 }
26033                  this.mozKeyPress(e);
26034                 
26035                //if (String.fromCharCode(k).toLowerCase() == 'v') { // paste
26036                  //   this.cleanUpPaste.defer(100, this);
26037                  //   return;
26038                // }
26039                 
26040              };
26041         }
26042     }(),
26043     
26044     getAllAncestors: function()
26045     {
26046         var p = this.getSelectedNode();
26047         var a = [];
26048         if (!p) {
26049             a.push(p); // push blank onto stack..
26050             p = this.getParentElement();
26051         }
26052         
26053         
26054         while (p && (p.nodeType == 1) && (p.tagName.toLowerCase() != 'body')) {
26055             a.push(p);
26056             p = p.parentNode;
26057         }
26058         a.push(this.doc.body);
26059         return a;
26060     },
26061     lastSel : false,
26062     lastSelNode : false,
26063     
26064     
26065     getSelection : function() 
26066     {
26067         this.assignDocWin();
26068         return Roo.lib.Selection.wrap(Roo.isIE ? this.doc.selection : this.win.getSelection(), this.doc);
26069     },
26070     /**
26071      * Select a dom node
26072      * @param {DomElement} node the node to select
26073      */
26074     selectNode : function(node, collapse)
26075     {
26076         var nodeRange = node.ownerDocument.createRange();
26077         try {
26078             nodeRange.selectNode(node);
26079         } catch (e) {
26080             nodeRange.selectNodeContents(node);
26081         }
26082         if (collapse === true) {
26083             nodeRange.collapse(true);
26084         }
26085         //
26086         var s = this.win.getSelection();
26087         s.removeAllRanges();
26088         s.addRange(nodeRange);
26089     },
26090     
26091     getSelectedNode: function() 
26092     {
26093         // this may only work on Gecko!!!
26094         
26095         // should we cache this!!!!
26096         
26097          
26098          
26099         var range = this.createRange(this.getSelection()).cloneRange();
26100         
26101         if (Roo.isIE) {
26102             var parent = range.parentElement();
26103             while (true) {
26104                 var testRange = range.duplicate();
26105                 testRange.moveToElementText(parent);
26106                 if (testRange.inRange(range)) {
26107                     break;
26108                 }
26109                 if ((parent.nodeType != 1) || (parent.tagName.toLowerCase() == 'body')) {
26110                     break;
26111                 }
26112                 parent = parent.parentElement;
26113             }
26114             return parent;
26115         }
26116         
26117         // is ancestor a text element.
26118         var ac =  range.commonAncestorContainer;
26119         if (ac.nodeType == 3) {
26120             ac = ac.parentNode;
26121         }
26122         
26123         var ar = ac.childNodes;
26124          
26125         var nodes = [];
26126         var other_nodes = [];
26127         var has_other_nodes = false;
26128         for (var i=0;i<ar.length;i++) {
26129             if ((ar[i].nodeType == 3) && (!ar[i].data.length)) { // empty text ? 
26130                 continue;
26131             }
26132             // fullly contained node.
26133             
26134             if (this.rangeIntersectsNode(range,ar[i]) && this.rangeCompareNode(range,ar[i]) == 3) {
26135                 nodes.push(ar[i]);
26136                 continue;
26137             }
26138             
26139             // probably selected..
26140             if ((ar[i].nodeType == 1) && this.rangeIntersectsNode(range,ar[i]) && (this.rangeCompareNode(range,ar[i]) > 0)) {
26141                 other_nodes.push(ar[i]);
26142                 continue;
26143             }
26144             // outer..
26145             if (!this.rangeIntersectsNode(range,ar[i])|| (this.rangeCompareNode(range,ar[i]) == 0))  {
26146                 continue;
26147             }
26148             
26149             
26150             has_other_nodes = true;
26151         }
26152         if (!nodes.length && other_nodes.length) {
26153             nodes= other_nodes;
26154         }
26155         if (has_other_nodes || !nodes.length || (nodes.length > 1)) {
26156             return false;
26157         }
26158         
26159         return nodes[0];
26160     },
26161     
26162     
26163     createRange: function(sel)
26164     {
26165         // this has strange effects when using with 
26166         // top toolbar - not sure if it's a great idea.
26167         //this.editor.contentWindow.focus();
26168         if (typeof sel != "undefined") {
26169             try {
26170                 return sel.getRangeAt ? sel.getRangeAt(0) : sel.createRange();
26171             } catch(e) {
26172                 return this.doc.createRange();
26173             }
26174         } else {
26175             return this.doc.createRange();
26176         }
26177     },
26178     getParentElement: function()
26179     {
26180         
26181         this.assignDocWin();
26182         var sel = Roo.isIE ? this.doc.selection : this.win.getSelection();
26183         
26184         var range = this.createRange(sel);
26185          
26186         try {
26187             var p = range.commonAncestorContainer;
26188             while (p.nodeType == 3) { // text node
26189                 p = p.parentNode;
26190             }
26191             return p;
26192         } catch (e) {
26193             return null;
26194         }
26195     
26196     },
26197     /***
26198      *
26199      * Range intersection.. the hard stuff...
26200      *  '-1' = before
26201      *  '0' = hits..
26202      *  '1' = after.
26203      *         [ -- selected range --- ]
26204      *   [fail]                        [fail]
26205      *
26206      *    basically..
26207      *      if end is before start or  hits it. fail.
26208      *      if start is after end or hits it fail.
26209      *
26210      *   if either hits (but other is outside. - then it's not 
26211      *   
26212      *    
26213      **/
26214     
26215     
26216     // @see http://www.thismuchiknow.co.uk/?p=64.
26217     rangeIntersectsNode : function(range, node)
26218     {
26219         var nodeRange = node.ownerDocument.createRange();
26220         try {
26221             nodeRange.selectNode(node);
26222         } catch (e) {
26223             nodeRange.selectNodeContents(node);
26224         }
26225     
26226         var rangeStartRange = range.cloneRange();
26227         rangeStartRange.collapse(true);
26228     
26229         var rangeEndRange = range.cloneRange();
26230         rangeEndRange.collapse(false);
26231     
26232         var nodeStartRange = nodeRange.cloneRange();
26233         nodeStartRange.collapse(true);
26234     
26235         var nodeEndRange = nodeRange.cloneRange();
26236         nodeEndRange.collapse(false);
26237     
26238         return rangeStartRange.compareBoundaryPoints(
26239                  Range.START_TO_START, nodeEndRange) == -1 &&
26240                rangeEndRange.compareBoundaryPoints(
26241                  Range.START_TO_START, nodeStartRange) == 1;
26242         
26243          
26244     },
26245     rangeCompareNode : function(range, node)
26246     {
26247         var nodeRange = node.ownerDocument.createRange();
26248         try {
26249             nodeRange.selectNode(node);
26250         } catch (e) {
26251             nodeRange.selectNodeContents(node);
26252         }
26253         
26254         
26255         range.collapse(true);
26256     
26257         nodeRange.collapse(true);
26258      
26259         var ss = range.compareBoundaryPoints( Range.START_TO_START, nodeRange);
26260         var ee = range.compareBoundaryPoints(  Range.END_TO_END, nodeRange);
26261          
26262         //Roo.log(node.tagName + ': ss='+ss +', ee='+ee)
26263         
26264         var nodeIsBefore   =  ss == 1;
26265         var nodeIsAfter    = ee == -1;
26266         
26267         if (nodeIsBefore && nodeIsAfter) {
26268             return 0; // outer
26269         }
26270         if (!nodeIsBefore && nodeIsAfter) {
26271             return 1; //right trailed.
26272         }
26273         
26274         if (nodeIsBefore && !nodeIsAfter) {
26275             return 2;  // left trailed.
26276         }
26277         // fully contined.
26278         return 3;
26279     },
26280  
26281     cleanWordChars : function(input) {// change the chars to hex code
26282         
26283        var swapCodes  = [ 
26284             [    8211, "&#8211;" ], 
26285             [    8212, "&#8212;" ], 
26286             [    8216,  "'" ],  
26287             [    8217, "'" ],  
26288             [    8220, '"' ],  
26289             [    8221, '"' ],  
26290             [    8226, "*" ],  
26291             [    8230, "..." ]
26292         ]; 
26293         var output = input;
26294         Roo.each(swapCodes, function(sw) { 
26295             var swapper = new RegExp("\\u" + sw[0].toString(16), "g"); // hex codes
26296             
26297             output = output.replace(swapper, sw[1]);
26298         });
26299         
26300         return output;
26301     },
26302     
26303      
26304     
26305         
26306     
26307     cleanUpChild : function (node)
26308     {
26309         
26310         new Roo.htmleditor.FilterComment({node : node});
26311         new Roo.htmleditor.FilterAttributes({
26312                 node : node,
26313                 attrib_black : this.ablack,
26314                 attrib_clean : this.aclean,
26315                 style_white : this.cwhite,
26316                 style_black : this.cblack
26317         });
26318         new Roo.htmleditor.FilterBlack({ node : node, tag : this.black});
26319         new Roo.htmleditor.FilterKeepChildren({node : node, tag : this.tag_remove} );
26320          
26321         
26322     },
26323     
26324     /**
26325      * Clean up MS wordisms...
26326      * @deprecated - use filter directly
26327      */
26328     cleanWord : function(node)
26329     {
26330         new Roo.htmleditor.FilterWord({ node : node ? node : this.doc.body });
26331         
26332     },
26333    
26334     
26335     /**
26336
26337      * @deprecated - use filters
26338      */
26339     cleanTableWidths : function(node)
26340     {
26341         new Roo.htmleditor.FilterTableWidth({ node : node ? node : this.doc.body});
26342         
26343  
26344     },
26345     
26346      
26347         
26348     applyBlacklists : function()
26349     {
26350         var w = typeof(this.owner.white) != 'undefined' && this.owner.white ? this.owner.white  : [];
26351         var b = typeof(this.owner.black) != 'undefined' && this.owner.black ? this.owner.black :  [];
26352         
26353         this.aclean = typeof(this.owner.aclean) != 'undefined' && this.owner.aclean ? this.owner.aclean :  Roo.HtmlEditorCore.aclean;
26354         this.ablack = typeof(this.owner.ablack) != 'undefined' && this.owner.ablack ? this.owner.ablack :  Roo.HtmlEditorCore.ablack;
26355         this.tag_remove = typeof(this.owner.tag_remove) != 'undefined' && this.owner.tag_remove ? this.owner.tag_remove :  Roo.HtmlEditorCore.tag_remove;
26356         
26357         this.white = [];
26358         this.black = [];
26359         Roo.each(Roo.HtmlEditorCore.white, function(tag) {
26360             if (b.indexOf(tag) > -1) {
26361                 return;
26362             }
26363             this.white.push(tag);
26364             
26365         }, this);
26366         
26367         Roo.each(w, function(tag) {
26368             if (b.indexOf(tag) > -1) {
26369                 return;
26370             }
26371             if (this.white.indexOf(tag) > -1) {
26372                 return;
26373             }
26374             this.white.push(tag);
26375             
26376         }, this);
26377         
26378         
26379         Roo.each(Roo.HtmlEditorCore.black, function(tag) {
26380             if (w.indexOf(tag) > -1) {
26381                 return;
26382             }
26383             this.black.push(tag);
26384             
26385         }, this);
26386         
26387         Roo.each(b, function(tag) {
26388             if (w.indexOf(tag) > -1) {
26389                 return;
26390             }
26391             if (this.black.indexOf(tag) > -1) {
26392                 return;
26393             }
26394             this.black.push(tag);
26395             
26396         }, this);
26397         
26398         
26399         w = typeof(this.owner.cwhite) != 'undefined' && this.owner.cwhite ? this.owner.cwhite  : [];
26400         b = typeof(this.owner.cblack) != 'undefined' && this.owner.cblack ? this.owner.cblack :  [];
26401         
26402         this.cwhite = [];
26403         this.cblack = [];
26404         Roo.each(Roo.HtmlEditorCore.cwhite, function(tag) {
26405             if (b.indexOf(tag) > -1) {
26406                 return;
26407             }
26408             this.cwhite.push(tag);
26409             
26410         }, this);
26411         
26412         Roo.each(w, function(tag) {
26413             if (b.indexOf(tag) > -1) {
26414                 return;
26415             }
26416             if (this.cwhite.indexOf(tag) > -1) {
26417                 return;
26418             }
26419             this.cwhite.push(tag);
26420             
26421         }, this);
26422         
26423         
26424         Roo.each(Roo.HtmlEditorCore.cblack, function(tag) {
26425             if (w.indexOf(tag) > -1) {
26426                 return;
26427             }
26428             this.cblack.push(tag);
26429             
26430         }, this);
26431         
26432         Roo.each(b, function(tag) {
26433             if (w.indexOf(tag) > -1) {
26434                 return;
26435             }
26436             if (this.cblack.indexOf(tag) > -1) {
26437                 return;
26438             }
26439             this.cblack.push(tag);
26440             
26441         }, this);
26442     },
26443     
26444     setStylesheets : function(stylesheets)
26445     {
26446         if(typeof(stylesheets) == 'string'){
26447             Roo.get(this.iframe.contentDocument.head).createChild({
26448                 tag : 'link',
26449                 rel : 'stylesheet',
26450                 type : 'text/css',
26451                 href : stylesheets
26452             });
26453             
26454             return;
26455         }
26456         var _this = this;
26457      
26458         Roo.each(stylesheets, function(s) {
26459             if(!s.length){
26460                 return;
26461             }
26462             
26463             Roo.get(_this.iframe.contentDocument.head).createChild({
26464                 tag : 'link',
26465                 rel : 'stylesheet',
26466                 type : 'text/css',
26467                 href : s
26468             });
26469         });
26470
26471         
26472     },
26473     
26474     
26475     updateLanguage : function()
26476     {
26477         if (!this.iframe || !this.iframe.contentDocument) {
26478             return;
26479         }
26480         Roo.get(this.iframe.contentDocument.body).attr("lang", this.language);
26481     },
26482     
26483     
26484     removeStylesheets : function()
26485     {
26486         var _this = this;
26487         
26488         Roo.each(Roo.get(_this.iframe.contentDocument.head).select('link[rel=stylesheet]', true).elements, function(s){
26489             s.remove();
26490         });
26491     },
26492     
26493     setStyle : function(style)
26494     {
26495         Roo.get(this.iframe.contentDocument.head).createChild({
26496             tag : 'style',
26497             type : 'text/css',
26498             html : style
26499         });
26500
26501         return;
26502     }
26503     
26504     // hide stuff that is not compatible
26505     /**
26506      * @event blur
26507      * @hide
26508      */
26509     /**
26510      * @event change
26511      * @hide
26512      */
26513     /**
26514      * @event focus
26515      * @hide
26516      */
26517     /**
26518      * @event specialkey
26519      * @hide
26520      */
26521     /**
26522      * @cfg {String} fieldClass @hide
26523      */
26524     /**
26525      * @cfg {String} focusClass @hide
26526      */
26527     /**
26528      * @cfg {String} autoCreate @hide
26529      */
26530     /**
26531      * @cfg {String} inputType @hide
26532      */
26533     /**
26534      * @cfg {String} invalidClass @hide
26535      */
26536     /**
26537      * @cfg {String} invalidText @hide
26538      */
26539     /**
26540      * @cfg {String} msgFx @hide
26541      */
26542     /**
26543      * @cfg {String} validateOnBlur @hide
26544      */
26545 });
26546
26547 Roo.HtmlEditorCore.white = [
26548         'AREA', 'BR', 'IMG', 'INPUT', 'HR', 'WBR',
26549         
26550        'ADDRESS', 'BLOCKQUOTE', 'CENTER', 'DD',      'DIR',       'DIV', 
26551        'DL',      'DT',         'H1',     'H2',      'H3',        'H4', 
26552        'H5',      'H6',         'HR',     'ISINDEX', 'LISTING',   'MARQUEE', 
26553        'MENU',    'MULTICOL',   'OL',     'P',       'PLAINTEXT', 'PRE', 
26554        'TABLE',   'UL',         'XMP', 
26555        
26556        'CAPTION', 'COL', 'COLGROUP', 'TBODY', 'TD', 'TFOOT', 'TH', 
26557       'THEAD',   'TR', 
26558      
26559       'DIR', 'MENU', 'OL', 'UL', 'DL',
26560        
26561       'EMBED',  'OBJECT'
26562 ];
26563
26564
26565 Roo.HtmlEditorCore.black = [
26566     //    'embed',  'object', // enable - backend responsiblity to clean thiese
26567         'APPLET', // 
26568         'BASE',   'BASEFONT', 'BGSOUND', 'BLINK',  'BODY', 
26569         'FRAME',  'FRAMESET', 'HEAD',    'HTML',   'ILAYER', 
26570         'IFRAME', 'LAYER',  'LINK',     'META',    'OBJECT',   
26571         'SCRIPT', 'STYLE' ,'TITLE',  'XML',
26572         //'FONT' // CLEAN LATER..
26573         'COLGROUP', 'COL'   // messy tables.
26574         
26575         
26576 ];
26577 Roo.HtmlEditorCore.clean = [ // ?? needed???
26578      'SCRIPT', 'STYLE', 'TITLE', 'XML'
26579 ];
26580 Roo.HtmlEditorCore.tag_remove = [
26581     'FONT', 'TBODY'  
26582 ];
26583 // attributes..
26584
26585 Roo.HtmlEditorCore.ablack = [
26586     'on'
26587 ];
26588     
26589 Roo.HtmlEditorCore.aclean = [ 
26590     'action', 'background', 'codebase', 'dynsrc', 'href', 'lowsrc' 
26591 ];
26592
26593 // protocols..
26594 Roo.HtmlEditorCore.pwhite= [
26595         'http',  'https',  'mailto'
26596 ];
26597
26598 // white listed style attributes.
26599 Roo.HtmlEditorCore.cwhite= [
26600       //  'text-align', /// default is to allow most things..
26601       
26602          
26603 //        'font-size'//??
26604 ];
26605
26606 // black listed style attributes.
26607 Roo.HtmlEditorCore.cblack= [
26608       //  'font-size' -- this can be set by the project 
26609 ];
26610
26611
26612
26613
26614     //<script type="text/javascript">
26615
26616 /*
26617  * Ext JS Library 1.1.1
26618  * Copyright(c) 2006-2007, Ext JS, LLC.
26619  * Licence LGPL
26620  * 
26621  */
26622  
26623  
26624 Roo.form.HtmlEditor = function(config){
26625     
26626     
26627     
26628     Roo.form.HtmlEditor.superclass.constructor.call(this, config);
26629     
26630     if (!this.toolbars) {
26631         this.toolbars = [];
26632     }
26633     this.editorcore = new Roo.HtmlEditorCore(Roo.apply({ owner : this} , config));
26634     
26635     
26636 };
26637
26638 /**
26639  * @class Roo.form.HtmlEditor
26640  * @extends Roo.form.Field
26641  * Provides a lightweight HTML Editor component.
26642  *
26643  * This has been tested on Fireforx / Chrome.. IE may not be so great..
26644  * 
26645  * <br><br><b>Note: The focus/blur and validation marking functionality inherited from Ext.form.Field is NOT
26646  * supported by this editor.</b><br/><br/>
26647  * An Editor is a sensitive component that can't be used in all spots standard fields can be used. Putting an Editor within
26648  * any element that has display set to 'none' can cause problems in Safari and Firefox.<br/><br/>
26649  */
26650 Roo.extend(Roo.form.HtmlEditor, Roo.form.Field, {
26651     /**
26652      * @cfg {Boolean} clearUp
26653      */
26654     clearUp : true,
26655       /**
26656      * @cfg {Array} toolbars Array of toolbars. - defaults to just the Standard one
26657      */
26658     toolbars : false,
26659    
26660      /**
26661      * @cfg {String} resizable  's' or 'se' or 'e' - wrapps the element in a
26662      *                        Roo.resizable.
26663      */
26664     resizable : false,
26665      /**
26666      * @cfg {Number} height (in pixels)
26667      */   
26668     height: 300,
26669    /**
26670      * @cfg {Number} width (in pixels)
26671      */   
26672     width: 500,
26673     
26674     /**
26675      * @cfg {Array} stylesheets url of stylesheets. set to [] to disable stylesheets - this is usally a good idea  rootURL + '/roojs1/css/undoreset.css',   .
26676      * 
26677      */
26678     stylesheets: false,
26679     
26680     
26681      /**
26682      * @cfg {Array} blacklist of css styles style attributes (blacklist overrides whitelist)
26683      * 
26684      */
26685     cblack: false,
26686     /**
26687      * @cfg {Array} whitelist of css styles style attributes (blacklist overrides whitelist)
26688      * 
26689      */
26690     cwhite: false,
26691     
26692      /**
26693      * @cfg {Array} blacklist of html tags - in addition to standard blacklist.
26694      * 
26695      */
26696     black: false,
26697     /**
26698      * @cfg {Array} whitelist of html tags - in addition to statndard whitelist
26699      * 
26700      */
26701     white: false,
26702     /**
26703      * @cfg {boolean} allowComments - default false - allow comments in HTML source - by default they are stripped - if you are editing email you may need this.
26704      */
26705     allowComments: false,
26706     /**
26707      * @cfg {boolean} enableBlocks - default true - if the block editor (table and figure should be enabled)
26708      */
26709     enableBlocks : true,
26710     
26711     /**
26712      * @cfg {boolean} autoClean - default true - loading and saving will remove quite a bit of formating,
26713      *         if you are doing an email editor, this probably needs disabling, it's designed
26714      */
26715     autoClean: true,
26716     /**
26717      * @cfg {string} bodyCls default '' default classes to add to body of editable area - usually undoreset is a good start..
26718      */
26719     bodyCls : '',
26720     /**
26721      * @cfg {String} language default en - language of text (usefull for rtl languages)
26722      * 
26723      */
26724     language: 'en',
26725     
26726      
26727     // id of frame..
26728     frameId: false,
26729     
26730     // private properties
26731     validationEvent : false,
26732     deferHeight: true,
26733     initialized : false,
26734     activated : false,
26735     
26736     onFocus : Roo.emptyFn,
26737     iframePad:3,
26738     hideMode:'offsets',
26739     
26740     actionMode : 'container', // defaults to hiding it...
26741     
26742     defaultAutoCreate : { // modified by initCompnoent..
26743         tag: "textarea",
26744         style:"width:500px;height:300px;",
26745         autocomplete: "new-password"
26746     },
26747
26748     // private
26749     initComponent : function(){
26750         this.addEvents({
26751             /**
26752              * @event initialize
26753              * Fires when the editor is fully initialized (including the iframe)
26754              * @param {HtmlEditor} this
26755              */
26756             initialize: true,
26757             /**
26758              * @event activate
26759              * Fires when the editor is first receives the focus. Any insertion must wait
26760              * until after this event.
26761              * @param {HtmlEditor} this
26762              */
26763             activate: true,
26764              /**
26765              * @event beforesync
26766              * Fires before the textarea is updated with content from the editor iframe. Return false
26767              * to cancel the sync.
26768              * @param {HtmlEditor} this
26769              * @param {String} html
26770              */
26771             beforesync: true,
26772              /**
26773              * @event beforepush
26774              * Fires before the iframe editor is updated with content from the textarea. Return false
26775              * to cancel the push.
26776              * @param {HtmlEditor} this
26777              * @param {String} html
26778              */
26779             beforepush: true,
26780              /**
26781              * @event sync
26782              * Fires when the textarea is updated with content from the editor iframe.
26783              * @param {HtmlEditor} this
26784              * @param {String} html
26785              */
26786             sync: true,
26787              /**
26788              * @event push
26789              * Fires when the iframe editor is updated with content from the textarea.
26790              * @param {HtmlEditor} this
26791              * @param {String} html
26792              */
26793             push: true,
26794              /**
26795              * @event editmodechange
26796              * Fires when the editor switches edit modes
26797              * @param {HtmlEditor} this
26798              * @param {Boolean} sourceEdit True if source edit, false if standard editing.
26799              */
26800             editmodechange: true,
26801             /**
26802              * @event editorevent
26803              * Fires when on any editor (mouse up/down cursor movement etc.) - used for toolbar hooks.
26804              * @param {HtmlEditor} this
26805              */
26806             editorevent: true,
26807             /**
26808              * @event firstfocus
26809              * Fires when on first focus - needed by toolbars..
26810              * @param {HtmlEditor} this
26811              */
26812             firstfocus: true,
26813             /**
26814              * @event autosave
26815              * Auto save the htmlEditor value as a file into Events
26816              * @param {HtmlEditor} this
26817              */
26818             autosave: true,
26819             /**
26820              * @event savedpreview
26821              * preview the saved version of htmlEditor
26822              * @param {HtmlEditor} this
26823              */
26824             savedpreview: true,
26825             
26826             /**
26827             * @event stylesheetsclick
26828             * Fires when press the Sytlesheets button
26829             * @param {Roo.HtmlEditorCore} this
26830             */
26831             stylesheetsclick: true,
26832             /**
26833             * @event paste
26834             * Fires when press user pastes into the editor
26835             * @param {Roo.HtmlEditorCore} this
26836             */
26837             paste: true 
26838         });
26839         this.defaultAutoCreate =  {
26840             tag: "textarea",
26841             style:'width: ' + this.width + 'px;height: ' + this.height + 'px;',
26842             autocomplete: "new-password"
26843         };
26844     },
26845
26846     /**
26847      * Protected method that will not generally be called directly. It
26848      * is called when the editor creates its toolbar. Override this method if you need to
26849      * add custom toolbar buttons.
26850      * @param {HtmlEditor} editor
26851      */
26852     createToolbar : function(editor){
26853         Roo.log("create toolbars");
26854         if (!editor.toolbars || !editor.toolbars.length) {
26855             editor.toolbars = [ new Roo.form.HtmlEditor.ToolbarStandard() ]; // can be empty?
26856         }
26857         
26858         for (var i =0 ; i < editor.toolbars.length;i++) {
26859             editor.toolbars[i] = Roo.factory(
26860                     typeof(editor.toolbars[i]) == 'string' ?
26861                         { xtype: editor.toolbars[i]} : editor.toolbars[i],
26862                 Roo.form.HtmlEditor);
26863             editor.toolbars[i].init(editor);
26864         }
26865          
26866         
26867     },
26868     /**
26869      * get the Context selected node
26870      * @returns {DomElement|boolean} selected node if active or false if none
26871      * 
26872      */
26873     getSelectedNode : function()
26874     {
26875         if (this.toolbars.length < 2 || !this.toolbars[1].tb) {
26876             return false;
26877         }
26878         return this.toolbars[1].tb.selectedNode;
26879     
26880     },
26881     // private
26882     onRender : function(ct, position)
26883     {
26884         var _t = this;
26885         Roo.form.HtmlEditor.superclass.onRender.call(this, ct, position);
26886         
26887         this.wrap = this.el.wrap({
26888             cls:'x-html-editor-wrap', cn:{cls:'x-html-editor-tb'}
26889         });
26890         
26891         this.editorcore.onRender(ct, position);
26892          
26893         if (this.resizable) {
26894             this.resizeEl = new Roo.Resizable(this.wrap, {
26895                 pinned : true,
26896                 wrap: true,
26897                 dynamic : true,
26898                 minHeight : this.height,
26899                 height: this.height,
26900                 handles : this.resizable,
26901                 width: this.width,
26902                 listeners : {
26903                     resize : function(r, w, h) {
26904                         _t.onResize(w,h); // -something
26905                     }
26906                 }
26907             });
26908             
26909         }
26910         this.createToolbar(this);
26911        
26912         
26913         if(!this.width){
26914             this.setSize(this.wrap.getSize());
26915         }
26916         if (this.resizeEl) {
26917             this.resizeEl.resizeTo.defer(100, this.resizeEl,[ this.width,this.height ] );
26918             // should trigger onReize..
26919         }
26920         
26921         this.keyNav = new Roo.KeyNav(this.el, {
26922             
26923             "tab" : function(e){
26924                 e.preventDefault();
26925                 
26926                 var value = this.getValue();
26927                 
26928                 var start = this.el.dom.selectionStart;
26929                 var end = this.el.dom.selectionEnd;
26930                 
26931                 if(!e.shiftKey){
26932                     
26933                     this.setValue(value.substring(0, start) + "\t" + value.substring(end));
26934                     this.el.dom.setSelectionRange(end + 1, end + 1);
26935                     return;
26936                 }
26937                 
26938                 var f = value.substring(0, start).split("\t");
26939                 
26940                 if(f.pop().length != 0){
26941                     return;
26942                 }
26943                 
26944                 this.setValue(f.join("\t") + value.substring(end));
26945                 this.el.dom.setSelectionRange(start - 1, start - 1);
26946                 
26947             },
26948             
26949             "home" : function(e){
26950                 e.preventDefault();
26951                 
26952                 var curr = this.el.dom.selectionStart;
26953                 var lines = this.getValue().split("\n");
26954                 
26955                 if(!lines.length){
26956                     return;
26957                 }
26958                 
26959                 if(e.ctrlKey){
26960                     this.el.dom.setSelectionRange(0, 0);
26961                     return;
26962                 }
26963                 
26964                 var pos = 0;
26965                 
26966                 for (var i = 0; i < lines.length;i++) {
26967                     pos += lines[i].length;
26968                     
26969                     if(i != 0){
26970                         pos += 1;
26971                     }
26972                     
26973                     if(pos < curr){
26974                         continue;
26975                     }
26976                     
26977                     pos -= lines[i].length;
26978                     
26979                     break;
26980                 }
26981                 
26982                 if(!e.shiftKey){
26983                     this.el.dom.setSelectionRange(pos, pos);
26984                     return;
26985                 }
26986                 
26987                 this.el.dom.selectionStart = pos;
26988                 this.el.dom.selectionEnd = curr;
26989             },
26990             
26991             "end" : function(e){
26992                 e.preventDefault();
26993                 
26994                 var curr = this.el.dom.selectionStart;
26995                 var lines = this.getValue().split("\n");
26996                 
26997                 if(!lines.length){
26998                     return;
26999                 }
27000                 
27001                 if(e.ctrlKey){
27002                     this.el.dom.setSelectionRange(this.getValue().length, this.getValue().length);
27003                     return;
27004                 }
27005                 
27006                 var pos = 0;
27007                 
27008                 for (var i = 0; i < lines.length;i++) {
27009                     
27010                     pos += lines[i].length;
27011                     
27012                     if(i != 0){
27013                         pos += 1;
27014                     }
27015                     
27016                     if(pos < curr){
27017                         continue;
27018                     }
27019                     
27020                     break;
27021                 }
27022                 
27023                 if(!e.shiftKey){
27024                     this.el.dom.setSelectionRange(pos, pos);
27025                     return;
27026                 }
27027                 
27028                 this.el.dom.selectionStart = curr;
27029                 this.el.dom.selectionEnd = pos;
27030             },
27031
27032             scope : this,
27033
27034             doRelay : function(foo, bar, hname){
27035                 return Roo.KeyNav.prototype.doRelay.apply(this, arguments);
27036             },
27037
27038             forceKeyDown: true
27039         });
27040         
27041 //        if(this.autosave && this.w){
27042 //            this.autoSaveFn = setInterval(this.autosave, 1000);
27043 //        }
27044     },
27045
27046     // private
27047     onResize : function(w, h)
27048     {
27049         Roo.form.HtmlEditor.superclass.onResize.apply(this, arguments);
27050         var ew = false;
27051         var eh = false;
27052         
27053         if(this.el ){
27054             if(typeof w == 'number'){
27055                 var aw = w - this.wrap.getFrameWidth('lr');
27056                 this.el.setWidth(this.adjustWidth('textarea', aw));
27057                 ew = aw;
27058             }
27059             if(typeof h == 'number'){
27060                 var tbh = 0;
27061                 for (var i =0; i < this.toolbars.length;i++) {
27062                     // fixme - ask toolbars for heights?
27063                     tbh += this.toolbars[i].tb.el.getHeight();
27064                     if (this.toolbars[i].footer) {
27065                         tbh += this.toolbars[i].footer.el.getHeight();
27066                     }
27067                 }
27068                 
27069                 
27070                 
27071                 
27072                 var ah = h - this.wrap.getFrameWidth('tb') - tbh;// this.tb.el.getHeight();
27073                 ah -= 5; // knock a few pixes off for look..
27074 //                Roo.log(ah);
27075                 this.el.setHeight(this.adjustWidth('textarea', ah));
27076                 var eh = ah;
27077             }
27078         }
27079         Roo.log('onResize:' + [w,h,ew,eh].join(',') );
27080         this.editorcore.onResize(ew,eh);
27081         
27082     },
27083
27084     /**
27085      * Toggles the editor between standard and source edit mode.
27086      * @param {Boolean} sourceEdit (optional) True for source edit, false for standard
27087      */
27088     toggleSourceEdit : function(sourceEditMode)
27089     {
27090         this.editorcore.toggleSourceEdit(sourceEditMode);
27091         
27092         if(this.editorcore.sourceEditMode){
27093             Roo.log('editor - showing textarea');
27094             
27095 //            Roo.log('in');
27096 //            Roo.log(this.syncValue());
27097             this.editorcore.syncValue();
27098             this.el.removeClass('x-hidden');
27099             this.el.dom.removeAttribute('tabIndex');
27100             this.el.focus();
27101             this.el.dom.scrollTop = 0;
27102             
27103             
27104             for (var i = 0; i < this.toolbars.length; i++) {
27105                 if(this.toolbars[i] instanceof Roo.form.HtmlEditor.ToolbarContext){
27106                     this.toolbars[i].tb.hide();
27107                     this.toolbars[i].footer.hide();
27108                 }
27109             }
27110             
27111         }else{
27112             Roo.log('editor - hiding textarea');
27113 //            Roo.log('out')
27114 //            Roo.log(this.pushValue()); 
27115             this.editorcore.pushValue();
27116             
27117             this.el.addClass('x-hidden');
27118             this.el.dom.setAttribute('tabIndex', -1);
27119             
27120             for (var i = 0; i < this.toolbars.length; i++) {
27121                 if(this.toolbars[i] instanceof Roo.form.HtmlEditor.ToolbarContext){
27122                     this.toolbars[i].tb.show();
27123                     this.toolbars[i].footer.show();
27124                 }
27125             }
27126             
27127             //this.deferFocus();
27128         }
27129         
27130         this.setSize(this.wrap.getSize());
27131         this.onResize(this.wrap.getSize().width, this.wrap.getSize().height);
27132         
27133         this.fireEvent('editmodechange', this, this.editorcore.sourceEditMode);
27134     },
27135  
27136     // private (for BoxComponent)
27137     adjustSize : Roo.BoxComponent.prototype.adjustSize,
27138
27139     // private (for BoxComponent)
27140     getResizeEl : function(){
27141         return this.wrap;
27142     },
27143
27144     // private (for BoxComponent)
27145     getPositionEl : function(){
27146         return this.wrap;
27147     },
27148
27149     // private
27150     initEvents : function(){
27151         this.originalValue = this.getValue();
27152     },
27153
27154     /**
27155      * Overridden and disabled. The editor element does not support standard valid/invalid marking. @hide
27156      * @method
27157      */
27158     markInvalid : Roo.emptyFn,
27159     /**
27160      * Overridden and disabled. The editor element does not support standard valid/invalid marking. @hide
27161      * @method
27162      */
27163     clearInvalid : Roo.emptyFn,
27164
27165     setValue : function(v){
27166         Roo.form.HtmlEditor.superclass.setValue.call(this, v);
27167         this.editorcore.pushValue();
27168     },
27169
27170     /**
27171      * update the language in the body - really done by core
27172      * @param {String} language - eg. en / ar / zh-CN etc..
27173      */
27174     updateLanguage : function(lang)
27175     {
27176         this.language = lang;
27177         this.editorcore.language = lang;
27178         this.editorcore.updateLanguage();
27179      
27180     },
27181     // private
27182     deferFocus : function(){
27183         this.focus.defer(10, this);
27184     },
27185
27186     // doc'ed in Field
27187     focus : function(){
27188         this.editorcore.focus();
27189         
27190     },
27191       
27192
27193     // private
27194     onDestroy : function(){
27195         
27196         
27197         
27198         if(this.rendered){
27199             
27200             for (var i =0; i < this.toolbars.length;i++) {
27201                 // fixme - ask toolbars for heights?
27202                 this.toolbars[i].onDestroy();
27203             }
27204             
27205             this.wrap.dom.innerHTML = '';
27206             this.wrap.remove();
27207         }
27208     },
27209
27210     // private
27211     onFirstFocus : function(){
27212         //Roo.log("onFirstFocus");
27213         this.editorcore.onFirstFocus();
27214          for (var i =0; i < this.toolbars.length;i++) {
27215             this.toolbars[i].onFirstFocus();
27216         }
27217         
27218     },
27219     
27220     // private
27221     syncValue : function()
27222     {
27223         this.editorcore.syncValue();
27224     },
27225     
27226     pushValue : function()
27227     {
27228         this.editorcore.pushValue();
27229     },
27230     
27231     setStylesheets : function(stylesheets)
27232     {
27233         this.editorcore.setStylesheets(stylesheets);
27234     },
27235     
27236     removeStylesheets : function()
27237     {
27238         this.editorcore.removeStylesheets();
27239     }
27240      
27241     
27242     // hide stuff that is not compatible
27243     /**
27244      * @event blur
27245      * @hide
27246      */
27247     /**
27248      * @event change
27249      * @hide
27250      */
27251     /**
27252      * @event focus
27253      * @hide
27254      */
27255     /**
27256      * @event specialkey
27257      * @hide
27258      */
27259     /**
27260      * @cfg {String} fieldClass @hide
27261      */
27262     /**
27263      * @cfg {String} focusClass @hide
27264      */
27265     /**
27266      * @cfg {String} autoCreate @hide
27267      */
27268     /**
27269      * @cfg {String} inputType @hide
27270      */
27271     /**
27272      * @cfg {String} invalidClass @hide
27273      */
27274     /**
27275      * @cfg {String} invalidText @hide
27276      */
27277     /**
27278      * @cfg {String} msgFx @hide
27279      */
27280     /**
27281      * @cfg {String} validateOnBlur @hide
27282      */
27283 });
27284  
27285     /*
27286  * Based on
27287  * Ext JS Library 1.1.1
27288  * Copyright(c) 2006-2007, Ext JS, LLC.
27289  *  
27290  
27291  */
27292
27293 /**
27294  * @class Roo.form.HtmlEditor.ToolbarStandard
27295  * Basic Toolbar
27296
27297  * Usage:
27298  *
27299  new Roo.form.HtmlEditor({
27300     ....
27301     toolbars : [
27302         new Roo.form.HtmlEditorToolbar1({
27303             disable : { fonts: 1 , format: 1, ..., ... , ...],
27304             btns : [ .... ]
27305         })
27306     }
27307      
27308  * 
27309  * @cfg {Object} disable List of elements to disable..
27310  * @cfg {Roo.Toolbar.Item|Roo.Toolbar.Button|Roo.Toolbar.SplitButton|Roo.form.Field} btns[] List of additional buttons.
27311  * 
27312  * 
27313  * NEEDS Extra CSS? 
27314  * .x-html-editor-tb .x-edit-none .x-btn-text { background: none; }
27315  */
27316  
27317 Roo.form.HtmlEditor.ToolbarStandard = function(config)
27318 {
27319     
27320     Roo.apply(this, config);
27321     
27322     // default disabled, based on 'good practice'..
27323     this.disable = this.disable || {};
27324     Roo.applyIf(this.disable, {
27325         fontSize : true,
27326         colors : true,
27327         specialElements : true
27328     });
27329     
27330     
27331     //Roo.form.HtmlEditorToolbar1.superclass.constructor.call(this, editor.wrap.dom.firstChild, [], config);
27332     // dont call parent... till later.
27333 }
27334
27335 Roo.form.HtmlEditor.ToolbarStandard.prototype = {
27336     
27337     tb: false,
27338     
27339     rendered: false,
27340     
27341     editor : false,
27342     editorcore : false,
27343     /**
27344      * @cfg {Object} disable  List of toolbar elements to disable
27345          
27346      */
27347     disable : false,
27348     
27349     
27350      /**
27351      * @cfg {String} createLinkText The default text for the create link prompt
27352      */
27353     createLinkText : 'Please enter the URL for the link:',
27354     /**
27355      * @cfg {String} defaultLinkValue The default value for the create link prompt (defaults to http:/ /)
27356      */
27357     defaultLinkValue : 'http:/'+'/',
27358    
27359     
27360       /**
27361      * @cfg {Array} fontFamilies An array of available font families
27362      */
27363     fontFamilies : [
27364         'Arial',
27365         'Courier New',
27366         'Tahoma',
27367         'Times New Roman',
27368         'Verdana'
27369     ],
27370     
27371     specialChars : [
27372            "&#169;",
27373           "&#174;",     
27374           "&#8482;",    
27375           "&#163;" ,    
27376          // "&#8212;",    
27377           "&#8230;",    
27378           "&#247;" ,    
27379         //  "&#225;" ,     ?? a acute?
27380            "&#8364;"    , //Euro
27381        //   "&#8220;"    ,
27382         //  "&#8221;"    ,
27383         //  "&#8226;"    ,
27384           "&#176;"  //   , // degrees
27385
27386          // "&#233;"     , // e ecute
27387          // "&#250;"     , // u ecute?
27388     ],
27389     
27390     specialElements : [
27391         {
27392             text: "Insert Table",
27393             xtype: 'MenuItem',
27394             xns : Roo.Menu,
27395             ihtml :  '<table><tr><td>Cell</td></tr></table>' 
27396                 
27397         },
27398         {    
27399             text: "Insert Image",
27400             xtype: 'MenuItem',
27401             xns : Roo.Menu,
27402             ihtml : '<img src="about:blank"/>'
27403             
27404         }
27405         
27406          
27407     ],
27408     
27409     
27410     inputElements : [ 
27411             "form", "input:text", "input:hidden", "input:checkbox", "input:radio", "input:password", 
27412             "input:submit", "input:button", "select", "textarea", "label" ],
27413     formats : [
27414         ["p"] ,  
27415         ["h1"],["h2"],["h3"],["h4"],["h5"],["h6"], 
27416         ["pre"],[ "code"], 
27417         ["abbr"],[ "acronym"],[ "address"],[ "cite"],[ "samp"],[ "var"],
27418         ['div'],['span'],
27419         ['sup'],['sub']
27420     ],
27421     
27422     cleanStyles : [
27423         "font-size"
27424     ],
27425      /**
27426      * @cfg {String} defaultFont default font to use.
27427      */
27428     defaultFont: 'tahoma',
27429    
27430     fontSelect : false,
27431     
27432     
27433     formatCombo : false,
27434     
27435     init : function(editor)
27436     {
27437         this.editor = editor;
27438         this.editorcore = editor.editorcore ? editor.editorcore : editor;
27439         var editorcore = this.editorcore;
27440         
27441         var _t = this;
27442         
27443         var fid = editorcore.frameId;
27444         var etb = this;
27445         function btn(id, toggle, handler){
27446             var xid = fid + '-'+ id ;
27447             return {
27448                 id : xid,
27449                 cmd : id,
27450                 cls : 'x-btn-icon x-edit-'+id,
27451                 enableToggle:toggle !== false,
27452                 scope: _t, // was editor...
27453                 handler:handler||_t.relayBtnCmd,
27454                 clickEvent:'mousedown',
27455                 tooltip: etb.buttonTips[id] || undefined, ///tips ???
27456                 tabIndex:-1
27457             };
27458         }
27459         
27460         
27461         
27462         var tb = new Roo.Toolbar(editor.wrap.dom.firstChild);
27463         this.tb = tb;
27464          // stop form submits
27465         tb.el.on('click', function(e){
27466             e.preventDefault(); // what does this do?
27467         });
27468
27469         if(!this.disable.font) { // && !Roo.isSafari){
27470             /* why no safari for fonts 
27471             editor.fontSelect = tb.el.createChild({
27472                 tag:'select',
27473                 tabIndex: -1,
27474                 cls:'x-font-select',
27475                 html: this.createFontOptions()
27476             });
27477             
27478             editor.fontSelect.on('change', function(){
27479                 var font = editor.fontSelect.dom.value;
27480                 editor.relayCmd('fontname', font);
27481                 editor.deferFocus();
27482             }, editor);
27483             
27484             tb.add(
27485                 editor.fontSelect.dom,
27486                 '-'
27487             );
27488             */
27489             
27490         };
27491         if(!this.disable.formats){
27492             this.formatCombo = new Roo.form.ComboBox({
27493                 store: new Roo.data.SimpleStore({
27494                     id : 'tag',
27495                     fields: ['tag'],
27496                     data : this.formats // from states.js
27497                 }),
27498                 blockFocus : true,
27499                 name : '',
27500                 //autoCreate : {tag: "div",  size: "20"},
27501                 displayField:'tag',
27502                 typeAhead: false,
27503                 mode: 'local',
27504                 editable : false,
27505                 triggerAction: 'all',
27506                 emptyText:'Add tag',
27507                 selectOnFocus:true,
27508                 width:135,
27509                 listeners : {
27510                     'select': function(c, r, i) {
27511                         editorcore.insertTag(r.get('tag'));
27512                         editor.focus();
27513                     }
27514                 }
27515
27516             });
27517             tb.addField(this.formatCombo);
27518             
27519         }
27520         
27521         if(!this.disable.format){
27522             tb.add(
27523                 btn('bold'),
27524                 btn('italic'),
27525                 btn('underline'),
27526                 btn('strikethrough')
27527             );
27528         };
27529         if(!this.disable.fontSize){
27530             tb.add(
27531                 '-',
27532                 
27533                 
27534                 btn('increasefontsize', false, editorcore.adjustFont),
27535                 btn('decreasefontsize', false, editorcore.adjustFont)
27536             );
27537         };
27538         
27539         
27540         if(!this.disable.colors){
27541             tb.add(
27542                 '-', {
27543                     id:editorcore.frameId +'-forecolor',
27544                     cls:'x-btn-icon x-edit-forecolor',
27545                     clickEvent:'mousedown',
27546                     tooltip: this.buttonTips['forecolor'] || undefined,
27547                     tabIndex:-1,
27548                     menu : new Roo.menu.ColorMenu({
27549                         allowReselect: true,
27550                         focus: Roo.emptyFn,
27551                         value:'000000',
27552                         plain:true,
27553                         selectHandler: function(cp, color){
27554                             editorcore.execCmd('forecolor', Roo.isSafari || Roo.isIE ? '#'+color : color);
27555                             editor.deferFocus();
27556                         },
27557                         scope: editorcore,
27558                         clickEvent:'mousedown'
27559                     })
27560                 }, {
27561                     id:editorcore.frameId +'backcolor',
27562                     cls:'x-btn-icon x-edit-backcolor',
27563                     clickEvent:'mousedown',
27564                     tooltip: this.buttonTips['backcolor'] || undefined,
27565                     tabIndex:-1,
27566                     menu : new Roo.menu.ColorMenu({
27567                         focus: Roo.emptyFn,
27568                         value:'FFFFFF',
27569                         plain:true,
27570                         allowReselect: true,
27571                         selectHandler: function(cp, color){
27572                             if(Roo.isGecko){
27573                                 editorcore.execCmd('useCSS', false);
27574                                 editorcore.execCmd('hilitecolor', color);
27575                                 editorcore.execCmd('useCSS', true);
27576                                 editor.deferFocus();
27577                             }else{
27578                                 editorcore.execCmd(Roo.isOpera ? 'hilitecolor' : 'backcolor', 
27579                                     Roo.isSafari || Roo.isIE ? '#'+color : color);
27580                                 editor.deferFocus();
27581                             }
27582                         },
27583                         scope:editorcore,
27584                         clickEvent:'mousedown'
27585                     })
27586                 }
27587             );
27588         };
27589         // now add all the items...
27590         
27591
27592         if(!this.disable.alignments){
27593             tb.add(
27594                 '-',
27595                 btn('justifyleft'),
27596                 btn('justifycenter'),
27597                 btn('justifyright')
27598             );
27599         };
27600
27601         //if(!Roo.isSafari){
27602             if(!this.disable.links){
27603                 tb.add(
27604                     '-',
27605                     btn('createlink', false, this.createLink)    /// MOVE TO HERE?!!?!?!?!
27606                 );
27607             };
27608
27609             if(!this.disable.lists){
27610                 tb.add(
27611                     '-',
27612                     btn('insertorderedlist'),
27613                     btn('insertunorderedlist')
27614                 );
27615             }
27616             if(!this.disable.sourceEdit){
27617                 tb.add(
27618                     '-',
27619                     btn('sourceedit', true, function(btn){
27620                         this.toggleSourceEdit(btn.pressed);
27621                     })
27622                 );
27623             }
27624         //}
27625         
27626         var smenu = { };
27627         // special menu.. - needs to be tidied up..
27628         if (!this.disable.special) {
27629             smenu = {
27630                 text: "&#169;",
27631                 cls: 'x-edit-none',
27632                 
27633                 menu : {
27634                     items : []
27635                 }
27636             };
27637             for (var i =0; i < this.specialChars.length; i++) {
27638                 smenu.menu.items.push({
27639                     
27640                     html: this.specialChars[i],
27641                     handler: function(a,b) {
27642                         editorcore.insertAtCursor(String.fromCharCode(a.html.replace('&#','').replace(';', '')));
27643                         //editor.insertAtCursor(a.html);
27644                         
27645                     },
27646                     tabIndex:-1
27647                 });
27648             }
27649             
27650             
27651             tb.add(smenu);
27652             
27653             
27654         }
27655         
27656         var cmenu = { };
27657         if (!this.disable.cleanStyles) {
27658             cmenu = {
27659                 cls: 'x-btn-icon x-btn-clear',
27660                 
27661                 menu : {
27662                     items : []
27663                 }
27664             };
27665             for (var i =0; i < this.cleanStyles.length; i++) {
27666                 cmenu.menu.items.push({
27667                     actiontype : this.cleanStyles[i],
27668                     html: 'Remove ' + this.cleanStyles[i],
27669                     handler: function(a,b) {
27670 //                        Roo.log(a);
27671 //                        Roo.log(b);
27672                         var c = Roo.get(editorcore.doc.body);
27673                         c.select('[style]').each(function(s) {
27674                             s.dom.style.removeProperty(a.actiontype);
27675                         });
27676                         editorcore.syncValue();
27677                     },
27678                     tabIndex:-1
27679                 });
27680             }
27681             cmenu.menu.items.push({
27682                 actiontype : 'tablewidths',
27683                 html: 'Remove Table Widths',
27684                 handler: function(a,b) {
27685                     editorcore.cleanTableWidths();
27686                     editorcore.syncValue();
27687                 },
27688                 tabIndex:-1
27689             });
27690             cmenu.menu.items.push({
27691                 actiontype : 'word',
27692                 html: 'Remove MS Word Formating',
27693                 handler: function(a,b) {
27694                     editorcore.cleanWord();
27695                     editorcore.syncValue();
27696                 },
27697                 tabIndex:-1
27698             });
27699             
27700             cmenu.menu.items.push({
27701                 actiontype : 'all',
27702                 html: 'Remove All Styles',
27703                 handler: function(a,b) {
27704                     
27705                     var c = Roo.get(editorcore.doc.body);
27706                     c.select('[style]').each(function(s) {
27707                         s.dom.removeAttribute('style');
27708                     });
27709                     editorcore.syncValue();
27710                 },
27711                 tabIndex:-1
27712             });
27713             
27714             cmenu.menu.items.push({
27715                 actiontype : 'all',
27716                 html: 'Remove All CSS Classes',
27717                 handler: function(a,b) {
27718                     
27719                     var c = Roo.get(editorcore.doc.body);
27720                     c.select('[class]').each(function(s) {
27721                         s.dom.removeAttribute('class');
27722                     });
27723                     editorcore.cleanWord();
27724                     editorcore.syncValue();
27725                 },
27726                 tabIndex:-1
27727             });
27728             
27729              cmenu.menu.items.push({
27730                 actiontype : 'tidy',
27731                 html: 'Tidy HTML Source',
27732                 handler: function(a,b) {
27733                     new Roo.htmleditor.Tidy(editorcore.doc.body);
27734                     editorcore.syncValue();
27735                 },
27736                 tabIndex:-1
27737             });
27738             
27739             
27740             tb.add(cmenu);
27741         }
27742          
27743         if (!this.disable.specialElements) {
27744             var semenu = {
27745                 text: "Other;",
27746                 cls: 'x-edit-none',
27747                 menu : {
27748                     items : []
27749                 }
27750             };
27751             for (var i =0; i < this.specialElements.length; i++) {
27752                 semenu.menu.items.push(
27753                     Roo.apply({ 
27754                         handler: function(a,b) {
27755                             editor.insertAtCursor(this.ihtml);
27756                         }
27757                     }, this.specialElements[i])
27758                 );
27759                     
27760             }
27761             
27762             tb.add(semenu);
27763             
27764             
27765         }
27766          
27767         
27768         if (this.btns) {
27769             for(var i =0; i< this.btns.length;i++) {
27770                 var b = Roo.factory(this.btns[i],this.btns[i].xns || Roo.form);
27771                 b.cls =  'x-edit-none';
27772                 
27773                 if(typeof(this.btns[i].cls) != 'undefined' && this.btns[i].cls.indexOf('x-init-enable') !== -1){
27774                     b.cls += ' x-init-enable';
27775                 }
27776                 
27777                 b.scope = editorcore;
27778                 tb.add(b);
27779             }
27780         
27781         }
27782         
27783         
27784         
27785         // disable everything...
27786         
27787         this.tb.items.each(function(item){
27788             
27789            if(
27790                 item.id != editorcore.frameId+ '-sourceedit' && 
27791                 (typeof(item.cls) != 'undefined' && item.cls.indexOf('x-init-enable') === -1)
27792             ){
27793                 
27794                 item.disable();
27795             }
27796         });
27797         this.rendered = true;
27798         
27799         // the all the btns;
27800         editor.on('editorevent', this.updateToolbar, this);
27801         // other toolbars need to implement this..
27802         //editor.on('editmodechange', this.updateToolbar, this);
27803     },
27804     
27805     
27806     relayBtnCmd : function(btn) {
27807         this.editorcore.relayCmd(btn.cmd);
27808     },
27809     // private used internally
27810     createLink : function(){
27811         //Roo.log("create link?");
27812         var ec = this.editorcore;
27813         var ar = ec.getAllAncestors();
27814         var n = false;
27815         for(var i = 0;i< ar.length;i++) {
27816             if (ar[i] && ar[i].nodeName == 'A') {
27817                 n = ar[i];
27818                 break;
27819             }
27820         }
27821         
27822         (function() {
27823             
27824             Roo.MessageBox.show({
27825                 title : "Add / Edit Link URL",
27826                 msg : "Enter the url for the link",
27827                 buttons: Roo.MessageBox.OKCANCEL,
27828                 fn: function(btn, url){
27829                     if (btn != 'ok') {
27830                         return;
27831                     }
27832                     if(url && url != 'http:/'+'/'){
27833                         if (n) {
27834                             n.setAttribute('href', url);
27835                         } else {
27836                             ec.relayCmd('createlink', url);
27837                         }
27838                     }
27839                 },
27840                 minWidth:250,
27841                 prompt:true,
27842                 //multiline: multiline,
27843                 modal : true,
27844                 value :  n  ? n.getAttribute('href') : '' 
27845             });
27846             
27847              
27848         }).defer(100, this); // we have to defer this , otherwise the mouse click gives focus to the main window.
27849         
27850     },
27851
27852     
27853     /**
27854      * Protected method that will not generally be called directly. It triggers
27855      * a toolbar update by reading the markup state of the current selection in the editor.
27856      */
27857     updateToolbar: function(){
27858
27859         if(!this.editorcore.activated){
27860             this.editor.onFirstFocus();
27861             return;
27862         }
27863
27864         var btns = this.tb.items.map, 
27865             doc = this.editorcore.doc,
27866             frameId = this.editorcore.frameId;
27867
27868         if(!this.disable.font && !Roo.isSafari){
27869             /*
27870             var name = (doc.queryCommandValue('FontName')||this.editor.defaultFont).toLowerCase();
27871             if(name != this.fontSelect.dom.value){
27872                 this.fontSelect.dom.value = name;
27873             }
27874             */
27875         }
27876         if(!this.disable.format){
27877             btns[frameId + '-bold'].toggle(doc.queryCommandState('bold'));
27878             btns[frameId + '-italic'].toggle(doc.queryCommandState('italic'));
27879             btns[frameId + '-underline'].toggle(doc.queryCommandState('underline'));
27880             btns[frameId + '-strikethrough'].toggle(doc.queryCommandState('strikethrough'));
27881         }
27882         if(!this.disable.alignments){
27883             btns[frameId + '-justifyleft'].toggle(doc.queryCommandState('justifyleft'));
27884             btns[frameId + '-justifycenter'].toggle(doc.queryCommandState('justifycenter'));
27885             btns[frameId + '-justifyright'].toggle(doc.queryCommandState('justifyright'));
27886         }
27887         if(!Roo.isSafari && !this.disable.lists){
27888             btns[frameId + '-insertorderedlist'].toggle(doc.queryCommandState('insertorderedlist'));
27889             btns[frameId + '-insertunorderedlist'].toggle(doc.queryCommandState('insertunorderedlist'));
27890         }
27891         
27892         var ans = this.editorcore.getAllAncestors();
27893         if (this.formatCombo) {
27894             
27895             
27896             var store = this.formatCombo.store;
27897             this.formatCombo.setValue("");
27898             for (var i =0; i < ans.length;i++) {
27899                 if (ans[i] && store.query('tag',ans[i].tagName.toLowerCase(), false).length) {
27900                     // select it..
27901                     this.formatCombo.setValue(ans[i].tagName.toLowerCase());
27902                     break;
27903                 }
27904             }
27905         }
27906         
27907         
27908         
27909         // hides menus... - so this cant be on a menu...
27910         Roo.menu.MenuMgr.hideAll();
27911
27912         //this.editorsyncValue();
27913     },
27914    
27915     
27916     createFontOptions : function(){
27917         var buf = [], fs = this.fontFamilies, ff, lc;
27918         
27919         
27920         
27921         for(var i = 0, len = fs.length; i< len; i++){
27922             ff = fs[i];
27923             lc = ff.toLowerCase();
27924             buf.push(
27925                 '<option value="',lc,'" style="font-family:',ff,';"',
27926                     (this.defaultFont == lc ? ' selected="true">' : '>'),
27927                     ff,
27928                 '</option>'
27929             );
27930         }
27931         return buf.join('');
27932     },
27933     
27934     toggleSourceEdit : function(sourceEditMode){
27935         
27936         Roo.log("toolbar toogle");
27937         if(sourceEditMode === undefined){
27938             sourceEditMode = !this.sourceEditMode;
27939         }
27940         this.sourceEditMode = sourceEditMode === true;
27941         var btn = this.tb.items.get(this.editorcore.frameId +'-sourceedit');
27942         // just toggle the button?
27943         if(btn.pressed !== this.sourceEditMode){
27944             btn.toggle(this.sourceEditMode);
27945             return;
27946         }
27947         
27948         if(sourceEditMode){
27949             Roo.log("disabling buttons");
27950             this.tb.items.each(function(item){
27951                 if(item.cmd != 'sourceedit' && (typeof(item.cls) != 'undefined' && item.cls.indexOf('x-init-enable') === -1)){
27952                     item.disable();
27953                 }
27954             });
27955           
27956         }else{
27957             Roo.log("enabling buttons");
27958             if(this.editorcore.initialized){
27959                 this.tb.items.each(function(item){
27960                     item.enable();
27961                 });
27962                 // initialize 'blocks'
27963                 Roo.each(Roo.get(this.editorcore.doc.body).query('*[data-block]'), function(e) {
27964                     Roo.htmleditor.Block.factory(e).updateElement(e);
27965                 },this);
27966             
27967             }
27968             
27969         }
27970         Roo.log("calling toggole on editor");
27971         // tell the editor that it's been pressed..
27972         this.editor.toggleSourceEdit(sourceEditMode);
27973        
27974     },
27975      /**
27976      * Object collection of toolbar tooltips for the buttons in the editor. The key
27977      * is the command id associated with that button and the value is a valid QuickTips object.
27978      * For example:
27979 <pre><code>
27980 {
27981     bold : {
27982         title: 'Bold (Ctrl+B)',
27983         text: 'Make the selected text bold.',
27984         cls: 'x-html-editor-tip'
27985     },
27986     italic : {
27987         title: 'Italic (Ctrl+I)',
27988         text: 'Make the selected text italic.',
27989         cls: 'x-html-editor-tip'
27990     },
27991     ...
27992 </code></pre>
27993     * @type Object
27994      */
27995     buttonTips : {
27996         bold : {
27997             title: 'Bold (Ctrl+B)',
27998             text: 'Make the selected text bold.',
27999             cls: 'x-html-editor-tip'
28000         },
28001         italic : {
28002             title: 'Italic (Ctrl+I)',
28003             text: 'Make the selected text italic.',
28004             cls: 'x-html-editor-tip'
28005         },
28006         underline : {
28007             title: 'Underline (Ctrl+U)',
28008             text: 'Underline the selected text.',
28009             cls: 'x-html-editor-tip'
28010         },
28011         strikethrough : {
28012             title: 'Strikethrough',
28013             text: 'Strikethrough the selected text.',
28014             cls: 'x-html-editor-tip'
28015         },
28016         increasefontsize : {
28017             title: 'Grow Text',
28018             text: 'Increase the font size.',
28019             cls: 'x-html-editor-tip'
28020         },
28021         decreasefontsize : {
28022             title: 'Shrink Text',
28023             text: 'Decrease the font size.',
28024             cls: 'x-html-editor-tip'
28025         },
28026         backcolor : {
28027             title: 'Text Highlight Color',
28028             text: 'Change the background color of the selected text.',
28029             cls: 'x-html-editor-tip'
28030         },
28031         forecolor : {
28032             title: 'Font Color',
28033             text: 'Change the color of the selected text.',
28034             cls: 'x-html-editor-tip'
28035         },
28036         justifyleft : {
28037             title: 'Align Text Left',
28038             text: 'Align text to the left.',
28039             cls: 'x-html-editor-tip'
28040         },
28041         justifycenter : {
28042             title: 'Center Text',
28043             text: 'Center text in the editor.',
28044             cls: 'x-html-editor-tip'
28045         },
28046         justifyright : {
28047             title: 'Align Text Right',
28048             text: 'Align text to the right.',
28049             cls: 'x-html-editor-tip'
28050         },
28051         insertunorderedlist : {
28052             title: 'Bullet List',
28053             text: 'Start a bulleted list.',
28054             cls: 'x-html-editor-tip'
28055         },
28056         insertorderedlist : {
28057             title: 'Numbered List',
28058             text: 'Start a numbered list.',
28059             cls: 'x-html-editor-tip'
28060         },
28061         createlink : {
28062             title: 'Hyperlink',
28063             text: 'Make the selected text a hyperlink.',
28064             cls: 'x-html-editor-tip'
28065         },
28066         sourceedit : {
28067             title: 'Source Edit',
28068             text: 'Switch to source editing mode.',
28069             cls: 'x-html-editor-tip'
28070         }
28071     },
28072     // private
28073     onDestroy : function(){
28074         if(this.rendered){
28075             
28076             this.tb.items.each(function(item){
28077                 if(item.menu){
28078                     item.menu.removeAll();
28079                     if(item.menu.el){
28080                         item.menu.el.destroy();
28081                     }
28082                 }
28083                 item.destroy();
28084             });
28085              
28086         }
28087     },
28088     onFirstFocus: function() {
28089         this.tb.items.each(function(item){
28090            item.enable();
28091         });
28092     }
28093 };
28094
28095
28096
28097
28098 // <script type="text/javascript">
28099 /*
28100  * Based on
28101  * Ext JS Library 1.1.1
28102  * Copyright(c) 2006-2007, Ext JS, LLC.
28103  *  
28104  
28105  */
28106
28107  
28108 /**
28109  * @class Roo.form.HtmlEditor.ToolbarContext
28110  * Context Toolbar
28111  * 
28112  * Usage:
28113  *
28114  new Roo.form.HtmlEditor({
28115     ....
28116     toolbars : [
28117         { xtype: 'ToolbarStandard', styles : {} }
28118         { xtype: 'ToolbarContext', disable : {} }
28119     ]
28120 })
28121
28122      
28123  * 
28124  * @config : {Object} disable List of elements to disable.. (not done yet.)
28125  * @config : {Object} styles  Map of styles available.
28126  * 
28127  */
28128
28129 Roo.form.HtmlEditor.ToolbarContext = function(config)
28130 {
28131     
28132     Roo.apply(this, config);
28133     //Roo.form.HtmlEditorToolbar1.superclass.constructor.call(this, editor.wrap.dom.firstChild, [], config);
28134     // dont call parent... till later.
28135     this.styles = this.styles || {};
28136 }
28137
28138  
28139
28140 Roo.form.HtmlEditor.ToolbarContext.types = {
28141     'IMG' : [
28142         {
28143             name : 'width',
28144             title: "Width",
28145             width: 40
28146         },
28147         {
28148             name : 'height',
28149             title: "Height",
28150             width: 40
28151         },
28152         {
28153             name : 'align',
28154             title: "Align",
28155             opts : [ [""],[ "left"],[ "right"],[ "center"],[ "top"]],
28156             width : 80
28157             
28158         },
28159         {
28160             name : 'border',
28161             title: "Border",
28162             width: 40
28163         },
28164         {
28165             name : 'alt',
28166             title: "Alt",
28167             width: 120
28168         },
28169         {
28170             name : 'src',
28171             title: "Src",
28172             width: 220
28173         }
28174         
28175     ],
28176     
28177     'FIGURE' : [
28178         {
28179             name : 'align',
28180             title: "Align",
28181             opts : [ [""],[ "left"],[ "right"],[ "center"],[ "top"]],
28182             width : 80  
28183         }
28184     ],
28185     'A' : [
28186         {
28187             name : 'name',
28188             title: "Name",
28189             width: 50
28190         },
28191         {
28192             name : 'target',
28193             title: "Target",
28194             width: 120
28195         },
28196         {
28197             name : 'href',
28198             title: "Href",
28199             width: 220
28200         } // border?
28201         
28202     ],
28203     
28204     'INPUT' : [
28205         {
28206             name : 'name',
28207             title: "name",
28208             width: 120
28209         },
28210         {
28211             name : 'value',
28212             title: "Value",
28213             width: 120
28214         },
28215         {
28216             name : 'width',
28217             title: "Width",
28218             width: 40
28219         }
28220     ],
28221     'LABEL' : [
28222          {
28223             name : 'for',
28224             title: "For",
28225             width: 120
28226         }
28227     ],
28228     'TEXTAREA' : [
28229         {
28230             name : 'name',
28231             title: "name",
28232             width: 120
28233         },
28234         {
28235             name : 'rows',
28236             title: "Rows",
28237             width: 20
28238         },
28239         {
28240             name : 'cols',
28241             title: "Cols",
28242             width: 20
28243         }
28244     ],
28245     'SELECT' : [
28246         {
28247             name : 'name',
28248             title: "name",
28249             width: 120
28250         },
28251         {
28252             name : 'selectoptions',
28253             title: "Options",
28254             width: 200
28255         }
28256     ],
28257     
28258     // should we really allow this??
28259     // should this just be 
28260     'BODY' : [
28261         
28262         {
28263             name : 'title',
28264             title: "Title",
28265             width: 200,
28266             disabled : true
28267         }
28268     ],
28269  
28270     '*' : [
28271         // empty.
28272     ]
28273
28274 };
28275
28276 // this should be configurable.. - you can either set it up using stores, or modify options somehwere..
28277 Roo.form.HtmlEditor.ToolbarContext.stores = false;
28278
28279 Roo.form.HtmlEditor.ToolbarContext.options = {
28280         'font-family'  : [ 
28281                 [ 'Helvetica,Arial,sans-serif', 'Helvetica'],
28282                 [ 'Courier New', 'Courier New'],
28283                 [ 'Tahoma', 'Tahoma'],
28284                 [ 'Times New Roman,serif', 'Times'],
28285                 [ 'Verdana','Verdana' ]
28286         ]
28287 };
28288
28289 // fixme - these need to be configurable..
28290  
28291
28292 //Roo.form.HtmlEditor.ToolbarContext.types
28293
28294
28295 Roo.apply(Roo.form.HtmlEditor.ToolbarContext.prototype,  {
28296     
28297     tb: false,
28298     
28299     rendered: false,
28300     
28301     editor : false,
28302     editorcore : false,
28303     /**
28304      * @cfg {Object} disable  List of toolbar elements to disable
28305          
28306      */
28307     disable : false,
28308     /**
28309      * @cfg {Object} styles List of styles 
28310      *    eg. { '*' : [ 'headline' ] , 'TD' : [ 'underline', 'double-underline' ] } 
28311      *
28312      * These must be defined in the page, so they get rendered correctly..
28313      * .headline { }
28314      * TD.underline { }
28315      * 
28316      */
28317     styles : false,
28318     
28319     options: false,
28320     
28321     toolbars : false,
28322     
28323     init : function(editor)
28324     {
28325         this.editor = editor;
28326         this.editorcore = editor.editorcore ? editor.editorcore : editor;
28327         var editorcore = this.editorcore;
28328         
28329         var fid = editorcore.frameId;
28330         var etb = this;
28331         function btn(id, toggle, handler){
28332             var xid = fid + '-'+ id ;
28333             return {
28334                 id : xid,
28335                 cmd : id,
28336                 cls : 'x-btn-icon x-edit-'+id,
28337                 enableToggle:toggle !== false,
28338                 scope: editorcore, // was editor...
28339                 handler:handler||editorcore.relayBtnCmd,
28340                 clickEvent:'mousedown',
28341                 tooltip: etb.buttonTips[id] || undefined, ///tips ???
28342                 tabIndex:-1
28343             };
28344         }
28345         // create a new element.
28346         var wdiv = editor.wrap.createChild({
28347                 tag: 'div'
28348             }, editor.wrap.dom.firstChild.nextSibling, true);
28349         
28350         // can we do this more than once??
28351         
28352          // stop form submits
28353       
28354  
28355         // disable everything...
28356         var ty= Roo.form.HtmlEditor.ToolbarContext.types;
28357         this.toolbars = {};
28358         // block toolbars are built in updateToolbar when needed.
28359         for (var i in  ty) {
28360             
28361             this.toolbars[i] = this.buildToolbar(ty[i],i);
28362         }
28363         this.tb = this.toolbars.BODY;
28364         this.tb.el.show();
28365         this.buildFooter();
28366         this.footer.show();
28367         editor.on('hide', function( ) { this.footer.hide() }, this);
28368         editor.on('show', function( ) { this.footer.show() }, this);
28369         
28370          
28371         this.rendered = true;
28372         
28373         // the all the btns;
28374         editor.on('editorevent', this.updateToolbar, this);
28375         // other toolbars need to implement this..
28376         //editor.on('editmodechange', this.updateToolbar, this);
28377     },
28378     
28379     
28380     
28381     /**
28382      * Protected method that will not generally be called directly. It triggers
28383      * a toolbar update by reading the markup state of the current selection in the editor.
28384      *
28385      * Note you can force an update by calling on('editorevent', scope, false)
28386      */
28387     updateToolbar: function(editor ,ev, sel)
28388     {
28389         
28390         if (ev) {
28391             ev.stopEvent(); // se if we can stop this looping with mutiple events.
28392         }
28393         
28394         //Roo.log(ev);
28395         // capture mouse up - this is handy for selecting images..
28396         // perhaps should go somewhere else...
28397         if(!this.editorcore.activated){
28398              this.editor.onFirstFocus();
28399             return;
28400         }
28401         //Roo.log(ev ? ev.target : 'NOTARGET');
28402         
28403         
28404         // http://developer.yahoo.com/yui/docs/simple-editor.js.html
28405         // selectNode - might want to handle IE?
28406         
28407         
28408         
28409         if (ev &&
28410             (ev.type == 'mouseup' || ev.type == 'click' ) &&
28411             ev.target && ev.target.tagName != 'BODY' ) { // && ev.target.tagName == 'IMG') {
28412             // they have click on an image...
28413             // let's see if we can change the selection...
28414             sel = ev.target;
28415             
28416             // this triggers looping?
28417             //this.editorcore.selectNode(sel);
28418              
28419         }
28420         
28421         // this forces an id..
28422         Array.from(this.editorcore.doc.body.querySelectorAll('.roo-ed-selection')).forEach(function(e) {
28423              e.classList.remove('roo-ed-selection');
28424         });
28425         //Roo.select('.roo-ed-selection', false, this.editorcore.doc).removeClass('roo-ed-selection');
28426         //Roo.get(node).addClass('roo-ed-selection');
28427       
28428         //var updateFooter = sel ? false : true; 
28429         
28430         
28431         var ans = this.editorcore.getAllAncestors();
28432         
28433         // pick
28434         var ty = Roo.form.HtmlEditor.ToolbarContext.types;
28435         
28436         if (!sel) { 
28437             sel = ans.length ? (ans[0] ?  ans[0]  : ans[1]) : this.editorcore.doc.body;
28438             sel = sel ? sel : this.editorcore.doc.body;
28439             sel = sel.tagName.length ? sel : this.editorcore.doc.body;
28440             
28441         }
28442         
28443         var tn = sel.tagName.toUpperCase();
28444         var lastSel = this.tb.selectedNode;
28445         this.tb.selectedNode = sel;
28446         var left_label = tn;
28447         
28448         // ok see if we are editing a block?
28449         
28450         var db = false;
28451         // you are not actually selecting the block.
28452         if (sel && sel.hasAttribute('data-block')) {
28453             db = sel;
28454         } else if (sel && sel.closest('[data-block]')) {
28455             
28456             db = sel.closest('[data-block]');
28457             //var cepar = sel.closest('[contenteditable=true]');
28458             //if (db && cepar && cepar.tagName != 'BODY') {
28459             //   db = false; // we are inside an editable block.. = not sure how we are going to handle nested blocks!?
28460             //}   
28461         }
28462         
28463         
28464         var block = false;
28465         //if (db && !sel.hasAttribute('contenteditable') && sel.getAttribute('contenteditable') != 'true' ) {
28466         if (db && this.editorcore.enableBlocks) {
28467             block = Roo.htmleditor.Block.factory(db);
28468             
28469             
28470             if (block) {
28471                  db.className = (
28472                         db.classList.length > 0  ? db.className + ' ' : ''
28473                     )  + 'roo-ed-selection';
28474                  
28475                  // since we removed it earlier... its not there..
28476                 tn = 'BLOCK.' + db.getAttribute('data-block');
28477                 
28478                 //this.editorcore.selectNode(db);
28479                 if (typeof(this.toolbars[tn]) == 'undefined') {
28480                    this.toolbars[tn] = this.buildToolbar( false  ,tn ,block.friendly_name, block);
28481                 }
28482                 this.toolbars[tn].selectedNode = db;
28483                 left_label = block.friendly_name;
28484                 ans = this.editorcore.getAllAncestors();
28485             }
28486             
28487                 
28488             
28489         }
28490         
28491         
28492         if (this.tb.name == tn && lastSel == this.tb.selectedNode && ev !== false) {
28493             return; // no change?
28494         }
28495         
28496         
28497           
28498         this.tb.el.hide();
28499         ///console.log("show: " + tn);
28500         this.tb =  typeof(this.toolbars[tn]) != 'undefined' ? this.toolbars[tn] : this.toolbars['*'];
28501         
28502         this.tb.el.show();
28503         // update name
28504         this.tb.items.first().el.innerHTML = left_label + ':&nbsp;';
28505         
28506         
28507         // update attributes
28508         if (block && this.tb.fields) {
28509              
28510             this.tb.fields.each(function(e) {
28511                 e.setValue(block[e.name]);
28512             });
28513             
28514             
28515         } else  if (this.tb.fields && this.tb.selectedNode) {
28516             this.tb.fields.each( function(e) {
28517                 if (e.stylename) {
28518                     e.setValue(this.tb.selectedNode.style[e.stylename]);
28519                     return;
28520                 } 
28521                 e.setValue(this.tb.selectedNode.getAttribute(e.attrname));
28522             }, this);
28523             this.updateToolbarStyles(this.tb.selectedNode);  
28524         }
28525         
28526         
28527        
28528         Roo.menu.MenuMgr.hideAll();
28529
28530         
28531         
28532     
28533         // update the footer
28534         //
28535         this.updateFooter(ans);
28536              
28537     },
28538     
28539     updateToolbarStyles : function(sel)
28540     {
28541         var hasStyles = false;
28542         for(var i in this.styles) {
28543             hasStyles = true;
28544             break;
28545         }
28546         
28547         // update styles
28548         if (hasStyles && this.tb.hasStyles) { 
28549             var st = this.tb.fields.item(0);
28550             
28551             st.store.removeAll();
28552             var cn = sel.className.split(/\s+/);
28553             
28554             var avs = [];
28555             if (this.styles['*']) {
28556                 
28557                 Roo.each(this.styles['*'], function(v) {
28558                     avs.push( [ v , cn.indexOf(v) > -1 ? 1 : 0 ] );         
28559                 });
28560             }
28561             if (this.styles[tn]) { 
28562                 Roo.each(this.styles[tn], function(v) {
28563                     avs.push( [ v , cn.indexOf(v) > -1 ? 1 : 0 ] );         
28564                 });
28565             }
28566             
28567             st.store.loadData(avs);
28568             st.collapse();
28569             st.setValue(cn);
28570         }
28571     },
28572     
28573      
28574     updateFooter : function(ans)
28575     {
28576         var html = '';
28577         if (ans === false) {
28578             this.footDisp.dom.innerHTML = '';
28579             return;
28580         }
28581         
28582         this.footerEls = ans.reverse();
28583         Roo.each(this.footerEls, function(a,i) {
28584             if (!a) { return; }
28585             html += html.length ? ' &gt; '  :  '';
28586             
28587             html += '<span class="x-ed-loc-' + i + '">' + a.tagName + '</span>';
28588             
28589         });
28590        
28591         // 
28592         var sz = this.footDisp.up('td').getSize();
28593         this.footDisp.dom.style.width = (sz.width -10) + 'px';
28594         this.footDisp.dom.style.marginLeft = '5px';
28595         
28596         this.footDisp.dom.style.overflow = 'hidden';
28597         
28598         this.footDisp.dom.innerHTML = html;
28599             
28600         
28601     },
28602    
28603        
28604     // private
28605     onDestroy : function(){
28606         if(this.rendered){
28607             
28608             this.tb.items.each(function(item){
28609                 if(item.menu){
28610                     item.menu.removeAll();
28611                     if(item.menu.el){
28612                         item.menu.el.destroy();
28613                     }
28614                 }
28615                 item.destroy();
28616             });
28617              
28618         }
28619     },
28620     onFirstFocus: function() {
28621         // need to do this for all the toolbars..
28622         this.tb.items.each(function(item){
28623            item.enable();
28624         });
28625     },
28626     buildToolbar: function(tlist, nm, friendly_name, block)
28627     {
28628         var editor = this.editor;
28629         var editorcore = this.editorcore;
28630          // create a new element.
28631         var wdiv = editor.wrap.createChild({
28632                 tag: 'div'
28633             }, editor.wrap.dom.firstChild.nextSibling, true);
28634         
28635        
28636         var tb = new Roo.Toolbar(wdiv);
28637         ///this.tb = tb; // << this sets the active toolbar..
28638         if (tlist === false && block) {
28639             tlist = block.contextMenu(this);
28640         }
28641         
28642         tb.hasStyles = false;
28643         tb.name = nm;
28644         
28645         tb.add((typeof(friendly_name) == 'undefined' ? nm : friendly_name) + ":&nbsp;");
28646         
28647         var styles = Array.from(this.styles);
28648         
28649         
28650         // styles...
28651         if (styles && styles.length) {
28652             tb.hasStyles = true;
28653             // this needs a multi-select checkbox...
28654             tb.addField( new Roo.form.ComboBox({
28655                 store: new Roo.data.SimpleStore({
28656                     id : 'val',
28657                     fields: ['val', 'selected'],
28658                     data : [] 
28659                 }),
28660                 name : '-roo-edit-className',
28661                 attrname : 'className',
28662                 displayField: 'val',
28663                 typeAhead: false,
28664                 mode: 'local',
28665                 editable : false,
28666                 triggerAction: 'all',
28667                 emptyText:'Select Style',
28668                 selectOnFocus:true,
28669                 width: 130,
28670                 listeners : {
28671                     'select': function(c, r, i) {
28672                         // initial support only for on class per el..
28673                         tb.selectedNode.className =  r ? r.get('val') : '';
28674                         editorcore.syncValue();
28675                     }
28676                 }
28677     
28678             }));
28679         }
28680         
28681         var tbc = Roo.form.HtmlEditor.ToolbarContext;
28682         
28683         
28684         for (var i = 0; i < tlist.length; i++) {
28685             
28686             // newer versions will use xtype cfg to create menus.
28687             if (typeof(tlist[i].xtype) != 'undefined') {
28688                 
28689                 tb[typeof(tlist[i].name)== 'undefined' ? 'add' : 'addField'](Roo.factory(tlist[i]));
28690                 
28691                 
28692                 continue;
28693             }
28694             
28695             var item = tlist[i];
28696             tb.add(item.title + ":&nbsp;");
28697             
28698             
28699             //optname == used so you can configure the options available..
28700             var opts = item.opts ? item.opts : false;
28701             if (item.optname) { // use the b
28702                 opts = Roo.form.HtmlEditor.ToolbarContext.options[item.optname];
28703            
28704             }
28705             
28706             if (opts) {
28707                 // opts == pulldown..
28708                 tb.addField( new Roo.form.ComboBox({
28709                     store:   typeof(tbc.stores[i]) != 'undefined' ?  Roo.factory(tbc.stores[i],Roo.data) : new Roo.data.SimpleStore({
28710                         id : 'val',
28711                         fields: ['val', 'display'],
28712                         data : opts  
28713                     }),
28714                     name : '-roo-edit-' + tlist[i].name,
28715                     
28716                     attrname : tlist[i].name,
28717                     stylename : item.style ? item.style : false,
28718                     
28719                     displayField: item.displayField ? item.displayField : 'val',
28720                     valueField :  'val',
28721                     typeAhead: false,
28722                     mode: typeof(tbc.stores[tlist[i].name]) != 'undefined'  ? 'remote' : 'local',
28723                     editable : false,
28724                     triggerAction: 'all',
28725                     emptyText:'Select',
28726                     selectOnFocus:true,
28727                     width: item.width ? item.width  : 130,
28728                     listeners : {
28729                         'select': function(c, r, i) {
28730                              
28731                             
28732                             if (c.stylename) {
28733                                 tb.selectedNode.style[c.stylename] =  r.get('val');
28734                                 editorcore.syncValue();
28735                                 return;
28736                             }
28737                             if (r === false) {
28738                                 tb.selectedNode.removeAttribute(c.attrname);
28739                                 editorcore.syncValue();
28740                                 return;
28741                             }
28742                             tb.selectedNode.setAttribute(c.attrname, r.get('val'));
28743                             editorcore.syncValue();
28744                         }
28745                     }
28746
28747                 }));
28748                 continue;
28749                     
28750                  
28751                 /*
28752                 tb.addField( new Roo.form.TextField({
28753                     name: i,
28754                     width: 100,
28755                     //allowBlank:false,
28756                     value: ''
28757                 }));
28758                 continue;
28759                 */
28760             }
28761             tb.addField( new Roo.form.TextField({
28762                 name: '-roo-edit-' + tlist[i].name,
28763                 attrname : tlist[i].name,
28764                 
28765                 width: item.width,
28766                 //allowBlank:true,
28767                 value: '',
28768                 listeners: {
28769                     'change' : function(f, nv, ov) {
28770                         
28771                          
28772                         tb.selectedNode.setAttribute(f.attrname, nv);
28773                         editorcore.syncValue();
28774                     }
28775                 }
28776             }));
28777              
28778         }
28779         
28780         var _this = this;
28781         var show_delete = !block || block.deleteTitle !== false;
28782         if(nm == 'BODY'){
28783             show_delete = false;
28784             tb.addSeparator();
28785         
28786             tb.addButton( {
28787                 text: 'Stylesheets',
28788
28789                 listeners : {
28790                     click : function ()
28791                     {
28792                         _this.editor.fireEvent('stylesheetsclick', _this.editor);
28793                     }
28794                 }
28795             });
28796         }
28797         
28798         tb.addFill();
28799         if (show_delete) {
28800             tb.addButton({
28801                 text: block && block.deleteTitle ? block.deleteTitle  : 'Remove Block or Formating', // remove the tag, and puts the children outside...
28802         
28803                 listeners : {
28804                     click : function ()
28805                     {
28806                         var sn = tb.selectedNode;
28807                         if (block) {
28808                             sn = Roo.htmleditor.Block.factory(tb.selectedNode).removeNode();
28809                             
28810                         }
28811                         if (!sn) {
28812                             return;
28813                         }
28814                         var stn =  sn.childNodes[0] || sn.nextSibling || sn.previousSibling || sn.parentNode;
28815                         if (sn.hasAttribute('data-block')) {
28816                             stn =  sn.nextSibling || sn.previousSibling || sn.parentNode;
28817                             sn.parentNode.removeChild(sn);
28818                             
28819                         } else if (sn && sn.tagName != 'BODY') {
28820                             // remove and keep parents.
28821                             a = new Roo.htmleditor.FilterKeepChildren({tag : false});
28822                             a.replaceTag(sn);
28823                         }
28824                         
28825                         
28826                         var range = editorcore.createRange();
28827             
28828                         range.setStart(stn,0);
28829                         range.setEnd(stn,0); 
28830                         var selection = editorcore.getSelection();
28831                         selection.removeAllRanges();
28832                         selection.addRange(range);
28833                         
28834                         
28835                         //_this.updateToolbar(null, null, pn);
28836                         _this.updateToolbar(null, null, null);
28837                         _this.updateFooter(false);
28838                         
28839                     }
28840                 }
28841                 
28842                         
28843                     
28844                 
28845             });
28846         }    
28847         
28848         tb.el.on('click', function(e){
28849             e.preventDefault(); // what does this do?
28850         });
28851         tb.el.setVisibilityMode( Roo.Element.DISPLAY);
28852         tb.el.hide();
28853         
28854         // dont need to disable them... as they will get hidden
28855         return tb;
28856          
28857         
28858     },
28859     buildFooter : function()
28860     {
28861         
28862         var fel = this.editor.wrap.createChild();
28863         this.footer = new Roo.Toolbar(fel);
28864         // toolbar has scrolly on left / right?
28865         var footDisp= new Roo.Toolbar.Fill();
28866         var _t = this;
28867         this.footer.add(
28868             {
28869                 text : '&lt;',
28870                 xtype: 'Button',
28871                 handler : function() {
28872                     _t.footDisp.scrollTo('left',0,true)
28873                 }
28874             }
28875         );
28876         this.footer.add( footDisp );
28877         this.footer.add( 
28878             {
28879                 text : '&gt;',
28880                 xtype: 'Button',
28881                 handler : function() {
28882                     // no animation..
28883                     _t.footDisp.select('span').last().scrollIntoView(_t.footDisp,true);
28884                 }
28885             }
28886         );
28887         var fel = Roo.get(footDisp.el);
28888         fel.addClass('x-editor-context');
28889         this.footDispWrap = fel; 
28890         this.footDispWrap.overflow  = 'hidden';
28891         
28892         this.footDisp = fel.createChild();
28893         this.footDispWrap.on('click', this.onContextClick, this)
28894         
28895         
28896     },
28897     // when the footer contect changes
28898     onContextClick : function (ev,dom)
28899     {
28900         ev.preventDefault();
28901         var  cn = dom.className;
28902         //Roo.log(cn);
28903         if (!cn.match(/x-ed-loc-/)) {
28904             return;
28905         }
28906         var n = cn.split('-').pop();
28907         var ans = this.footerEls;
28908         var sel = ans[n];
28909         
28910         this.editorcore.selectNode(sel);
28911         
28912         
28913         this.updateToolbar(null, null, sel);
28914         
28915         
28916     }
28917     
28918     
28919     
28920     
28921     
28922 });
28923
28924
28925
28926
28927
28928 /*
28929  * Based on:
28930  * Ext JS Library 1.1.1
28931  * Copyright(c) 2006-2007, Ext JS, LLC.
28932  *
28933  * Originally Released Under LGPL - original licence link has changed is not relivant.
28934  *
28935  * Fork - LGPL
28936  * <script type="text/javascript">
28937  */
28938  
28939 /**
28940  * @class Roo.form.BasicForm
28941  * @extends Roo.util.Observable
28942  * Supplies the functionality to do "actions" on forms and initialize Roo.form.Field types on existing markup.
28943  * @constructor
28944  * @param {String/HTMLElement/Roo.Element} el The form element or its id
28945  * @param {Object} config Configuration options
28946  */
28947 Roo.form.BasicForm = function(el, config){
28948     this.allItems = [];
28949     this.childForms = [];
28950     Roo.apply(this, config);
28951     /*
28952      * The Roo.form.Field items in this form.
28953      * @type MixedCollection
28954      */
28955      
28956      
28957     this.items = new Roo.util.MixedCollection(false, function(o){
28958         return o.id || (o.id = Roo.id());
28959     });
28960     this.addEvents({
28961         /**
28962          * @event beforeaction
28963          * Fires before any action is performed. Return false to cancel the action.
28964          * @param {Form} this
28965          * @param {Action} action The action to be performed
28966          */
28967         beforeaction: true,
28968         /**
28969          * @event actionfailed
28970          * Fires when an action fails.
28971          * @param {Form} this
28972          * @param {Action} action The action that failed
28973          */
28974         actionfailed : true,
28975         /**
28976          * @event actioncomplete
28977          * Fires when an action is completed.
28978          * @param {Form} this
28979          * @param {Action} action The action that completed
28980          */
28981         actioncomplete : true
28982     });
28983     if(el){
28984         this.initEl(el);
28985     }
28986     Roo.form.BasicForm.superclass.constructor.call(this);
28987     
28988     Roo.form.BasicForm.popover.apply();
28989 };
28990
28991 Roo.extend(Roo.form.BasicForm, Roo.util.Observable, {
28992     /**
28993      * @cfg {String} method
28994      * The request method to use (GET or POST) for form actions if one isn't supplied in the action options.
28995      */
28996     /**
28997      * @cfg {DataReader} reader
28998      * An Roo.data.DataReader (e.g. {@link Roo.data.XmlReader}) to be used to read data when executing "load" actions.
28999      * This is optional as there is built-in support for processing JSON.
29000      */
29001     /**
29002      * @cfg {DataReader} errorReader
29003      * An Roo.data.DataReader (e.g. {@link Roo.data.XmlReader}) to be used to read data when reading validation errors on "submit" actions.
29004      * This is completely optional as there is built-in support for processing JSON.
29005      */
29006     /**
29007      * @cfg {String} url
29008      * The URL to use for form actions if one isn't supplied in the action options.
29009      */
29010     /**
29011      * @cfg {Boolean} fileUpload
29012      * Set to true if this form is a file upload.
29013      */
29014      
29015     /**
29016      * @cfg {Object} baseParams
29017      * Parameters to pass with all requests. e.g. baseParams: {id: '123', foo: 'bar'}.
29018      */
29019      /**
29020      
29021     /**
29022      * @cfg {Number} timeout Timeout for form actions in seconds (default is 30 seconds).
29023      */
29024     timeout: 30,
29025
29026     // private
29027     activeAction : null,
29028
29029     /**
29030      * @cfg {Boolean} trackResetOnLoad If set to true, form.reset() resets to the last loaded
29031      * or setValues() data instead of when the form was first created.
29032      */
29033     trackResetOnLoad : false,
29034     
29035     
29036     /**
29037      * childForms - used for multi-tab forms
29038      * @type {Array}
29039      */
29040     childForms : false,
29041     
29042     /**
29043      * allItems - full list of fields.
29044      * @type {Array}
29045      */
29046     allItems : false,
29047     
29048     /**
29049      * By default wait messages are displayed with Roo.MessageBox.wait. You can target a specific
29050      * element by passing it or its id or mask the form itself by passing in true.
29051      * @type Mixed
29052      */
29053     waitMsgTarget : false,
29054     
29055     /**
29056      * @type Boolean
29057      */
29058     disableMask : false,
29059     
29060     /**
29061      * @cfg {Boolean} errorMask (true|false) default false
29062      */
29063     errorMask : false,
29064     
29065     /**
29066      * @cfg {Number} maskOffset Default 100
29067      */
29068     maskOffset : 100,
29069
29070     // private
29071     initEl : function(el){
29072         this.el = Roo.get(el);
29073         this.id = this.el.id || Roo.id();
29074         this.el.on('submit', this.onSubmit, this);
29075         this.el.addClass('x-form');
29076     },
29077
29078     // private
29079     onSubmit : function(e){
29080         e.stopEvent();
29081     },
29082
29083     /**
29084      * Returns true if client-side validation on the form is successful.
29085      * @return Boolean
29086      */
29087     isValid : function(){
29088         var valid = true;
29089         var target = false;
29090         this.items.each(function(f){
29091             if(f.validate()){
29092                 return;
29093             }
29094             
29095             valid = false;
29096                 
29097             if(!target && f.el.isVisible(true)){
29098                 target = f;
29099             }
29100         });
29101         
29102         if(this.errorMask && !valid){
29103             Roo.form.BasicForm.popover.mask(this, target);
29104         }
29105         
29106         return valid;
29107     },
29108     /**
29109      * Returns array of invalid form fields.
29110      * @return Array
29111      */
29112     
29113     invalidFields : function()
29114     {
29115         var ret = [];
29116         this.items.each(function(f){
29117             if(f.validate()){
29118                 return;
29119             }
29120             ret.push(f);
29121             
29122         });
29123         
29124         return ret;
29125     },
29126     
29127     
29128     /**
29129      * DEPRICATED Returns true if any fields in this form have changed since their original load. 
29130      * @return Boolean
29131      */
29132     isDirty : function(){
29133         var dirty = false;
29134         this.items.each(function(f){
29135            if(f.isDirty()){
29136                dirty = true;
29137                return false;
29138            }
29139         });
29140         return dirty;
29141     },
29142     
29143     /**
29144      * Returns true if any fields in this form have changed since their original load. (New version)
29145      * @return Boolean
29146      */
29147     
29148     hasChanged : function()
29149     {
29150         var dirty = false;
29151         this.items.each(function(f){
29152            if(f.hasChanged()){
29153                dirty = true;
29154                return false;
29155            }
29156         });
29157         return dirty;
29158         
29159     },
29160     /**
29161      * Resets all hasChanged to 'false' -
29162      * The old 'isDirty' used 'original value..' however this breaks reset() and a few other things.
29163      * So hasChanged storage is only to be used for this purpose
29164      * @return Boolean
29165      */
29166     resetHasChanged : function()
29167     {
29168         this.items.each(function(f){
29169            f.resetHasChanged();
29170         });
29171         
29172     },
29173     
29174     
29175     /**
29176      * Performs a predefined action (submit or load) or custom actions you define on this form.
29177      * @param {String} actionName The name of the action type
29178      * @param {Object} options (optional) The options to pass to the action.  All of the config options listed
29179      * below are supported by both the submit and load actions unless otherwise noted (custom actions could also
29180      * accept other config options):
29181      * <pre>
29182 Property          Type             Description
29183 ----------------  ---------------  ----------------------------------------------------------------------------------
29184 url               String           The url for the action (defaults to the form's url)
29185 method            String           The form method to use (defaults to the form's method, or POST if not defined)
29186 params            String/Object    The params to pass (defaults to the form's baseParams, or none if not defined)
29187 clientValidation  Boolean          Applies to submit only.  Pass true to call form.isValid() prior to posting to
29188                                    validate the form on the client (defaults to false)
29189      * </pre>
29190      * @return {BasicForm} this
29191      */
29192     doAction : function(action, options){
29193         if(typeof action == 'string'){
29194             action = new Roo.form.Action.ACTION_TYPES[action](this, options);
29195         }
29196         if(this.fireEvent('beforeaction', this, action) !== false){
29197             this.beforeAction(action);
29198             action.run.defer(100, action);
29199         }
29200         return this;
29201     },
29202
29203     /**
29204      * Shortcut to do a submit action.
29205      * @param {Object} options The options to pass to the action (see {@link #doAction} for details)
29206      * @return {BasicForm} this
29207      */
29208     submit : function(options){
29209         this.doAction('submit', options);
29210         return this;
29211     },
29212
29213     /**
29214      * Shortcut to do a load action.
29215      * @param {Object} options The options to pass to the action (see {@link #doAction} for details)
29216      * @return {BasicForm} this
29217      */
29218     load : function(options){
29219         this.doAction('load', options);
29220         return this;
29221     },
29222
29223     /**
29224      * Persists the values in this form into the passed Roo.data.Record object in a beginEdit/endEdit block.
29225      * @param {Record} record The record to edit
29226      * @return {BasicForm} this
29227      */
29228     updateRecord : function(record){
29229         record.beginEdit();
29230         var fs = record.fields;
29231         fs.each(function(f){
29232             var field = this.findField(f.name);
29233             if(field){
29234                 record.set(f.name, field.getValue());
29235             }
29236         }, this);
29237         record.endEdit();
29238         return this;
29239     },
29240
29241     /**
29242      * Loads an Roo.data.Record into this form.
29243      * @param {Record} record The record to load
29244      * @return {BasicForm} this
29245      */
29246     loadRecord : function(record){
29247         this.setValues(record.data);
29248         return this;
29249     },
29250
29251     // private
29252     beforeAction : function(action){
29253         var o = action.options;
29254         
29255         if(!this.disableMask) {
29256             if(this.waitMsgTarget === true){
29257                 this.el.mask(o.waitMsg || "Sending", 'x-mask-loading');
29258             }else if(this.waitMsgTarget){
29259                 this.waitMsgTarget = Roo.get(this.waitMsgTarget);
29260                 this.waitMsgTarget.mask(o.waitMsg || "Sending", 'x-mask-loading');
29261             }else {
29262                 Roo.MessageBox.wait(o.waitMsg || "Sending", o.waitTitle || this.waitTitle || 'Please Wait...');
29263             }
29264         }
29265         
29266          
29267     },
29268
29269     // private
29270     afterAction : function(action, success){
29271         this.activeAction = null;
29272         var o = action.options;
29273         
29274         if(!this.disableMask) {
29275             if(this.waitMsgTarget === true){
29276                 this.el.unmask();
29277             }else if(this.waitMsgTarget){
29278                 this.waitMsgTarget.unmask();
29279             }else{
29280                 Roo.MessageBox.updateProgress(1);
29281                 Roo.MessageBox.hide();
29282             }
29283         }
29284         
29285         if(success){
29286             if(o.reset){
29287                 this.reset();
29288             }
29289             Roo.callback(o.success, o.scope, [this, action]);
29290             this.fireEvent('actioncomplete', this, action);
29291             
29292         }else{
29293             
29294             // failure condition..
29295             // we have a scenario where updates need confirming.
29296             // eg. if a locking scenario exists..
29297             // we look for { errors : { needs_confirm : true }} in the response.
29298             if (
29299                 (typeof(action.result) != 'undefined')  &&
29300                 (typeof(action.result.errors) != 'undefined')  &&
29301                 (typeof(action.result.errors.needs_confirm) != 'undefined')
29302            ){
29303                 var _t = this;
29304                 Roo.MessageBox.confirm(
29305                     "Change requires confirmation",
29306                     action.result.errorMsg,
29307                     function(r) {
29308                         if (r != 'yes') {
29309                             return;
29310                         }
29311                         _t.doAction('submit', { params :  { _submit_confirmed : 1 } }  );
29312                     }
29313                     
29314                 );
29315                 
29316                 
29317                 
29318                 return;
29319             }
29320             
29321             Roo.callback(o.failure, o.scope, [this, action]);
29322             // show an error message if no failed handler is set..
29323             if (!this.hasListener('actionfailed')) {
29324                 Roo.MessageBox.alert("Error",
29325                     (typeof(action.result) != 'undefined' && typeof(action.result.errorMsg) != 'undefined') ?
29326                         action.result.errorMsg :
29327                         "Saving Failed, please check your entries or try again"
29328                 );
29329             }
29330             
29331             this.fireEvent('actionfailed', this, action);
29332         }
29333         
29334     },
29335
29336     /**
29337      * Find a Roo.form.Field in this form by id, dataIndex, name or hiddenName
29338      * @param {String} id The value to search for
29339      * @return Field
29340      */
29341     findField : function(id){
29342         var field = this.items.get(id);
29343         if(!field){
29344             this.items.each(function(f){
29345                 if(f.isFormField && (f.dataIndex == id || f.id == id || f.getName() == id)){
29346                     field = f;
29347                     return false;
29348                 }
29349             });
29350         }
29351         return field || null;
29352     },
29353
29354     /**
29355      * Add a secondary form to this one, 
29356      * Used to provide tabbed forms. One form is primary, with hidden values 
29357      * which mirror the elements from the other forms.
29358      * 
29359      * @param {Roo.form.Form} form to add.
29360      * 
29361      */
29362     addForm : function(form)
29363     {
29364        
29365         if (this.childForms.indexOf(form) > -1) {
29366             // already added..
29367             return;
29368         }
29369         this.childForms.push(form);
29370         var n = '';
29371         Roo.each(form.allItems, function (fe) {
29372             
29373             n = typeof(fe.getName) == 'undefined' ? fe.name : fe.getName();
29374             if (this.findField(n)) { // already added..
29375                 return;
29376             }
29377             var add = new Roo.form.Hidden({
29378                 name : n
29379             });
29380             add.render(this.el);
29381             
29382             this.add( add );
29383         }, this);
29384         
29385     },
29386     /**
29387      * Mark fields in this form invalid in bulk.
29388      * @param {Array/Object} errors Either an array in the form [{id:'fieldId', msg:'The message'},...] or an object hash of {id: msg, id2: msg2}
29389      * @return {BasicForm} this
29390      */
29391     markInvalid : function(errors){
29392         if(errors instanceof Array){
29393             for(var i = 0, len = errors.length; i < len; i++){
29394                 var fieldError = errors[i];
29395                 var f = this.findField(fieldError.id);
29396                 if(f){
29397                     f.markInvalid(fieldError.msg);
29398                 }
29399             }
29400         }else{
29401             var field, id;
29402             for(id in errors){
29403                 if(typeof errors[id] != 'function' && (field = this.findField(id))){
29404                     field.markInvalid(errors[id]);
29405                 }
29406             }
29407         }
29408         Roo.each(this.childForms || [], function (f) {
29409             f.markInvalid(errors);
29410         });
29411         
29412         return this;
29413     },
29414
29415     /**
29416      * Set values for fields in this form in bulk.
29417      * @param {Array/Object} values Either an array in the form [{id:'fieldId', value:'foo'},...] or an object hash of {id: value, id2: value2}
29418      * @return {BasicForm} this
29419      */
29420     setValues : function(values){
29421         if(values instanceof Array){ // array of objects
29422             for(var i = 0, len = values.length; i < len; i++){
29423                 var v = values[i];
29424                 var f = this.findField(v.id);
29425                 if(f){
29426                     f.setValue(v.value);
29427                     if(this.trackResetOnLoad){
29428                         f.originalValue = f.getValue();
29429                     }
29430                 }
29431             }
29432         }else{ // object hash
29433             var field, id;
29434             for(id in values){
29435                 if(typeof values[id] != 'function' && (field = this.findField(id))){
29436                     
29437                     if (field.setFromData && 
29438                         field.valueField && 
29439                         field.displayField &&
29440                         // combos' with local stores can 
29441                         // be queried via setValue()
29442                         // to set their value..
29443                         (field.store && !field.store.isLocal)
29444                         ) {
29445                         // it's a combo
29446                         var sd = { };
29447                         sd[field.valueField] = typeof(values[field.hiddenName]) == 'undefined' ? '' : values[field.hiddenName];
29448                         sd[field.displayField] = typeof(values[field.name]) == 'undefined' ? '' : values[field.name];
29449                         field.setFromData(sd);
29450                         
29451                     } else {
29452                         field.setValue(values[id]);
29453                     }
29454                     
29455                     
29456                     if(this.trackResetOnLoad){
29457                         field.originalValue = field.getValue();
29458                     }
29459                 }
29460             }
29461         }
29462         this.resetHasChanged();
29463         
29464         
29465         Roo.each(this.childForms || [], function (f) {
29466             f.setValues(values);
29467             f.resetHasChanged();
29468         });
29469                 
29470         return this;
29471     },
29472  
29473     /**
29474      * Returns the fields in this form as an object with key/value pairs. If multiple fields exist with the same name
29475      * they are returned as an array.
29476      * @param {Boolean} asString
29477      * @return {Object}
29478      */
29479     getValues : function(asString)
29480     {
29481         if (this.childForms) {
29482             // copy values from the child forms
29483             Roo.each(this.childForms, function (f) {
29484                 this.setValues(f.getFieldValues()); // get the full set of data, as we might be copying comboboxes from external into this one.
29485             }, this);
29486         }
29487         
29488         // use formdata
29489         if (typeof(FormData) != 'undefined' && asString !== true) {
29490             // this relies on a 'recent' version of chrome apparently...
29491             try {
29492                 var fd = (new FormData(this.el.dom)).entries();
29493                 var ret = {};
29494                 var ent = fd.next();
29495                 while (!ent.done) {
29496                     ret[ent.value[0]] = ent.value[1]; // not sure how this will handle duplicates..
29497                     ent = fd.next();
29498                 };
29499                 return ret;
29500             } catch(e) {
29501                 
29502             }
29503             
29504         }
29505         
29506         
29507         var fs = Roo.lib.Ajax.serializeForm(this.el.dom);
29508         if(asString === true){
29509             return fs;
29510         }
29511         return Roo.urlDecode(fs);
29512     },
29513     
29514     /**
29515      * Returns the fields in this form as an object with key/value pairs. 
29516      * This differs from getValues as it calls getValue on each child item, rather than using dom data.
29517      * Normally this will not return readOnly data 
29518      * @param {Boolean} with_readonly return readonly field data.
29519      * @return {Object}
29520      */
29521     getFieldValues : function(with_readonly)
29522     {
29523         if (this.childForms) {
29524             // copy values from the child forms
29525             // should this call getFieldValues - probably not as we do not currently copy
29526             // hidden fields when we generate..
29527             Roo.each(this.childForms, function (f) {
29528                 this.setValues(f.getFieldValues());
29529             }, this);
29530         }
29531         
29532         var ret = {};
29533         this.items.each(function(f){
29534             
29535             if (f.readOnly && with_readonly !== true) {
29536                 return; // skip read only values. - this is in theory to stop 'old' values being copied over new ones
29537                         // if a subform contains a copy of them.
29538                         // if you have subforms with the same editable data, you will need to copy the data back
29539                         // and forth.
29540             }
29541             
29542             if (!f.getName()) {
29543                 return;
29544             }
29545             var v = f.getValue();
29546             if (f.inputType =='radio') {
29547                 if (typeof(ret[f.getName()]) == 'undefined') {
29548                     ret[f.getName()] = ''; // empty..
29549                 }
29550                 
29551                 if (!f.el.dom.checked) {
29552                     return;
29553                     
29554                 }
29555                 v = f.el.dom.value;
29556                 
29557             }
29558             
29559             // not sure if this supported any more..
29560             if ((typeof(v) == 'object') && f.getRawValue) {
29561                 v = f.getRawValue() ; // dates..
29562             }
29563             // combo boxes where name != hiddenName...
29564             if (f.name != f.getName()) {
29565                 ret[f.name] = f.getRawValue();
29566             }
29567             ret[f.getName()] = v;
29568         });
29569         
29570         return ret;
29571     },
29572
29573     /**
29574      * Clears all invalid messages in this form.
29575      * @return {BasicForm} this
29576      */
29577     clearInvalid : function(){
29578         this.items.each(function(f){
29579            f.clearInvalid();
29580         });
29581         
29582         Roo.each(this.childForms || [], function (f) {
29583             f.clearInvalid();
29584         });
29585         
29586         
29587         return this;
29588     },
29589
29590     /**
29591      * Resets this form.
29592      * @return {BasicForm} this
29593      */
29594     reset : function(){
29595         this.items.each(function(f){
29596             f.reset();
29597         });
29598         
29599         Roo.each(this.childForms || [], function (f) {
29600             f.reset();
29601         });
29602         this.resetHasChanged();
29603         
29604         return this;
29605     },
29606
29607     /**
29608      * Add Roo.form components to this form.
29609      * @param {Field} field1
29610      * @param {Field} field2 (optional)
29611      * @param {Field} etc (optional)
29612      * @return {BasicForm} this
29613      */
29614     add : function(){
29615         this.items.addAll(Array.prototype.slice.call(arguments, 0));
29616         return this;
29617     },
29618
29619
29620     /**
29621      * Removes a field from the items collection (does NOT remove its markup).
29622      * @param {Field} field
29623      * @return {BasicForm} this
29624      */
29625     remove : function(field){
29626         this.items.remove(field);
29627         return this;
29628     },
29629
29630     /**
29631      * Looks at the fields in this form, checks them for an id attribute,
29632      * and calls applyTo on the existing dom element with that id.
29633      * @return {BasicForm} this
29634      */
29635     render : function(){
29636         this.items.each(function(f){
29637             if(f.isFormField && !f.rendered && document.getElementById(f.id)){ // if the element exists
29638                 f.applyTo(f.id);
29639             }
29640         });
29641         return this;
29642     },
29643
29644     /**
29645      * Calls {@link Ext#apply} for all fields in this form with the passed object.
29646      * @param {Object} values
29647      * @return {BasicForm} this
29648      */
29649     applyToFields : function(o){
29650         this.items.each(function(f){
29651            Roo.apply(f, o);
29652         });
29653         return this;
29654     },
29655
29656     /**
29657      * Calls {@link Ext#applyIf} for all field in this form with the passed object.
29658      * @param {Object} values
29659      * @return {BasicForm} this
29660      */
29661     applyIfToFields : function(o){
29662         this.items.each(function(f){
29663            Roo.applyIf(f, o);
29664         });
29665         return this;
29666     }
29667 });
29668
29669 // back compat
29670 Roo.BasicForm = Roo.form.BasicForm;
29671
29672 Roo.apply(Roo.form.BasicForm, {
29673     
29674     popover : {
29675         
29676         padding : 5,
29677         
29678         isApplied : false,
29679         
29680         isMasked : false,
29681         
29682         form : false,
29683         
29684         target : false,
29685         
29686         intervalID : false,
29687         
29688         maskEl : false,
29689         
29690         apply : function()
29691         {
29692             if(this.isApplied){
29693                 return;
29694             }
29695             
29696             this.maskEl = {
29697                 top : Roo.DomHelper.append(Roo.get(document.body), { tag: "div", cls:"x-dlg-mask roo-form-top-mask" }, true),
29698                 left : Roo.DomHelper.append(Roo.get(document.body), { tag: "div", cls:"x-dlg-mask roo-form-left-mask" }, true),
29699                 bottom : Roo.DomHelper.append(Roo.get(document.body), { tag: "div", cls:"x-dlg-mask roo-form-bottom-mask" }, true),
29700                 right : Roo.DomHelper.append(Roo.get(document.body), { tag: "div", cls:"x-dlg-mask roo-form-right-mask" }, true)
29701             };
29702             
29703             this.maskEl.top.enableDisplayMode("block");
29704             this.maskEl.left.enableDisplayMode("block");
29705             this.maskEl.bottom.enableDisplayMode("block");
29706             this.maskEl.right.enableDisplayMode("block");
29707             
29708             Roo.get(document.body).on('click', function(){
29709                 this.unmask();
29710             }, this);
29711             
29712             Roo.get(document.body).on('touchstart', function(){
29713                 this.unmask();
29714             }, this);
29715             
29716             this.isApplied = true
29717         },
29718         
29719         mask : function(form, target)
29720         {
29721             this.form = form;
29722             
29723             this.target = target;
29724             
29725             if(!this.form.errorMask || !target.el){
29726                 return;
29727             }
29728             
29729             var scrollable = this.target.el.findScrollableParent() || this.target.el.findParent('div.x-layout-active-content', 100, true) || Roo.get(document.body);
29730             
29731             var ot = this.target.el.calcOffsetsTo(scrollable);
29732             
29733             var scrollTo = ot[1] - this.form.maskOffset;
29734             
29735             scrollTo = Math.min(scrollTo, scrollable.dom.scrollHeight);
29736             
29737             scrollable.scrollTo('top', scrollTo);
29738             
29739             var el = this.target.wrap || this.target.el;
29740             
29741             var box = el.getBox();
29742             
29743             this.maskEl.top.setStyle('position', 'absolute');
29744             this.maskEl.top.setStyle('z-index', 10000);
29745             this.maskEl.top.setSize(Roo.lib.Dom.getDocumentWidth(), box.y - this.padding);
29746             this.maskEl.top.setLeft(0);
29747             this.maskEl.top.setTop(0);
29748             this.maskEl.top.show();
29749             
29750             this.maskEl.left.setStyle('position', 'absolute');
29751             this.maskEl.left.setStyle('z-index', 10000);
29752             this.maskEl.left.setSize(box.x - this.padding, box.height + this.padding * 2);
29753             this.maskEl.left.setLeft(0);
29754             this.maskEl.left.setTop(box.y - this.padding);
29755             this.maskEl.left.show();
29756
29757             this.maskEl.bottom.setStyle('position', 'absolute');
29758             this.maskEl.bottom.setStyle('z-index', 10000);
29759             this.maskEl.bottom.setSize(Roo.lib.Dom.getDocumentWidth(), Roo.lib.Dom.getDocumentHeight() - box.bottom - this.padding);
29760             this.maskEl.bottom.setLeft(0);
29761             this.maskEl.bottom.setTop(box.bottom + this.padding);
29762             this.maskEl.bottom.show();
29763
29764             this.maskEl.right.setStyle('position', 'absolute');
29765             this.maskEl.right.setStyle('z-index', 10000);
29766             this.maskEl.right.setSize(Roo.lib.Dom.getDocumentWidth() - box.right - this.padding, box.height + this.padding * 2);
29767             this.maskEl.right.setLeft(box.right + this.padding);
29768             this.maskEl.right.setTop(box.y - this.padding);
29769             this.maskEl.right.show();
29770
29771             this.intervalID = window.setInterval(function() {
29772                 Roo.form.BasicForm.popover.unmask();
29773             }, 10000);
29774
29775             window.onwheel = function(){ return false;};
29776             
29777             (function(){ this.isMasked = true; }).defer(500, this);
29778             
29779         },
29780         
29781         unmask : function()
29782         {
29783             if(!this.isApplied || !this.isMasked || !this.form || !this.target || !this.form.errorMask){
29784                 return;
29785             }
29786             
29787             this.maskEl.top.setStyle('position', 'absolute');
29788             this.maskEl.top.setSize(0, 0).setXY([0, 0]);
29789             this.maskEl.top.hide();
29790
29791             this.maskEl.left.setStyle('position', 'absolute');
29792             this.maskEl.left.setSize(0, 0).setXY([0, 0]);
29793             this.maskEl.left.hide();
29794
29795             this.maskEl.bottom.setStyle('position', 'absolute');
29796             this.maskEl.bottom.setSize(0, 0).setXY([0, 0]);
29797             this.maskEl.bottom.hide();
29798
29799             this.maskEl.right.setStyle('position', 'absolute');
29800             this.maskEl.right.setSize(0, 0).setXY([0, 0]);
29801             this.maskEl.right.hide();
29802             
29803             window.onwheel = function(){ return true;};
29804             
29805             if(this.intervalID){
29806                 window.clearInterval(this.intervalID);
29807                 this.intervalID = false;
29808             }
29809             
29810             this.isMasked = false;
29811             
29812         }
29813         
29814     }
29815     
29816 });/*
29817  * Based on:
29818  * Ext JS Library 1.1.1
29819  * Copyright(c) 2006-2007, Ext JS, LLC.
29820  *
29821  * Originally Released Under LGPL - original licence link has changed is not relivant.
29822  *
29823  * Fork - LGPL
29824  * <script type="text/javascript">
29825  */
29826
29827 /**
29828  * @class Roo.form.Form
29829  * @extends Roo.form.BasicForm
29830  * @children Roo.form.Column Roo.form.FieldSet Roo.form.Row Roo.form.Field Roo.Button Roo.form.TextItem
29831  * Adds the ability to dynamically render forms with JavaScript to {@link Roo.form.BasicForm}.
29832  * @constructor
29833  * @param {Object} config Configuration options
29834  */
29835 Roo.form.Form = function(config){
29836     var xitems =  [];
29837     if (config.items) {
29838         xitems = config.items;
29839         delete config.items;
29840     }
29841    
29842     
29843     Roo.form.Form.superclass.constructor.call(this, null, config);
29844     this.url = this.url || this.action;
29845     if(!this.root){
29846         this.root = new Roo.form.Layout(Roo.applyIf({
29847             id: Roo.id()
29848         }, config));
29849     }
29850     this.active = this.root;
29851     /**
29852      * Array of all the buttons that have been added to this form via {@link addButton}
29853      * @type Array
29854      */
29855     this.buttons = [];
29856     this.allItems = [];
29857     this.addEvents({
29858         /**
29859          * @event clientvalidation
29860          * If the monitorValid config option is true, this event fires repetitively to notify of valid state
29861          * @param {Form} this
29862          * @param {Boolean} valid true if the form has passed client-side validation
29863          */
29864         clientvalidation: true,
29865         /**
29866          * @event rendered
29867          * Fires when the form is rendered
29868          * @param {Roo.form.Form} form
29869          */
29870         rendered : true
29871     });
29872     
29873     if (this.progressUrl) {
29874             // push a hidden field onto the list of fields..
29875             this.addxtype( {
29876                     xns: Roo.form, 
29877                     xtype : 'Hidden', 
29878                     name : 'UPLOAD_IDENTIFIER' 
29879             });
29880         }
29881         
29882     
29883     Roo.each(xitems, this.addxtype, this);
29884     
29885 };
29886
29887 Roo.extend(Roo.form.Form, Roo.form.BasicForm, {
29888      /**
29889      * @cfg {Roo.Button} buttons[] buttons at bottom of form
29890      */
29891     
29892     /**
29893      * @cfg {Number} labelWidth The width of labels. This property cascades to child containers.
29894      */
29895     /**
29896      * @cfg {String} itemCls A css class to apply to the x-form-item of fields. This property cascades to child containers.
29897      */
29898     /**
29899      * @cfg {String} (left|center|right) buttonAlign Valid values are "left," "center" and "right" (defaults to "center")
29900      */
29901     buttonAlign:'center',
29902
29903     /**
29904      * @cfg {Number} minButtonWidth Minimum width of all buttons in pixels (defaults to 75)
29905      */
29906     minButtonWidth:75,
29907
29908     /**
29909      * @cfg {String} labelAlign (left|top|right) Valid values are "left," "top" and "right" (defaults to "left").
29910      * This property cascades to child containers if not set.
29911      */
29912     labelAlign:'left',
29913
29914     /**
29915      * @cfg {Boolean} monitorValid If true the form monitors its valid state <b>client-side</b> and
29916      * fires a looping event with that state. This is required to bind buttons to the valid
29917      * state using the config value formBind:true on the button.
29918      */
29919     monitorValid : false,
29920
29921     /**
29922      * @cfg {Number} monitorPoll The milliseconds to poll valid state, ignored if monitorValid is not true (defaults to 200)
29923      */
29924     monitorPoll : 200,
29925     
29926     /**
29927      * @cfg {String} progressUrl - Url to return progress data 
29928      */
29929     
29930     progressUrl : false,
29931     /**
29932      * @cfg {boolean|FormData} formData - true to use new 'FormData' post, or set to a new FormData({dom form}) Object, if
29933      * sending a formdata with extra parameters - eg uploaded elements.
29934      */
29935     
29936     formData : false,
29937     
29938     /**
29939      * Opens a new {@link Roo.form.Column} container in the layout stack. If fields are passed after the config, the
29940      * fields are added and the column is closed. If no fields are passed the column remains open
29941      * until end() is called.
29942      * @param {Object} config The config to pass to the column
29943      * @param {Field} field1 (optional)
29944      * @param {Field} field2 (optional)
29945      * @param {Field} etc (optional)
29946      * @return Column The column container object
29947      */
29948     column : function(c){
29949         var col = new Roo.form.Column(c);
29950         this.start(col);
29951         if(arguments.length > 1){ // duplicate code required because of Opera
29952             this.add.apply(this, Array.prototype.slice.call(arguments, 1));
29953             this.end();
29954         }
29955         return col;
29956     },
29957
29958     /**
29959      * Opens a new {@link Roo.form.FieldSet} container in the layout stack. If fields are passed after the config, the
29960      * fields are added and the fieldset is closed. If no fields are passed the fieldset remains open
29961      * until end() is called.
29962      * @param {Object} config The config to pass to the fieldset
29963      * @param {Field} field1 (optional)
29964      * @param {Field} field2 (optional)
29965      * @param {Field} etc (optional)
29966      * @return FieldSet The fieldset container object
29967      */
29968     fieldset : function(c){
29969         var fs = new Roo.form.FieldSet(c);
29970         this.start(fs);
29971         if(arguments.length > 1){ // duplicate code required because of Opera
29972             this.add.apply(this, Array.prototype.slice.call(arguments, 1));
29973             this.end();
29974         }
29975         return fs;
29976     },
29977
29978     /**
29979      * Opens a new {@link Roo.form.Layout} container in the layout stack. If fields are passed after the config, the
29980      * fields are added and the container is closed. If no fields are passed the container remains open
29981      * until end() is called.
29982      * @param {Object} config The config to pass to the Layout
29983      * @param {Field} field1 (optional)
29984      * @param {Field} field2 (optional)
29985      * @param {Field} etc (optional)
29986      * @return Layout The container object
29987      */
29988     container : function(c){
29989         var l = new Roo.form.Layout(c);
29990         this.start(l);
29991         if(arguments.length > 1){ // duplicate code required because of Opera
29992             this.add.apply(this, Array.prototype.slice.call(arguments, 1));
29993             this.end();
29994         }
29995         return l;
29996     },
29997
29998     /**
29999      * Opens the passed container in the layout stack. The container can be any {@link Roo.form.Layout} or subclass.
30000      * @param {Object} container A Roo.form.Layout or subclass of Layout
30001      * @return {Form} this
30002      */
30003     start : function(c){
30004         // cascade label info
30005         Roo.applyIf(c, {'labelAlign': this.active.labelAlign, 'labelWidth': this.active.labelWidth, 'itemCls': this.active.itemCls});
30006         this.active.stack.push(c);
30007         c.ownerCt = this.active;
30008         this.active = c;
30009         return this;
30010     },
30011
30012     /**
30013      * Closes the current open container
30014      * @return {Form} this
30015      */
30016     end : function(){
30017         if(this.active == this.root){
30018             return this;
30019         }
30020         this.active = this.active.ownerCt;
30021         return this;
30022     },
30023
30024     /**
30025      * Add Roo.form components to the current open container (e.g. column, fieldset, etc.).  Fields added via this method
30026      * can also be passed with an additional property of fieldLabel, which if supplied, will provide the text to display
30027      * as the label of the field.
30028      * @param {Field} field1
30029      * @param {Field} field2 (optional)
30030      * @param {Field} etc. (optional)
30031      * @return {Form} this
30032      */
30033     add : function(){
30034         this.active.stack.push.apply(this.active.stack, arguments);
30035         this.allItems.push.apply(this.allItems,arguments);
30036         var r = [];
30037         for(var i = 0, a = arguments, len = a.length; i < len; i++) {
30038             if(a[i].isFormField){
30039                 r.push(a[i]);
30040             }
30041         }
30042         if(r.length > 0){
30043             Roo.form.Form.superclass.add.apply(this, r);
30044         }
30045         return this;
30046     },
30047     
30048
30049     
30050     
30051     
30052      /**
30053      * Find any element that has been added to a form, using it's ID or name
30054      * This can include framesets, columns etc. along with regular fields..
30055      * @param {String} id - id or name to find.
30056      
30057      * @return {Element} e - or false if nothing found.
30058      */
30059     findbyId : function(id)
30060     {
30061         var ret = false;
30062         if (!id) {
30063             return ret;
30064         }
30065         Roo.each(this.allItems, function(f){
30066             if (f.id == id || f.name == id ){
30067                 ret = f;
30068                 return false;
30069             }
30070         });
30071         return ret;
30072     },
30073
30074     
30075     
30076     /**
30077      * Render this form into the passed container. This should only be called once!
30078      * @param {String/HTMLElement/Element} container The element this component should be rendered into
30079      * @return {Form} this
30080      */
30081     render : function(ct)
30082     {
30083         
30084         
30085         
30086         ct = Roo.get(ct);
30087         var o = this.autoCreate || {
30088             tag: 'form',
30089             method : this.method || 'POST',
30090             id : this.id || Roo.id()
30091         };
30092         this.initEl(ct.createChild(o));
30093
30094         this.root.render(this.el);
30095         
30096        
30097              
30098         this.items.each(function(f){
30099             f.render('x-form-el-'+f.id);
30100         });
30101
30102         if(this.buttons.length > 0){
30103             // tables are required to maintain order and for correct IE layout
30104             var tb = this.el.createChild({cls:'x-form-btns-ct', cn: {
30105                 cls:"x-form-btns x-form-btns-"+this.buttonAlign,
30106                 html:'<table cellspacing="0"><tbody><tr></tr></tbody></table><div class="x-clear"></div>'
30107             }}, null, true);
30108             var tr = tb.getElementsByTagName('tr')[0];
30109             for(var i = 0, len = this.buttons.length; i < len; i++) {
30110                 var b = this.buttons[i];
30111                 var td = document.createElement('td');
30112                 td.className = 'x-form-btn-td';
30113                 b.render(tr.appendChild(td));
30114             }
30115         }
30116         if(this.monitorValid){ // initialize after render
30117             this.startMonitoring();
30118         }
30119         this.fireEvent('rendered', this);
30120         return this;
30121     },
30122
30123     /**
30124      * Adds a button to the footer of the form - this <b>must</b> be called before the form is rendered.
30125      * @param {String/Object} config A string becomes the button text, an object can either be a Button config
30126      * object or a valid Roo.DomHelper element config
30127      * @param {Function} handler The function called when the button is clicked
30128      * @param {Object} scope (optional) The scope of the handler function
30129      * @return {Roo.Button}
30130      */
30131     addButton : function(config, handler, scope){
30132         var bc = {
30133             handler: handler,
30134             scope: scope,
30135             minWidth: this.minButtonWidth,
30136             hideParent:true
30137         };
30138         if(typeof config == "string"){
30139             bc.text = config;
30140         }else{
30141             Roo.apply(bc, config);
30142         }
30143         var btn = new Roo.Button(null, bc);
30144         this.buttons.push(btn);
30145         return btn;
30146     },
30147
30148      /**
30149      * Adds a series of form elements (using the xtype property as the factory method.
30150      * Valid xtypes are:  TextField, TextArea .... Button, Layout, FieldSet, Column, (and 'end' to close a block)
30151      * @param {Object} config 
30152      */
30153     
30154     addxtype : function()
30155     {
30156         var ar = Array.prototype.slice.call(arguments, 0);
30157         var ret = false;
30158         for(var i = 0; i < ar.length; i++) {
30159             if (!ar[i]) {
30160                 continue; // skip -- if this happends something invalid got sent, we 
30161                 // should ignore it, as basically that interface element will not show up
30162                 // and that should be pretty obvious!!
30163             }
30164             
30165             if (Roo.form[ar[i].xtype]) {
30166                 ar[i].form = this;
30167                 var fe = Roo.factory(ar[i], Roo.form);
30168                 if (!ret) {
30169                     ret = fe;
30170                 }
30171                 fe.form = this;
30172                 if (fe.store) {
30173                     fe.store.form = this;
30174                 }
30175                 if (fe.isLayout) {  
30176                          
30177                     this.start(fe);
30178                     this.allItems.push(fe);
30179                     if (fe.items && fe.addxtype) {
30180                         fe.addxtype.apply(fe, fe.items);
30181                         delete fe.items;
30182                     }
30183                      this.end();
30184                     continue;
30185                 }
30186                 
30187                 
30188                  
30189                 this.add(fe);
30190               //  console.log('adding ' + ar[i].xtype);
30191             }
30192             if (ar[i].xtype == 'Button') {  
30193                 //console.log('adding button');
30194                 //console.log(ar[i]);
30195                 this.addButton(ar[i]);
30196                 this.allItems.push(fe);
30197                 continue;
30198             }
30199             
30200             if (ar[i].xtype == 'end') { // so we can add fieldsets... / layout etc.
30201                 alert('end is not supported on xtype any more, use items');
30202             //    this.end();
30203             //    //console.log('adding end');
30204             }
30205             
30206         }
30207         return ret;
30208     },
30209     
30210     /**
30211      * Starts monitoring of the valid state of this form. Usually this is done by passing the config
30212      * option "monitorValid"
30213      */
30214     startMonitoring : function(){
30215         if(!this.bound){
30216             this.bound = true;
30217             Roo.TaskMgr.start({
30218                 run : this.bindHandler,
30219                 interval : this.monitorPoll || 200,
30220                 scope: this
30221             });
30222         }
30223     },
30224
30225     /**
30226      * Stops monitoring of the valid state of this form
30227      */
30228     stopMonitoring : function(){
30229         this.bound = false;
30230     },
30231
30232     // private
30233     bindHandler : function(){
30234         if(!this.bound){
30235             return false; // stops binding
30236         }
30237         var valid = true;
30238         this.items.each(function(f){
30239             if(!f.isValid(true)){
30240                 valid = false;
30241                 return false;
30242             }
30243         });
30244         for(var i = 0, len = this.buttons.length; i < len; i++){
30245             var btn = this.buttons[i];
30246             if(btn.formBind === true && btn.disabled === valid){
30247                 btn.setDisabled(!valid);
30248             }
30249         }
30250         this.fireEvent('clientvalidation', this, valid);
30251     }
30252     
30253     
30254     
30255     
30256     
30257     
30258     
30259     
30260 });
30261
30262
30263 // back compat
30264 Roo.Form = Roo.form.Form;
30265 /*
30266  * Based on:
30267  * Ext JS Library 1.1.1
30268  * Copyright(c) 2006-2007, Ext JS, LLC.
30269  *
30270  * Originally Released Under LGPL - original licence link has changed is not relivant.
30271  *
30272  * Fork - LGPL
30273  * <script type="text/javascript">
30274  */
30275
30276 // as we use this in bootstrap.
30277 Roo.namespace('Roo.form');
30278  /**
30279  * @class Roo.form.Action
30280  * Internal Class used to handle form actions
30281  * @constructor
30282  * @param {Roo.form.BasicForm} el The form element or its id
30283  * @param {Object} config Configuration options
30284  */
30285
30286  
30287  
30288 // define the action interface
30289 Roo.form.Action = function(form, options){
30290     this.form = form;
30291     this.options = options || {};
30292 };
30293 /**
30294  * Client Validation Failed
30295  * @const 
30296  */
30297 Roo.form.Action.CLIENT_INVALID = 'client';
30298 /**
30299  * Server Validation Failed
30300  * @const 
30301  */
30302 Roo.form.Action.SERVER_INVALID = 'server';
30303  /**
30304  * Connect to Server Failed
30305  * @const 
30306  */
30307 Roo.form.Action.CONNECT_FAILURE = 'connect';
30308 /**
30309  * Reading Data from Server Failed
30310  * @const 
30311  */
30312 Roo.form.Action.LOAD_FAILURE = 'load';
30313
30314 Roo.form.Action.prototype = {
30315     type : 'default',
30316     failureType : undefined,
30317     response : undefined,
30318     result : undefined,
30319
30320     // interface method
30321     run : function(options){
30322
30323     },
30324
30325     // interface method
30326     success : function(response){
30327
30328     },
30329
30330     // interface method
30331     handleResponse : function(response){
30332
30333     },
30334
30335     // default connection failure
30336     failure : function(response){
30337         
30338         this.response = response;
30339         this.failureType = Roo.form.Action.CONNECT_FAILURE;
30340         this.form.afterAction(this, false);
30341     },
30342
30343     processResponse : function(response){
30344         this.response = response;
30345         if(!response.responseText){
30346             return true;
30347         }
30348         this.result = this.handleResponse(response);
30349         return this.result;
30350     },
30351
30352     // utility functions used internally
30353     getUrl : function(appendParams){
30354         var url = this.options.url || this.form.url || this.form.el.dom.action;
30355         if(appendParams){
30356             var p = this.getParams();
30357             if(p){
30358                 url += (url.indexOf('?') != -1 ? '&' : '?') + p;
30359             }
30360         }
30361         return url;
30362     },
30363
30364     getMethod : function(){
30365         return (this.options.method || this.form.method || this.form.el.dom.method || 'POST').toUpperCase();
30366     },
30367
30368     getParams : function(){
30369         var bp = this.form.baseParams;
30370         var p = this.options.params;
30371         if(p){
30372             if(typeof p == "object"){
30373                 p = Roo.urlEncode(Roo.applyIf(p, bp));
30374             }else if(typeof p == 'string' && bp){
30375                 p += '&' + Roo.urlEncode(bp);
30376             }
30377         }else if(bp){
30378             p = Roo.urlEncode(bp);
30379         }
30380         return p;
30381     },
30382
30383     createCallback : function(){
30384         return {
30385             success: this.success,
30386             failure: this.failure,
30387             scope: this,
30388             timeout: (this.form.timeout*1000),
30389             upload: this.form.fileUpload ? this.success : undefined
30390         };
30391     }
30392 };
30393
30394 Roo.form.Action.Submit = function(form, options){
30395     Roo.form.Action.Submit.superclass.constructor.call(this, form, options);
30396 };
30397
30398 Roo.extend(Roo.form.Action.Submit, Roo.form.Action, {
30399     type : 'submit',
30400
30401     haveProgress : false,
30402     uploadComplete : false,
30403     
30404     // uploadProgress indicator.
30405     uploadProgress : function()
30406     {
30407         if (!this.form.progressUrl) {
30408             return;
30409         }
30410         
30411         if (!this.haveProgress) {
30412             Roo.MessageBox.progress("Uploading", "Uploading");
30413         }
30414         if (this.uploadComplete) {
30415            Roo.MessageBox.hide();
30416            return;
30417         }
30418         
30419         this.haveProgress = true;
30420    
30421         var uid = this.form.findField('UPLOAD_IDENTIFIER').getValue();
30422         
30423         var c = new Roo.data.Connection();
30424         c.request({
30425             url : this.form.progressUrl,
30426             params: {
30427                 id : uid
30428             },
30429             method: 'GET',
30430             success : function(req){
30431                //console.log(data);
30432                 var rdata = false;
30433                 var edata;
30434                 try  {
30435                    rdata = Roo.decode(req.responseText)
30436                 } catch (e) {
30437                     Roo.log("Invalid data from server..");
30438                     Roo.log(edata);
30439                     return;
30440                 }
30441                 if (!rdata || !rdata.success) {
30442                     Roo.log(rdata);
30443                     Roo.MessageBox.alert(Roo.encode(rdata));
30444                     return;
30445                 }
30446                 var data = rdata.data;
30447                 
30448                 if (this.uploadComplete) {
30449                    Roo.MessageBox.hide();
30450                    return;
30451                 }
30452                    
30453                 if (data){
30454                     Roo.MessageBox.updateProgress(data.bytes_uploaded/data.bytes_total,
30455                        Math.floor((data.bytes_total - data.bytes_uploaded)/1000) + 'k remaining'
30456                     );
30457                 }
30458                 this.uploadProgress.defer(2000,this);
30459             },
30460        
30461             failure: function(data) {
30462                 Roo.log('progress url failed ');
30463                 Roo.log(data);
30464             },
30465             scope : this
30466         });
30467            
30468     },
30469     
30470     
30471     run : function()
30472     {
30473         // run get Values on the form, so it syncs any secondary forms.
30474         this.form.getValues();
30475         
30476         var o = this.options;
30477         var method = this.getMethod();
30478         var isPost = method == 'POST';
30479         if(o.clientValidation === false || this.form.isValid()){
30480             
30481             if (this.form.progressUrl) {
30482                 this.form.findField('UPLOAD_IDENTIFIER').setValue(
30483                     (new Date() * 1) + '' + Math.random());
30484                     
30485             } 
30486             
30487             
30488             Roo.Ajax.request(Roo.apply(this.createCallback(), {
30489                 form:this.form.el.dom,
30490                 url:this.getUrl(!isPost),
30491                 method: method,
30492                 params:isPost ? this.getParams() : null,
30493                 isUpload: this.form.fileUpload,
30494                 formData : this.form.formData
30495             }));
30496             
30497             this.uploadProgress();
30498
30499         }else if (o.clientValidation !== false){ // client validation failed
30500             this.failureType = Roo.form.Action.CLIENT_INVALID;
30501             this.form.afterAction(this, false);
30502         }
30503     },
30504
30505     success : function(response)
30506     {
30507         this.uploadComplete= true;
30508         if (this.haveProgress) {
30509             Roo.MessageBox.hide();
30510         }
30511         
30512         
30513         var result = this.processResponse(response);
30514         if(result === true || result.success){
30515             this.form.afterAction(this, true);
30516             return;
30517         }
30518         if(result.errors){
30519             this.form.markInvalid(result.errors);
30520             this.failureType = Roo.form.Action.SERVER_INVALID;
30521         }
30522         this.form.afterAction(this, false);
30523     },
30524     failure : function(response)
30525     {
30526         this.uploadComplete= true;
30527         if (this.haveProgress) {
30528             Roo.MessageBox.hide();
30529         }
30530         
30531         this.response = response;
30532         this.failureType = Roo.form.Action.CONNECT_FAILURE;
30533         this.form.afterAction(this, false);
30534     },
30535     
30536     handleResponse : function(response){
30537         if(this.form.errorReader){
30538             var rs = this.form.errorReader.read(response);
30539             var errors = [];
30540             if(rs.records){
30541                 for(var i = 0, len = rs.records.length; i < len; i++) {
30542                     var r = rs.records[i];
30543                     errors[i] = r.data;
30544                 }
30545             }
30546             if(errors.length < 1){
30547                 errors = null;
30548             }
30549             return {
30550                 success : rs.success,
30551                 errors : errors
30552             };
30553         }
30554         var ret = false;
30555         try {
30556             ret = Roo.decode(response.responseText);
30557         } catch (e) {
30558             ret = {
30559                 success: false,
30560                 errorMsg: "Failed to read server message: " + (response ? response.responseText : ' - no message'),
30561                 errors : []
30562             };
30563         }
30564         return ret;
30565         
30566     }
30567 });
30568
30569
30570 Roo.form.Action.Load = function(form, options){
30571     Roo.form.Action.Load.superclass.constructor.call(this, form, options);
30572     this.reader = this.form.reader;
30573 };
30574
30575 Roo.extend(Roo.form.Action.Load, Roo.form.Action, {
30576     type : 'load',
30577
30578     run : function(){
30579         
30580         Roo.Ajax.request(Roo.apply(
30581                 this.createCallback(), {
30582                     method:this.getMethod(),
30583                     url:this.getUrl(false),
30584                     params:this.getParams()
30585         }));
30586     },
30587
30588     success : function(response){
30589         
30590         var result = this.processResponse(response);
30591         if(result === true || !result.success || !result.data){
30592             this.failureType = Roo.form.Action.LOAD_FAILURE;
30593             this.form.afterAction(this, false);
30594             return;
30595         }
30596         this.form.clearInvalid();
30597         this.form.setValues(result.data);
30598         this.form.afterAction(this, true);
30599     },
30600
30601     handleResponse : function(response){
30602         if(this.form.reader){
30603             var rs = this.form.reader.read(response);
30604             var data = rs.records && rs.records[0] ? rs.records[0].data : null;
30605             return {
30606                 success : rs.success,
30607                 data : data
30608             };
30609         }
30610         return Roo.decode(response.responseText);
30611     }
30612 });
30613
30614 Roo.form.Action.ACTION_TYPES = {
30615     'load' : Roo.form.Action.Load,
30616     'submit' : Roo.form.Action.Submit
30617 };/*
30618  * Based on:
30619  * Ext JS Library 1.1.1
30620  * Copyright(c) 2006-2007, Ext JS, LLC.
30621  *
30622  * Originally Released Under LGPL - original licence link has changed is not relivant.
30623  *
30624  * Fork - LGPL
30625  * <script type="text/javascript">
30626  */
30627  
30628 /**
30629  * @class Roo.form.Layout
30630  * @extends Roo.Component
30631  * @children Roo.form.Column Roo.form.Row Roo.form.Field Roo.Button Roo.form.TextItem Roo.form.FieldSet
30632  * Creates a container for layout and rendering of fields in an {@link Roo.form.Form}.
30633  * @constructor
30634  * @param {Object} config Configuration options
30635  */
30636 Roo.form.Layout = function(config){
30637     var xitems = [];
30638     if (config.items) {
30639         xitems = config.items;
30640         delete config.items;
30641     }
30642     Roo.form.Layout.superclass.constructor.call(this, config);
30643     this.stack = [];
30644     Roo.each(xitems, this.addxtype, this);
30645      
30646 };
30647
30648 Roo.extend(Roo.form.Layout, Roo.Component, {
30649     /**
30650      * @cfg {String/Object} autoCreate
30651      * A DomHelper element spec used to autocreate the layout (defaults to {tag: 'div', cls: 'x-form-ct'})
30652      */
30653     /**
30654      * @cfg {String/Object/Function} style
30655      * A style specification string, e.g. "width:100px", or object in the form {width:"100px"}, or
30656      * a function which returns such a specification.
30657      */
30658     /**
30659      * @cfg {String} labelAlign
30660      * Valid values are "left," "top" and "right" (defaults to "left")
30661      */
30662     /**
30663      * @cfg {Number} labelWidth
30664      * Fixed width in pixels of all field labels (defaults to undefined)
30665      */
30666     /**
30667      * @cfg {Boolean} clear
30668      * True to add a clearing element at the end of this layout, equivalent to CSS clear: both (defaults to true)
30669      */
30670     clear : true,
30671     /**
30672      * @cfg {String} labelSeparator
30673      * The separator to use after field labels (defaults to ':')
30674      */
30675     labelSeparator : ':',
30676     /**
30677      * @cfg {Boolean} hideLabels
30678      * True to suppress the display of field labels in this layout (defaults to false)
30679      */
30680     hideLabels : false,
30681
30682     // private
30683     defaultAutoCreate : {tag: 'div', cls: 'x-form-ct'},
30684     
30685     isLayout : true,
30686     
30687     // private
30688     onRender : function(ct, position){
30689         if(this.el){ // from markup
30690             this.el = Roo.get(this.el);
30691         }else {  // generate
30692             var cfg = this.getAutoCreate();
30693             this.el = ct.createChild(cfg, position);
30694         }
30695         if(this.style){
30696             this.el.applyStyles(this.style);
30697         }
30698         if(this.labelAlign){
30699             this.el.addClass('x-form-label-'+this.labelAlign);
30700         }
30701         if(this.hideLabels){
30702             this.labelStyle = "display:none";
30703             this.elementStyle = "padding-left:0;";
30704         }else{
30705             if(typeof this.labelWidth == 'number'){
30706                 this.labelStyle = "width:"+this.labelWidth+"px;";
30707                 this.elementStyle = "padding-left:"+((this.labelWidth+(typeof this.labelPad == 'number' ? this.labelPad : 5))+'px')+";";
30708             }
30709             if(this.labelAlign == 'top'){
30710                 this.labelStyle = "width:auto;";
30711                 this.elementStyle = "padding-left:0;";
30712             }
30713         }
30714         var stack = this.stack;
30715         var slen = stack.length;
30716         if(slen > 0){
30717             if(!this.fieldTpl){
30718                 var t = new Roo.Template(
30719                     '<div class="x-form-item {5}">',
30720                         '<label for="{0}" style="{2}">{1}{4}</label>',
30721                         '<div class="x-form-element" id="x-form-el-{0}" style="{3}">',
30722                         '</div>',
30723                     '</div><div class="x-form-clear-left"></div>'
30724                 );
30725                 t.disableFormats = true;
30726                 t.compile();
30727                 Roo.form.Layout.prototype.fieldTpl = t;
30728             }
30729             for(var i = 0; i < slen; i++) {
30730                 if(stack[i].isFormField){
30731                     this.renderField(stack[i]);
30732                 }else{
30733                     this.renderComponent(stack[i]);
30734                 }
30735             }
30736         }
30737         if(this.clear){
30738             this.el.createChild({cls:'x-form-clear'});
30739         }
30740     },
30741
30742     // private
30743     renderField : function(f){
30744         f.fieldEl = Roo.get(this.fieldTpl.append(this.el, [
30745                f.id, //0
30746                f.fieldLabel, //1
30747                f.labelStyle||this.labelStyle||'', //2
30748                this.elementStyle||'', //3
30749                typeof f.labelSeparator == 'undefined' ? this.labelSeparator : f.labelSeparator, //4
30750                f.itemCls||this.itemCls||''  //5
30751        ], true).getPrevSibling());
30752     },
30753
30754     // private
30755     renderComponent : function(c){
30756         c.render(c.isLayout ? this.el : this.el.createChild());    
30757     },
30758     /**
30759      * Adds a object form elements (using the xtype property as the factory method.)
30760      * Valid xtypes are:  TextField, TextArea .... Button, Layout, FieldSet, Column
30761      * @param {Object} config 
30762      */
30763     addxtype : function(o)
30764     {
30765         // create the lement.
30766         o.form = this.form;
30767         var fe = Roo.factory(o, Roo.form);
30768         this.form.allItems.push(fe);
30769         this.stack.push(fe);
30770         
30771         if (fe.isFormField) {
30772             this.form.items.add(fe);
30773         }
30774          
30775         return fe;
30776     }
30777 });
30778
30779 /**
30780  * @class Roo.form.Column
30781  * @extends Roo.form.Layout
30782  * @children Roo.form.Row Roo.form.Field Roo.Button Roo.form.TextItem Roo.form.FieldSet
30783  * Creates a column container for layout and rendering of fields in an {@link Roo.form.Form}.
30784  * @constructor
30785  * @param {Object} config Configuration options
30786  */
30787 Roo.form.Column = function(config){
30788     Roo.form.Column.superclass.constructor.call(this, config);
30789 };
30790
30791 Roo.extend(Roo.form.Column, Roo.form.Layout, {
30792     /**
30793      * @cfg {Number/String} width
30794      * The fixed width of the column in pixels or CSS value (defaults to "auto")
30795      */
30796     /**
30797      * @cfg {String/Object} autoCreate
30798      * A DomHelper element spec used to autocreate the column (defaults to {tag: 'div', cls: 'x-form-ct x-form-column'})
30799      */
30800
30801     // private
30802     defaultAutoCreate : {tag: 'div', cls: 'x-form-ct x-form-column'},
30803
30804     // private
30805     onRender : function(ct, position){
30806         Roo.form.Column.superclass.onRender.call(this, ct, position);
30807         if(this.width){
30808             this.el.setWidth(this.width);
30809         }
30810     }
30811 });
30812
30813
30814 /**
30815  * @class Roo.form.Row
30816  * @extends Roo.form.Layout
30817  * @children Roo.form.Column Roo.form.Row Roo.form.Field Roo.Button Roo.form.TextItem Roo.form.FieldSet
30818  * Creates a row container for layout and rendering of fields in an {@link Roo.form.Form}.
30819  * @constructor
30820  * @param {Object} config Configuration options
30821  */
30822
30823  
30824 Roo.form.Row = function(config){
30825     Roo.form.Row.superclass.constructor.call(this, config);
30826 };
30827  
30828 Roo.extend(Roo.form.Row, Roo.form.Layout, {
30829       /**
30830      * @cfg {Number/String} width
30831      * The fixed width of the column in pixels or CSS value (defaults to "auto")
30832      */
30833     /**
30834      * @cfg {Number/String} height
30835      * The fixed height of the column in pixels or CSS value (defaults to "auto")
30836      */
30837     defaultAutoCreate : {tag: 'div', cls: 'x-form-ct x-form-row'},
30838     
30839     padWidth : 20,
30840     // private
30841     onRender : function(ct, position){
30842         //console.log('row render');
30843         if(!this.rowTpl){
30844             var t = new Roo.Template(
30845                 '<div class="x-form-item {5}" style="float:left;width:{6}px">',
30846                     '<label for="{0}" style="{2}">{1}{4}</label>',
30847                     '<div class="x-form-element" id="x-form-el-{0}" style="{3}">',
30848                     '</div>',
30849                 '</div>'
30850             );
30851             t.disableFormats = true;
30852             t.compile();
30853             Roo.form.Layout.prototype.rowTpl = t;
30854         }
30855         this.fieldTpl = this.rowTpl;
30856         
30857         //console.log('lw' + this.labelWidth +', la:' + this.labelAlign);
30858         var labelWidth = 100;
30859         
30860         if ((this.labelAlign != 'top')) {
30861             if (typeof this.labelWidth == 'number') {
30862                 labelWidth = this.labelWidth
30863             }
30864             this.padWidth =  20 + labelWidth;
30865             
30866         }
30867         
30868         Roo.form.Column.superclass.onRender.call(this, ct, position);
30869         if(this.width){
30870             this.el.setWidth(this.width);
30871         }
30872         if(this.height){
30873             this.el.setHeight(this.height);
30874         }
30875     },
30876     
30877     // private
30878     renderField : function(f){
30879         f.fieldEl = this.fieldTpl.append(this.el, [
30880                f.id, f.fieldLabel,
30881                f.labelStyle||this.labelStyle||'',
30882                this.elementStyle||'',
30883                typeof f.labelSeparator == 'undefined' ? this.labelSeparator : f.labelSeparator,
30884                f.itemCls||this.itemCls||'',
30885                f.width ? f.width + this.padWidth : 160 + this.padWidth
30886        ],true);
30887     }
30888 });
30889  
30890
30891 /**
30892  * @class Roo.form.FieldSet
30893  * @extends Roo.form.Layout
30894  * @children Roo.form.Column Roo.form.Row Roo.form.Field Roo.Button Roo.form.TextItem
30895  * Creates a fieldset container for layout and rendering of fields in an {@link Roo.form.Form}.
30896  * @constructor
30897  * @param {Object} config Configuration options
30898  */
30899 Roo.form.FieldSet = function(config){
30900     Roo.form.FieldSet.superclass.constructor.call(this, config);
30901 };
30902
30903 Roo.extend(Roo.form.FieldSet, Roo.form.Layout, {
30904     /**
30905      * @cfg {String} legend
30906      * The text to display as the legend for the FieldSet (defaults to '')
30907      */
30908     /**
30909      * @cfg {String/Object} autoCreate
30910      * A DomHelper element spec used to autocreate the fieldset (defaults to {tag: 'fieldset', cn: {tag:'legend'}})
30911      */
30912
30913     // private
30914     defaultAutoCreate : {tag: 'fieldset', cn: {tag:'legend'}},
30915
30916     // private
30917     onRender : function(ct, position){
30918         Roo.form.FieldSet.superclass.onRender.call(this, ct, position);
30919         if(this.legend){
30920             this.setLegend(this.legend);
30921         }
30922     },
30923
30924     // private
30925     setLegend : function(text){
30926         if(this.rendered){
30927             this.el.child('legend').update(text);
30928         }
30929     }
30930 });/*
30931  * Based on:
30932  * Ext JS Library 1.1.1
30933  * Copyright(c) 2006-2007, Ext JS, LLC.
30934  *
30935  * Originally Released Under LGPL - original licence link has changed is not relivant.
30936  *
30937  * Fork - LGPL
30938  * <script type="text/javascript">
30939  */
30940 /**
30941  * @class Roo.form.VTypes
30942  * Overridable validation definitions. The validations provided are basic and intended to be easily customizable and extended.
30943  * @static
30944  */
30945 Roo.form.VTypes = function(){
30946     // closure these in so they are only created once.
30947     var alpha = /^[a-zA-Z_]+$/;
30948     var alphanum = /^[a-zA-Z0-9_]+$/;
30949     var email = /^([\w]+)(.[\w]+)*@([\w-]+\.){1,5}([A-Za-z]){2,24}$/;
30950     var url = /(((https?)|(ftp)):\/\/([\-\w]+\.)+\w{2,3}(\/[%\-\w]+(\.\w{2,})?)*(([\w\-\.\?\\\/+@&#;`~=%!]*)(\.\w{2,})?)*\/?)/i;
30951
30952     // All these messages and functions are configurable
30953     return {
30954         /**
30955          * The function used to validate email addresses
30956          * @param {String} value The email address
30957          */
30958         'email' : function(v){
30959             return email.test(v);
30960         },
30961         /**
30962          * The error text to display when the email validation function returns false
30963          * @type String
30964          */
30965         'emailText' : 'This field should be an e-mail address in the format "user@domain.com"',
30966         /**
30967          * The keystroke filter mask to be applied on email input
30968          * @type RegExp
30969          */
30970         'emailMask' : /[a-z0-9_\.\-@]/i,
30971
30972         /**
30973          * The function used to validate URLs
30974          * @param {String} value The URL
30975          */
30976         'url' : function(v){
30977             return url.test(v);
30978         },
30979         /**
30980          * The error text to display when the url validation function returns false
30981          * @type String
30982          */
30983         'urlText' : 'This field should be a URL in the format "http:/'+'/www.domain.com"',
30984         
30985         /**
30986          * The function used to validate alpha values
30987          * @param {String} value The value
30988          */
30989         'alpha' : function(v){
30990             return alpha.test(v);
30991         },
30992         /**
30993          * The error text to display when the alpha validation function returns false
30994          * @type String
30995          */
30996         'alphaText' : 'This field should only contain letters and _',
30997         /**
30998          * The keystroke filter mask to be applied on alpha input
30999          * @type RegExp
31000          */
31001         'alphaMask' : /[a-z_]/i,
31002
31003         /**
31004          * The function used to validate alphanumeric values
31005          * @param {String} value The value
31006          */
31007         'alphanum' : function(v){
31008             return alphanum.test(v);
31009         },
31010         /**
31011          * The error text to display when the alphanumeric validation function returns false
31012          * @type String
31013          */
31014         'alphanumText' : 'This field should only contain letters, numbers and _',
31015         /**
31016          * The keystroke filter mask to be applied on alphanumeric input
31017          * @type RegExp
31018          */
31019         'alphanumMask' : /[a-z0-9_]/i
31020     };
31021 }();//<script type="text/javascript">
31022
31023 /**
31024  * @class Roo.form.FCKeditor
31025  * @extends Roo.form.TextArea
31026  * Wrapper around the FCKEditor http://www.fckeditor.net
31027  * @constructor
31028  * Creates a new FCKeditor
31029  * @param {Object} config Configuration options
31030  */
31031 Roo.form.FCKeditor = function(config){
31032     Roo.form.FCKeditor.superclass.constructor.call(this, config);
31033     this.addEvents({
31034          /**
31035          * @event editorinit
31036          * Fired when the editor is initialized - you can add extra handlers here..
31037          * @param {FCKeditor} this
31038          * @param {Object} the FCK object.
31039          */
31040         editorinit : true
31041     });
31042     
31043     
31044 };
31045 Roo.form.FCKeditor.editors = { };
31046 Roo.extend(Roo.form.FCKeditor, Roo.form.TextArea,
31047 {
31048     //defaultAutoCreate : {
31049     //    tag : "textarea",style   : "width:100px;height:60px;" ,autocomplete    : "off"
31050     //},
31051     // private
31052     /**
31053      * @cfg {Object} fck options - see fck manual for details.
31054      */
31055     fckconfig : false,
31056     
31057     /**
31058      * @cfg {Object} fck toolbar set (Basic or Default)
31059      */
31060     toolbarSet : 'Basic',
31061     /**
31062      * @cfg {Object} fck BasePath
31063      */ 
31064     basePath : '/fckeditor/',
31065     
31066     
31067     frame : false,
31068     
31069     value : '',
31070     
31071    
31072     onRender : function(ct, position)
31073     {
31074         if(!this.el){
31075             this.defaultAutoCreate = {
31076                 tag: "textarea",
31077                 style:"width:300px;height:60px;",
31078                 autocomplete: "new-password"
31079             };
31080         }
31081         Roo.form.FCKeditor.superclass.onRender.call(this, ct, position);
31082         /*
31083         if(this.grow){
31084             this.textSizeEl = Roo.DomHelper.append(document.body, {tag: "pre", cls: "x-form-grow-sizer"});
31085             if(this.preventScrollbars){
31086                 this.el.setStyle("overflow", "hidden");
31087             }
31088             this.el.setHeight(this.growMin);
31089         }
31090         */
31091         //console.log('onrender' + this.getId() );
31092         Roo.form.FCKeditor.editors[this.getId()] = this;
31093          
31094
31095         this.replaceTextarea() ;
31096         
31097     },
31098     
31099     getEditor : function() {
31100         return this.fckEditor;
31101     },
31102     /**
31103      * Sets a data value into the field and validates it.  To set the value directly without validation see {@link #setRawValue}.
31104      * @param {Mixed} value The value to set
31105      */
31106     
31107     
31108     setValue : function(value)
31109     {
31110         //console.log('setValue: ' + value);
31111         
31112         if(typeof(value) == 'undefined') { // not sure why this is happending...
31113             return;
31114         }
31115         Roo.form.FCKeditor.superclass.setValue.apply(this,[value]);
31116         
31117         //if(!this.el || !this.getEditor()) {
31118         //    this.value = value;
31119             //this.setValue.defer(100,this,[value]);    
31120         //    return;
31121         //} 
31122         
31123         if(!this.getEditor()) {
31124             return;
31125         }
31126         
31127         this.getEditor().SetData(value);
31128         
31129         //
31130
31131     },
31132
31133     /**
31134      * Returns the normalized data value (undefined or emptyText will be returned as '').  To return the raw value see {@link #getRawValue}.
31135      * @return {Mixed} value The field value
31136      */
31137     getValue : function()
31138     {
31139         
31140         if (this.frame && this.frame.dom.style.display == 'none') {
31141             return Roo.form.FCKeditor.superclass.getValue.call(this);
31142         }
31143         
31144         if(!this.el || !this.getEditor()) {
31145            
31146            // this.getValue.defer(100,this); 
31147             return this.value;
31148         }
31149        
31150         
31151         var value=this.getEditor().GetData();
31152         Roo.form.FCKeditor.superclass.setValue.apply(this,[value]);
31153         return Roo.form.FCKeditor.superclass.getValue.call(this);
31154         
31155
31156     },
31157
31158     /**
31159      * Returns the raw data value which may or may not be a valid, defined value.  To return a normalized value see {@link #getValue}.
31160      * @return {Mixed} value The field value
31161      */
31162     getRawValue : function()
31163     {
31164         if (this.frame && this.frame.dom.style.display == 'none') {
31165             return Roo.form.FCKeditor.superclass.getRawValue.call(this);
31166         }
31167         
31168         if(!this.el || !this.getEditor()) {
31169             //this.getRawValue.defer(100,this); 
31170             return this.value;
31171             return;
31172         }
31173         
31174         
31175         
31176         var value=this.getEditor().GetData();
31177         Roo.form.FCKeditor.superclass.setRawValue.apply(this,[value]);
31178         return Roo.form.FCKeditor.superclass.getRawValue.call(this);
31179          
31180     },
31181     
31182     setSize : function(w,h) {
31183         
31184         
31185         
31186         //if (this.frame && this.frame.dom.style.display == 'none') {
31187         //    Roo.form.FCKeditor.superclass.setSize.apply(this, [w, h]);
31188         //    return;
31189         //}
31190         //if(!this.el || !this.getEditor()) {
31191         //    this.setSize.defer(100,this, [w,h]); 
31192         //    return;
31193         //}
31194         
31195         
31196         
31197         Roo.form.FCKeditor.superclass.setSize.apply(this, [w, h]);
31198         
31199         this.frame.dom.setAttribute('width', w);
31200         this.frame.dom.setAttribute('height', h);
31201         this.frame.setSize(w,h);
31202         
31203     },
31204     
31205     toggleSourceEdit : function(value) {
31206         
31207       
31208          
31209         this.el.dom.style.display = value ? '' : 'none';
31210         this.frame.dom.style.display = value ?  'none' : '';
31211         
31212     },
31213     
31214     
31215     focus: function(tag)
31216     {
31217         if (this.frame.dom.style.display == 'none') {
31218             return Roo.form.FCKeditor.superclass.focus.call(this);
31219         }
31220         if(!this.el || !this.getEditor()) {
31221             this.focus.defer(100,this, [tag]); 
31222             return;
31223         }
31224         
31225         
31226         
31227         
31228         var tgs = this.getEditor().EditorDocument.getElementsByTagName(tag);
31229         this.getEditor().Focus();
31230         if (tgs.length) {
31231             if (!this.getEditor().Selection.GetSelection()) {
31232                 this.focus.defer(100,this, [tag]); 
31233                 return;
31234             }
31235             
31236             
31237             var r = this.getEditor().EditorDocument.createRange();
31238             r.setStart(tgs[0],0);
31239             r.setEnd(tgs[0],0);
31240             this.getEditor().Selection.GetSelection().removeAllRanges();
31241             this.getEditor().Selection.GetSelection().addRange(r);
31242             this.getEditor().Focus();
31243         }
31244         
31245     },
31246     
31247     
31248     
31249     replaceTextarea : function()
31250     {
31251         if ( document.getElementById( this.getId() + '___Frame' ) ) {
31252             return ;
31253         }
31254         //if ( !this.checkBrowser || this._isCompatibleBrowser() )
31255         //{
31256             // We must check the elements firstly using the Id and then the name.
31257         var oTextarea = document.getElementById( this.getId() );
31258         
31259         var colElementsByName = document.getElementsByName( this.getId() ) ;
31260          
31261         oTextarea.style.display = 'none' ;
31262
31263         if ( oTextarea.tabIndex ) {            
31264             this.TabIndex = oTextarea.tabIndex ;
31265         }
31266         
31267         this._insertHtmlBefore( this._getConfigHtml(), oTextarea ) ;
31268         this._insertHtmlBefore( this._getIFrameHtml(), oTextarea ) ;
31269         this.frame = Roo.get(this.getId() + '___Frame')
31270     },
31271     
31272     _getConfigHtml : function()
31273     {
31274         var sConfig = '' ;
31275
31276         for ( var o in this.fckconfig ) {
31277             sConfig += sConfig.length > 0  ? '&amp;' : '';
31278             sConfig += encodeURIComponent( o ) + '=' + encodeURIComponent( this.fckconfig[o] ) ;
31279         }
31280
31281         return '<input type="hidden" id="' + this.getId() + '___Config" value="' + sConfig + '" style="display:none" />' ;
31282     },
31283     
31284     
31285     _getIFrameHtml : function()
31286     {
31287         var sFile = 'fckeditor.html' ;
31288         /* no idea what this is about..
31289         try
31290         {
31291             if ( (/fcksource=true/i).test( window.top.location.search ) )
31292                 sFile = 'fckeditor.original.html' ;
31293         }
31294         catch (e) { 
31295         */
31296
31297         var sLink = this.basePath + 'editor/' + sFile + '?InstanceName=' + encodeURIComponent( this.getId() ) ;
31298         sLink += this.toolbarSet ? ( '&amp;Toolbar=' + this.toolbarSet)  : '';
31299         
31300         
31301         var html = '<iframe id="' + this.getId() +
31302             '___Frame" src="' + sLink +
31303             '" width="' + this.width +
31304             '" height="' + this.height + '"' +
31305             (this.tabIndex ?  ' tabindex="' + this.tabIndex + '"' :'' ) +
31306             ' frameborder="0" scrolling="no"></iframe>' ;
31307
31308         return html ;
31309     },
31310     
31311     _insertHtmlBefore : function( html, element )
31312     {
31313         if ( element.insertAdjacentHTML )       {
31314             // IE
31315             element.insertAdjacentHTML( 'beforeBegin', html ) ;
31316         } else { // Gecko
31317             var oRange = document.createRange() ;
31318             oRange.setStartBefore( element ) ;
31319             var oFragment = oRange.createContextualFragment( html );
31320             element.parentNode.insertBefore( oFragment, element ) ;
31321         }
31322     }
31323     
31324     
31325   
31326     
31327     
31328     
31329     
31330
31331 });
31332
31333 //Roo.reg('fckeditor', Roo.form.FCKeditor);
31334
31335 function FCKeditor_OnComplete(editorInstance){
31336     var f = Roo.form.FCKeditor.editors[editorInstance.Name];
31337     f.fckEditor = editorInstance;
31338     //console.log("loaded");
31339     f.fireEvent('editorinit', f, editorInstance);
31340
31341   
31342
31343  
31344
31345
31346
31347
31348
31349
31350
31351
31352
31353
31354
31355
31356
31357
31358
31359 //<script type="text/javascript">
31360 /**
31361  * @class Roo.form.GridField
31362  * @extends Roo.form.Field
31363  * Embed a grid (or editable grid into a form)
31364  * STATUS ALPHA
31365  * 
31366  * This embeds a grid in a form, the value of the field should be the json encoded array of rows
31367  * it needs 
31368  * xgrid.store = Roo.data.Store
31369  * xgrid.store.proxy = Roo.data.MemoryProxy (data = [] )
31370  * xgrid.store.reader = Roo.data.JsonReader 
31371  * 
31372  * 
31373  * @constructor
31374  * Creates a new GridField
31375  * @param {Object} config Configuration options
31376  */
31377 Roo.form.GridField = function(config){
31378     Roo.form.GridField.superclass.constructor.call(this, config);
31379      
31380 };
31381
31382 Roo.extend(Roo.form.GridField, Roo.form.Field,  {
31383     /**
31384      * @cfg {Number} width  - used to restrict width of grid..
31385      */
31386     width : 100,
31387     /**
31388      * @cfg {Number} height - used to restrict height of grid..
31389      */
31390     height : 50,
31391      /**
31392      * @cfg {Object} xgrid (xtype'd description of grid) { xtype : 'Grid', dataSource: .... }
31393          * 
31394          *}
31395      */
31396     xgrid : false, 
31397     /**
31398      * @cfg {String/Object} autoCreate A DomHelper element spec, or true for a default element spec (defaults to
31399      * {tag: "input", type: "checkbox", autocomplete: "off"})
31400      */
31401    // defaultAutoCreate : { tag: 'div' },
31402     defaultAutoCreate : { tag: 'input', type: 'hidden', autocomplete: 'new-password'},
31403     /**
31404      * @cfg {String} addTitle Text to include for adding a title.
31405      */
31406     addTitle : false,
31407     //
31408     onResize : function(){
31409         Roo.form.Field.superclass.onResize.apply(this, arguments);
31410     },
31411
31412     initEvents : function(){
31413         // Roo.form.Checkbox.superclass.initEvents.call(this);
31414         // has no events...
31415        
31416     },
31417
31418
31419     getResizeEl : function(){
31420         return this.wrap;
31421     },
31422
31423     getPositionEl : function(){
31424         return this.wrap;
31425     },
31426
31427     // private
31428     onRender : function(ct, position){
31429         
31430         this.style = this.style || 'overflow: hidden; border:1px solid #c3daf9;';
31431         var style = this.style;
31432         delete this.style;
31433         
31434         Roo.form.GridField.superclass.onRender.call(this, ct, position);
31435         this.wrap = this.el.wrap({cls: ''}); // not sure why ive done thsi...
31436         this.viewEl = this.wrap.createChild({ tag: 'div' });
31437         if (style) {
31438             this.viewEl.applyStyles(style);
31439         }
31440         if (this.width) {
31441             this.viewEl.setWidth(this.width);
31442         }
31443         if (this.height) {
31444             this.viewEl.setHeight(this.height);
31445         }
31446         //if(this.inputValue !== undefined){
31447         //this.setValue(this.value);
31448         
31449         
31450         this.grid = new Roo.grid[this.xgrid.xtype](this.viewEl, this.xgrid);
31451         
31452         
31453         this.grid.render();
31454         this.grid.getDataSource().on('remove', this.refreshValue, this);
31455         this.grid.getDataSource().on('update', this.refreshValue, this);
31456         this.grid.on('afteredit', this.refreshValue, this);
31457  
31458     },
31459      
31460     
31461     /**
31462      * Sets the value of the item. 
31463      * @param {String} either an object  or a string..
31464      */
31465     setValue : function(v){
31466         //this.value = v;
31467         v = v || []; // empty set..
31468         // this does not seem smart - it really only affects memoryproxy grids..
31469         if (this.grid && this.grid.getDataSource() && typeof(v) != 'undefined') {
31470             var ds = this.grid.getDataSource();
31471             // assumes a json reader..
31472             var data = {}
31473             data[ds.reader.meta.root ] =  typeof(v) == 'string' ? Roo.decode(v) : v;
31474             ds.loadData( data);
31475         }
31476         // clear selection so it does not get stale.
31477         if (this.grid.sm) { 
31478             this.grid.sm.clearSelections();
31479         }
31480         
31481         Roo.form.GridField.superclass.setValue.call(this, v);
31482         this.refreshValue();
31483         // should load data in the grid really....
31484     },
31485     
31486     // private
31487     refreshValue: function() {
31488          var val = [];
31489         this.grid.getDataSource().each(function(r) {
31490             val.push(r.data);
31491         });
31492         this.el.dom.value = Roo.encode(val);
31493     }
31494     
31495      
31496     
31497     
31498 });/*
31499  * Based on:
31500  * Ext JS Library 1.1.1
31501  * Copyright(c) 2006-2007, Ext JS, LLC.
31502  *
31503  * Originally Released Under LGPL - original licence link has changed is not relivant.
31504  *
31505  * Fork - LGPL
31506  * <script type="text/javascript">
31507  */
31508 /**
31509  * @class Roo.form.DisplayField
31510  * @extends Roo.form.Field
31511  * A generic Field to display non-editable data.
31512  * @cfg {Boolean} closable (true|false) default false
31513  * @constructor
31514  * Creates a new Display Field item.
31515  * @param {Object} config Configuration options
31516  */
31517 Roo.form.DisplayField = function(config){
31518     Roo.form.DisplayField.superclass.constructor.call(this, config);
31519     
31520     this.addEvents({
31521         /**
31522          * @event close
31523          * Fires after the click the close btn
31524              * @param {Roo.form.DisplayField} this
31525              */
31526         close : true
31527     });
31528 };
31529
31530 Roo.extend(Roo.form.DisplayField, Roo.form.TextField,  {
31531     inputType:      'hidden',
31532     allowBlank:     true,
31533     readOnly:         true,
31534     
31535  
31536     /**
31537      * @cfg {String} focusClass The CSS class to use when the checkbox receives focus (defaults to undefined)
31538      */
31539     focusClass : undefined,
31540     /**
31541      * @cfg {String} fieldClass The default CSS class for the checkbox (defaults to "x-form-field")
31542      */
31543     fieldClass: 'x-form-field',
31544     
31545      /**
31546      * @cfg {Function} valueRenderer The renderer for the field (so you can reformat output). should return raw HTML
31547      */
31548     valueRenderer: undefined,
31549     
31550     width: 100,
31551     /**
31552      * @cfg {String/Object} autoCreate A DomHelper element spec, or true for a default element spec (defaults to
31553      * {tag: "input", type: "checkbox", autocomplete: "off"})
31554      */
31555      
31556  //   defaultAutoCreate : { tag: 'input', type: 'hidden', autocomplete: 'off'},
31557  
31558     closable : false,
31559     
31560     onResize : function(){
31561         Roo.form.DisplayField.superclass.onResize.apply(this, arguments);
31562         
31563     },
31564
31565     initEvents : function(){
31566         // Roo.form.Checkbox.superclass.initEvents.call(this);
31567         // has no events...
31568         
31569         if(this.closable){
31570             this.closeEl.on('click', this.onClose, this);
31571         }
31572        
31573     },
31574
31575
31576     getResizeEl : function(){
31577         return this.wrap;
31578     },
31579
31580     getPositionEl : function(){
31581         return this.wrap;
31582     },
31583
31584     // private
31585     onRender : function(ct, position){
31586         
31587         Roo.form.DisplayField.superclass.onRender.call(this, ct, position);
31588         //if(this.inputValue !== undefined){
31589         this.wrap = this.el.wrap();
31590         
31591         this.viewEl = this.wrap.createChild({ tag: 'div', cls: 'x-form-displayfield'});
31592         
31593         if(this.closable){
31594             this.closeEl = this.wrap.createChild({ tag: 'div', cls: 'x-dlg-close'});
31595         }
31596         
31597         if (this.bodyStyle) {
31598             this.viewEl.applyStyles(this.bodyStyle);
31599         }
31600         //this.viewEl.setStyle('padding', '2px');
31601         
31602         this.setValue(this.value);
31603         
31604     },
31605 /*
31606     // private
31607     initValue : Roo.emptyFn,
31608
31609   */
31610
31611         // private
31612     onClick : function(){
31613         
31614     },
31615
31616     /**
31617      * Sets the checked state of the checkbox.
31618      * @param {Boolean/String} checked True, 'true', '1', or 'on' to check the checkbox, any other value will uncheck it.
31619      */
31620     setValue : function(v){
31621         this.value = v;
31622         var html = this.valueRenderer ?  this.valueRenderer(v) : String.format('{0}', v);
31623         // this might be called before we have a dom element..
31624         if (!this.viewEl) {
31625             return;
31626         }
31627         this.viewEl.dom.innerHTML = html;
31628         Roo.form.DisplayField.superclass.setValue.call(this, v);
31629
31630     },
31631     
31632     onClose : function(e)
31633     {
31634         e.preventDefault();
31635         
31636         this.fireEvent('close', this);
31637     }
31638 });/*
31639  * 
31640  * Licence- LGPL
31641  * 
31642  */
31643
31644 /**
31645  * @class Roo.form.DayPicker
31646  * @extends Roo.form.Field
31647  * A Day picker show [M] [T] [W] ....
31648  * @constructor
31649  * Creates a new Day Picker
31650  * @param {Object} config Configuration options
31651  */
31652 Roo.form.DayPicker= function(config){
31653     Roo.form.DayPicker.superclass.constructor.call(this, config);
31654      
31655 };
31656
31657 Roo.extend(Roo.form.DayPicker, Roo.form.Field,  {
31658     /**
31659      * @cfg {String} focusClass The CSS class to use when the checkbox receives focus (defaults to undefined)
31660      */
31661     focusClass : undefined,
31662     /**
31663      * @cfg {String} fieldClass The default CSS class for the checkbox (defaults to "x-form-field")
31664      */
31665     fieldClass: "x-form-field",
31666    
31667     /**
31668      * @cfg {String/Object} autoCreate A DomHelper element spec, or true for a default element spec (defaults to
31669      * {tag: "input", type: "checkbox", autocomplete: "off"})
31670      */
31671     defaultAutoCreate : { tag: "input", type: 'hidden', autocomplete: "new-password"},
31672     
31673    
31674     actionMode : 'viewEl', 
31675     //
31676     // private
31677  
31678     inputType : 'hidden',
31679     
31680      
31681     inputElement: false, // real input element?
31682     basedOn: false, // ????
31683     
31684     isFormField: true, // not sure where this is needed!!!!
31685
31686     onResize : function(){
31687         Roo.form.Checkbox.superclass.onResize.apply(this, arguments);
31688         if(!this.boxLabel){
31689             this.el.alignTo(this.wrap, 'c-c');
31690         }
31691     },
31692
31693     initEvents : function(){
31694         Roo.form.Checkbox.superclass.initEvents.call(this);
31695         this.el.on("click", this.onClick,  this);
31696         this.el.on("change", this.onClick,  this);
31697     },
31698
31699
31700     getResizeEl : function(){
31701         return this.wrap;
31702     },
31703
31704     getPositionEl : function(){
31705         return this.wrap;
31706     },
31707
31708     
31709     // private
31710     onRender : function(ct, position){
31711         Roo.form.Checkbox.superclass.onRender.call(this, ct, position);
31712        
31713         this.wrap = this.el.wrap({cls: 'x-form-daypick-item '});
31714         
31715         var r1 = '<table><tr>';
31716         var r2 = '<tr class="x-form-daypick-icons">';
31717         for (var i=0; i < 7; i++) {
31718             r1+= '<td><div>' + Date.dayNames[i].substring(0,3) + '</div></td>';
31719             r2+= '<td><img class="x-menu-item-icon" src="' + Roo.BLANK_IMAGE_URL  +'"></td>';
31720         }
31721         
31722         var viewEl = this.wrap.createChild( r1 + '</tr>' + r2 + '</tr></table>');
31723         viewEl.select('img').on('click', this.onClick, this);
31724         this.viewEl = viewEl;   
31725         
31726         
31727         // this will not work on Chrome!!!
31728         this.el.on('DOMAttrModified', this.setFromHidden,  this); //ff
31729         this.el.on('propertychange', this.setFromHidden,  this);  //ie
31730         
31731         
31732           
31733
31734     },
31735
31736     // private
31737     initValue : Roo.emptyFn,
31738
31739     /**
31740      * Returns the checked state of the checkbox.
31741      * @return {Boolean} True if checked, else false
31742      */
31743     getValue : function(){
31744         return this.el.dom.value;
31745         
31746     },
31747
31748         // private
31749     onClick : function(e){ 
31750         //this.setChecked(!this.checked);
31751         Roo.get(e.target).toggleClass('x-menu-item-checked');
31752         this.refreshValue();
31753         //if(this.el.dom.checked != this.checked){
31754         //    this.setValue(this.el.dom.checked);
31755        // }
31756     },
31757     
31758     // private
31759     refreshValue : function()
31760     {
31761         var val = '';
31762         this.viewEl.select('img',true).each(function(e,i,n)  {
31763             val += e.is(".x-menu-item-checked") ? String(n) : '';
31764         });
31765         this.setValue(val, true);
31766     },
31767
31768     /**
31769      * Sets the checked state of the checkbox.
31770      * On is always based on a string comparison between inputValue and the param.
31771      * @param {Boolean/String} value - the value to set 
31772      * @param {Boolean/String} suppressEvent - whether to suppress the checkchange event.
31773      */
31774     setValue : function(v,suppressEvent){
31775         if (!this.el.dom) {
31776             return;
31777         }
31778         var old = this.el.dom.value ;
31779         this.el.dom.value = v;
31780         if (suppressEvent) {
31781             return ;
31782         }
31783          
31784         // update display..
31785         this.viewEl.select('img',true).each(function(e,i,n)  {
31786             
31787             var on = e.is(".x-menu-item-checked");
31788             var newv = v.indexOf(String(n)) > -1;
31789             if (on != newv) {
31790                 e.toggleClass('x-menu-item-checked');
31791             }
31792             
31793         });
31794         
31795         
31796         this.fireEvent('change', this, v, old);
31797         
31798         
31799     },
31800    
31801     // handle setting of hidden value by some other method!!?!?
31802     setFromHidden: function()
31803     {
31804         if(!this.el){
31805             return;
31806         }
31807         //console.log("SET FROM HIDDEN");
31808         //alert('setFrom hidden');
31809         this.setValue(this.el.dom.value);
31810     },
31811     
31812     onDestroy : function()
31813     {
31814         if(this.viewEl){
31815             Roo.get(this.viewEl).remove();
31816         }
31817          
31818         Roo.form.DayPicker.superclass.onDestroy.call(this);
31819     }
31820
31821 });/*
31822  * RooJS Library 1.1.1
31823  * Copyright(c) 2008-2011  Alan Knowles
31824  *
31825  * License - LGPL
31826  */
31827  
31828
31829 /**
31830  * @class Roo.form.ComboCheck
31831  * @extends Roo.form.ComboBox
31832  * A combobox for multiple select items.
31833  *
31834  * FIXME - could do with a reset button..
31835  * 
31836  * @constructor
31837  * Create a new ComboCheck
31838  * @param {Object} config Configuration options
31839  */
31840 Roo.form.ComboCheck = function(config){
31841     Roo.form.ComboCheck.superclass.constructor.call(this, config);
31842     // should verify some data...
31843     // like
31844     // hiddenName = required..
31845     // displayField = required
31846     // valudField == required
31847     var req= [ 'hiddenName', 'displayField', 'valueField' ];
31848     var _t = this;
31849     Roo.each(req, function(e) {
31850         if ((typeof(_t[e]) == 'undefined' ) || !_t[e].length) {
31851             throw "Roo.form.ComboCheck : missing value for: " + e;
31852         }
31853     });
31854     
31855     
31856 };
31857
31858 Roo.extend(Roo.form.ComboCheck, Roo.form.ComboBox, {
31859      
31860      
31861     editable : false,
31862      
31863     selectedClass: 'x-menu-item-checked', 
31864     
31865     // private
31866     onRender : function(ct, position){
31867         var _t = this;
31868         
31869         
31870         
31871         if(!this.tpl){
31872             var cls = 'x-combo-list';
31873
31874             
31875             this.tpl =  new Roo.Template({
31876                 html :  '<div class="'+cls+'-item x-menu-check-item">' +
31877                    '<img class="x-menu-item-icon" style="margin: 0px;" src="' + Roo.BLANK_IMAGE_URL + '">' + 
31878                    '<span>{' + this.displayField + '}</span>' +
31879                     '</div>' 
31880                 
31881             });
31882         }
31883  
31884         
31885         Roo.form.ComboCheck.superclass.onRender.call(this, ct, position);
31886         this.view.singleSelect = false;
31887         this.view.multiSelect = true;
31888         this.view.toggleSelect = true;
31889         this.pageTb.add(new Roo.Toolbar.Fill(), {
31890             
31891             text: 'Done',
31892             handler: function()
31893             {
31894                 _t.collapse();
31895             }
31896         });
31897     },
31898     
31899     onViewOver : function(e, t){
31900         // do nothing...
31901         return;
31902         
31903     },
31904     
31905     onViewClick : function(doFocus,index){
31906         return;
31907         
31908     },
31909     select: function () {
31910         //Roo.log("SELECT CALLED");
31911     },
31912      
31913     selectByValue : function(xv, scrollIntoView){
31914         var ar = this.getValueArray();
31915         var sels = [];
31916         
31917         Roo.each(ar, function(v) {
31918             if(v === undefined || v === null){
31919                 return;
31920             }
31921             var r = this.findRecord(this.valueField, v);
31922             if(r){
31923                 sels.push(this.store.indexOf(r))
31924                 
31925             }
31926         },this);
31927         this.view.select(sels);
31928         return false;
31929     },
31930     
31931     
31932     
31933     onSelect : function(record, index){
31934        // Roo.log("onselect Called");
31935        // this is only called by the clear button now..
31936         this.view.clearSelections();
31937         this.setValue('[]');
31938         if (this.value != this.valueBefore) {
31939             this.fireEvent('change', this, this.value, this.valueBefore);
31940             this.valueBefore = this.value;
31941         }
31942     },
31943     getValueArray : function()
31944     {
31945         var ar = [] ;
31946         
31947         try {
31948             //Roo.log(this.value);
31949             if (typeof(this.value) == 'undefined') {
31950                 return [];
31951             }
31952             var ar = Roo.decode(this.value);
31953             return  ar instanceof Array ? ar : []; //?? valid?
31954             
31955         } catch(e) {
31956             Roo.log(e + "\nRoo.form.ComboCheck:getValueArray  invalid data:" + this.getValue());
31957             return [];
31958         }
31959          
31960     },
31961     expand : function ()
31962     {
31963         
31964         Roo.form.ComboCheck.superclass.expand.call(this);
31965         this.valueBefore = typeof(this.value) == 'undefined' ? '' : this.value;
31966         //this.valueBefore = typeof(this.valueBefore) == 'undefined' ? '' : this.valueBefore;
31967         
31968
31969     },
31970     
31971     collapse : function(){
31972         Roo.form.ComboCheck.superclass.collapse.call(this);
31973         var sl = this.view.getSelectedIndexes();
31974         var st = this.store;
31975         var nv = [];
31976         var tv = [];
31977         var r;
31978         Roo.each(sl, function(i) {
31979             r = st.getAt(i);
31980             nv.push(r.get(this.valueField));
31981         },this);
31982         this.setValue(Roo.encode(nv));
31983         if (this.value != this.valueBefore) {
31984
31985             this.fireEvent('change', this, this.value, this.valueBefore);
31986             this.valueBefore = this.value;
31987         }
31988         
31989     },
31990     
31991     setValue : function(v){
31992         // Roo.log(v);
31993         this.value = v;
31994         
31995         var vals = this.getValueArray();
31996         var tv = [];
31997         Roo.each(vals, function(k) {
31998             var r = this.findRecord(this.valueField, k);
31999             if(r){
32000                 tv.push(r.data[this.displayField]);
32001             }else if(this.valueNotFoundText !== undefined){
32002                 tv.push( this.valueNotFoundText );
32003             }
32004         },this);
32005        // Roo.log(tv);
32006         
32007         Roo.form.ComboBox.superclass.setValue.call(this, tv.join(', '));
32008         this.hiddenField.value = v;
32009         this.value = v;
32010     }
32011     
32012 });/*
32013  * Based on:
32014  * Ext JS Library 1.1.1
32015  * Copyright(c) 2006-2007, Ext JS, LLC.
32016  *
32017  * Originally Released Under LGPL - original licence link has changed is not relivant.
32018  *
32019  * Fork - LGPL
32020  * <script type="text/javascript">
32021  */
32022  
32023 /**
32024  * @class Roo.form.Signature
32025  * @extends Roo.form.Field
32026  * Signature field.  
32027  * @constructor
32028  * 
32029  * @param {Object} config Configuration options
32030  */
32031
32032 Roo.form.Signature = function(config){
32033     Roo.form.Signature.superclass.constructor.call(this, config);
32034     
32035     this.addEvents({// not in used??
32036          /**
32037          * @event confirm
32038          * Fires when the 'confirm' icon is pressed (add a listener to enable add button)
32039              * @param {Roo.form.Signature} combo This combo box
32040              */
32041         'confirm' : true,
32042         /**
32043          * @event reset
32044          * Fires when the 'edit' icon is pressed (add a listener to enable add button)
32045              * @param {Roo.form.ComboBox} combo This combo box
32046              * @param {Roo.data.Record|false} record The data record returned from the underlying store (or false on nothing selected)
32047              */
32048         'reset' : true
32049     });
32050 };
32051
32052 Roo.extend(Roo.form.Signature, Roo.form.Field,  {
32053     /**
32054      * @cfg {Object} labels Label to use when rendering a form.
32055      * defaults to 
32056      * labels : { 
32057      *      clear : "Clear",
32058      *      confirm : "Confirm"
32059      *  }
32060      */
32061     labels : { 
32062         clear : "Clear",
32063         confirm : "Confirm"
32064     },
32065     /**
32066      * @cfg {Number} width The signature panel width (defaults to 300)
32067      */
32068     width: 300,
32069     /**
32070      * @cfg {Number} height The signature panel height (defaults to 100)
32071      */
32072     height : 100,
32073     /**
32074      * @cfg {Boolean} allowBlank False to validate that the value length > 0 (defaults to false)
32075      */
32076     allowBlank : false,
32077     
32078     //private
32079     // {Object} signPanel The signature SVG panel element (defaults to {})
32080     signPanel : {},
32081     // {Boolean} isMouseDown False to validate that the mouse down event (defaults to false)
32082     isMouseDown : false,
32083     // {Boolean} isConfirmed validate the signature is confirmed or not for submitting form (defaults to false)
32084     isConfirmed : false,
32085     // {String} signatureTmp SVG mapping string (defaults to empty string)
32086     signatureTmp : '',
32087     
32088     
32089     defaultAutoCreate : { // modified by initCompnoent..
32090         tag: "input",
32091         type:"hidden"
32092     },
32093
32094     // private
32095     onRender : function(ct, position){
32096         
32097         Roo.form.Signature.superclass.onRender.call(this, ct, position);
32098         
32099         this.wrap = this.el.wrap({
32100             cls:'x-form-signature-wrap', style : 'width: ' + this.width + 'px', cn:{cls:'x-form-signature'}
32101         });
32102         
32103         this.createToolbar(this);
32104         this.signPanel = this.wrap.createChild({
32105                 tag: 'div',
32106                 style: 'width: ' + this.width + 'px; height: ' + this.height + 'px; border: 0;'
32107             }, this.el
32108         );
32109             
32110         this.svgID = Roo.id();
32111         this.svgEl = this.signPanel.createChild({
32112               xmlns : 'http://www.w3.org/2000/svg',
32113               tag : 'svg',
32114               id : this.svgID + "-svg",
32115               width: this.width,
32116               height: this.height,
32117               viewBox: '0 0 '+this.width+' '+this.height,
32118               cn : [
32119                 {
32120                     tag: "rect",
32121                     id: this.svgID + "-svg-r",
32122                     width: this.width,
32123                     height: this.height,
32124                     fill: "#ffa"
32125                 },
32126                 {
32127                     tag: "line",
32128                     id: this.svgID + "-svg-l",
32129                     x1: "0", // start
32130                     y1: (this.height*0.8), // start set the line in 80% of height
32131                     x2: this.width, // end
32132                     y2: (this.height*0.8), // end set the line in 80% of height
32133                     'stroke': "#666",
32134                     'stroke-width': "1",
32135                     'stroke-dasharray': "3",
32136                     'shape-rendering': "crispEdges",
32137                     'pointer-events': "none"
32138                 },
32139                 {
32140                     tag: "path",
32141                     id: this.svgID + "-svg-p",
32142                     'stroke': "navy",
32143                     'stroke-width': "3",
32144                     'fill': "none",
32145                     'pointer-events': 'none'
32146                 }
32147               ]
32148         });
32149         this.createSVG();
32150         this.svgBox = this.svgEl.dom.getScreenCTM();
32151     },
32152     createSVG : function(){ 
32153         var svg = this.signPanel;
32154         var r = svg.select('#'+ this.svgID + '-svg-r', true).first().dom;
32155         var t = this;
32156
32157         r.addEventListener('mousedown', function(e) { return t.down(e); }, false);
32158         r.addEventListener('mousemove', function(e) { return t.move(e); }, false);
32159         r.addEventListener('mouseup', function(e) { return t.up(e); }, false);
32160         r.addEventListener('mouseout', function(e) { return t.up(e); }, false);
32161         r.addEventListener('touchstart', function(e) { return t.down(e); }, false);
32162         r.addEventListener('touchmove', function(e) { return t.move(e); }, false);
32163         r.addEventListener('touchend', function(e) { return t.up(e); }, false);
32164         
32165     },
32166     isTouchEvent : function(e){
32167         return e.type.match(/^touch/);
32168     },
32169     getCoords : function (e) {
32170         var pt    = this.svgEl.dom.createSVGPoint();
32171         pt.x = e.clientX; 
32172         pt.y = e.clientY;
32173         if (this.isTouchEvent(e)) {
32174             pt.x =  e.targetTouches[0].clientX;
32175             pt.y = e.targetTouches[0].clientY;
32176         }
32177         var a = this.svgEl.dom.getScreenCTM();
32178         var b = a.inverse();
32179         var mx = pt.matrixTransform(b);
32180         return mx.x + ',' + mx.y;
32181     },
32182     //mouse event headler 
32183     down : function (e) {
32184         this.signatureTmp += 'M' + this.getCoords(e) + ' ';
32185         this.signPanel.select('#'+ this.svgID + '-svg-p', true).first().attr('d', this.signatureTmp);
32186         
32187         this.isMouseDown = true;
32188         
32189         e.preventDefault();
32190     },
32191     move : function (e) {
32192         if (this.isMouseDown) {
32193             this.signatureTmp += 'L' + this.getCoords(e) + ' ';
32194             this.signPanel.select('#'+ this.svgID + '-svg-p', true).first().attr( 'd', this.signatureTmp);
32195         }
32196         
32197         e.preventDefault();
32198     },
32199     up : function (e) {
32200         this.isMouseDown = false;
32201         var sp = this.signatureTmp.split(' ');
32202         
32203         if(sp.length > 1){
32204             if(!sp[sp.length-2].match(/^L/)){
32205                 sp.pop();
32206                 sp.pop();
32207                 sp.push("");
32208                 this.signatureTmp = sp.join(" ");
32209             }
32210         }
32211         if(this.getValue() != this.signatureTmp){
32212             this.signPanel.select('#'+ this.svgID + '-svg-r', true).first().attr('fill', '#ffa');
32213             this.isConfirmed = false;
32214         }
32215         e.preventDefault();
32216     },
32217     
32218     /**
32219      * Protected method that will not generally be called directly. It
32220      * is called when the editor creates its toolbar. Override this method if you need to
32221      * add custom toolbar buttons.
32222      * @param {HtmlEditor} editor
32223      */
32224     createToolbar : function(editor){
32225          function btn(id, toggle, handler){
32226             var xid = fid + '-'+ id ;
32227             return {
32228                 id : xid,
32229                 cmd : id,
32230                 cls : 'x-btn-icon x-edit-'+id,
32231                 enableToggle:toggle !== false,
32232                 scope: editor, // was editor...
32233                 handler:handler||editor.relayBtnCmd,
32234                 clickEvent:'mousedown',
32235                 tooltip: etb.buttonTips[id] || undefined, ///tips ???
32236                 tabIndex:-1
32237             };
32238         }
32239         
32240         
32241         var tb = new Roo.Toolbar(editor.wrap.dom.firstChild);
32242         this.tb = tb;
32243         this.tb.add(
32244            {
32245                 cls : ' x-signature-btn x-signature-'+id,
32246                 scope: editor, // was editor...
32247                 handler: this.reset,
32248                 clickEvent:'mousedown',
32249                 text: this.labels.clear
32250             },
32251             {
32252                  xtype : 'Fill',
32253                  xns: Roo.Toolbar
32254             }, 
32255             {
32256                 cls : '  x-signature-btn x-signature-'+id,
32257                 scope: editor, // was editor...
32258                 handler: this.confirmHandler,
32259                 clickEvent:'mousedown',
32260                 text: this.labels.confirm
32261             }
32262         );
32263     
32264     },
32265     //public
32266     /**
32267      * when user is clicked confirm then show this image.....
32268      * 
32269      * @return {String} Image Data URI
32270      */
32271     getImageDataURI : function(){
32272         var svg = this.svgEl.dom.parentNode.innerHTML;
32273         var src = 'data:image/svg+xml;base64,'+window.btoa(svg);
32274         return src; 
32275     },
32276     /**
32277      * 
32278      * @return {Boolean} this.isConfirmed
32279      */
32280     getConfirmed : function(){
32281         return this.isConfirmed;
32282     },
32283     /**
32284      * 
32285      * @return {Number} this.width
32286      */
32287     getWidth : function(){
32288         return this.width;
32289     },
32290     /**
32291      * 
32292      * @return {Number} this.height
32293      */
32294     getHeight : function(){
32295         return this.height;
32296     },
32297     // private
32298     getSignature : function(){
32299         return this.signatureTmp;
32300     },
32301     // private
32302     reset : function(){
32303         this.signatureTmp = '';
32304         this.signPanel.select('#'+ this.svgID + '-svg-r', true).first().attr('fill', '#ffa');
32305         this.signPanel.select('#'+ this.svgID + '-svg-p', true).first().attr( 'd', '');
32306         this.isConfirmed = false;
32307         Roo.form.Signature.superclass.reset.call(this);
32308     },
32309     setSignature : function(s){
32310         this.signatureTmp = s;
32311         this.signPanel.select('#'+ this.svgID + '-svg-r', true).first().attr('fill', '#ffa');
32312         this.signPanel.select('#'+ this.svgID + '-svg-p', true).first().attr( 'd', s);
32313         this.setValue(s);
32314         this.isConfirmed = false;
32315         Roo.form.Signature.superclass.reset.call(this);
32316     }, 
32317     test : function(){
32318 //        Roo.log(this.signPanel.dom.contentWindow.up())
32319     },
32320     //private
32321     setConfirmed : function(){
32322         
32323         
32324         
32325 //        Roo.log(Roo.get(this.signPanel.dom.contentWindow.r).attr('fill', '#cfc'));
32326     },
32327     // private
32328     confirmHandler : function(){
32329         if(!this.getSignature()){
32330             return;
32331         }
32332         
32333         this.signPanel.select('#'+ this.svgID + '-svg-r', true).first().attr('fill', '#cfc');
32334         this.setValue(this.getSignature());
32335         this.isConfirmed = true;
32336         
32337         this.fireEvent('confirm', this);
32338     },
32339     // private
32340     // Subclasses should provide the validation implementation by overriding this
32341     validateValue : function(value){
32342         if(this.allowBlank){
32343             return true;
32344         }
32345         
32346         if(this.isConfirmed){
32347             return true;
32348         }
32349         return false;
32350     }
32351 });/*
32352  * Based on:
32353  * Ext JS Library 1.1.1
32354  * Copyright(c) 2006-2007, Ext JS, LLC.
32355  *
32356  * Originally Released Under LGPL - original licence link has changed is not relivant.
32357  *
32358  * Fork - LGPL
32359  * <script type="text/javascript">
32360  */
32361  
32362
32363 /**
32364  * @class Roo.form.ComboBox
32365  * @extends Roo.form.TriggerField
32366  * A combobox control with support for autocomplete, remote-loading, paging and many other features.
32367  * @constructor
32368  * Create a new ComboBox.
32369  * @param {Object} config Configuration options
32370  */
32371 Roo.form.Select = function(config){
32372     Roo.form.Select.superclass.constructor.call(this, config);
32373      
32374 };
32375
32376 Roo.extend(Roo.form.Select , Roo.form.ComboBox, {
32377     /**
32378      * @cfg {String/HTMLElement/Element} transform The id, DOM node or element of an existing select to convert to a ComboBox
32379      */
32380     /**
32381      * @cfg {Boolean} lazyRender True to prevent the ComboBox from rendering until requested (should always be used when
32382      * rendering into an Roo.Editor, defaults to false)
32383      */
32384     /**
32385      * @cfg {Boolean/Object} autoCreate A DomHelper element spec, or true for a default element spec (defaults to:
32386      * {tag: "input", type: "text", size: "24", autocomplete: "off"})
32387      */
32388     /**
32389      * @cfg {Roo.data.Store} store The data store to which this combo is bound (defaults to undefined)
32390      */
32391     /**
32392      * @cfg {String} title If supplied, a header element is created containing this text and added into the top of
32393      * the dropdown list (defaults to undefined, with no header element)
32394      */
32395
32396      /**
32397      * @cfg {String/Roo.Template} tpl The template to use to render the output
32398      */
32399      
32400     // private
32401     defaultAutoCreate : {tag: "select"  },
32402     /**
32403      * @cfg {Number} listWidth The width in pixels of the dropdown list (defaults to the width of the ComboBox field)
32404      */
32405     listWidth: undefined,
32406     /**
32407      * @cfg {String} displayField The underlying data field name to bind to this CombBox (defaults to undefined if
32408      * mode = 'remote' or 'text' if mode = 'local')
32409      */
32410     displayField: undefined,
32411     /**
32412      * @cfg {String} valueField The underlying data value name to bind to this CombBox (defaults to undefined if
32413      * mode = 'remote' or 'value' if mode = 'local'). 
32414      * Note: use of a valueField requires the user make a selection
32415      * in order for a value to be mapped.
32416      */
32417     valueField: undefined,
32418     
32419     
32420     /**
32421      * @cfg {String} hiddenName If specified, a hidden form field with this name is dynamically generated to store the
32422      * field's data value (defaults to the underlying DOM element's name)
32423      */
32424     hiddenName: undefined,
32425     /**
32426      * @cfg {String} listClass CSS class to apply to the dropdown list element (defaults to '')
32427      */
32428     listClass: '',
32429     /**
32430      * @cfg {String} selectedClass CSS class to apply to the selected item in the dropdown list (defaults to 'x-combo-selected')
32431      */
32432     selectedClass: 'x-combo-selected',
32433     /**
32434      * @cfg {String} triggerClass An additional CSS class used to style the trigger button.  The trigger will always get the
32435      * class 'x-form-trigger' and triggerClass will be <b>appended</b> if specified (defaults to 'x-form-arrow-trigger'
32436      * which displays a downward arrow icon).
32437      */
32438     triggerClass : 'x-form-arrow-trigger',
32439     /**
32440      * @cfg {Boolean/String} shadow True or "sides" for the default effect, "frame" for 4-way shadow, and "drop" for bottom-right
32441      */
32442     shadow:'sides',
32443     /**
32444      * @cfg {String} listAlign A valid anchor position value. See {@link Roo.Element#alignTo} for details on supported
32445      * anchor positions (defaults to 'tl-bl')
32446      */
32447     listAlign: 'tl-bl?',
32448     /**
32449      * @cfg {Number} maxHeight The maximum height in pixels of the dropdown list before scrollbars are shown (defaults to 300)
32450      */
32451     maxHeight: 300,
32452     /**
32453      * @cfg {String} triggerAction The action to execute when the trigger field is activated.  Use 'all' to run the
32454      * query specified by the allQuery config option (defaults to 'query')
32455      */
32456     triggerAction: 'query',
32457     /**
32458      * @cfg {Number} minChars The minimum number of characters the user must type before autocomplete and typeahead activate
32459      * (defaults to 4, does not apply if editable = false)
32460      */
32461     minChars : 4,
32462     /**
32463      * @cfg {Boolean} typeAhead True to populate and autoselect the remainder of the text being typed after a configurable
32464      * delay (typeAheadDelay) if it matches a known value (defaults to false)
32465      */
32466     typeAhead: false,
32467     /**
32468      * @cfg {Number} queryDelay The length of time in milliseconds to delay between the start of typing and sending the
32469      * query to filter the dropdown list (defaults to 500 if mode = 'remote' or 10 if mode = 'local')
32470      */
32471     queryDelay: 500,
32472     /**
32473      * @cfg {Number} pageSize If greater than 0, a paging toolbar is displayed in the footer of the dropdown list and the
32474      * filter queries will execute with page start and limit parameters.  Only applies when mode = 'remote' (defaults to 0)
32475      */
32476     pageSize: 0,
32477     /**
32478      * @cfg {Boolean} selectOnFocus True to select any existing text in the field immediately on focus.  Only applies
32479      * when editable = true (defaults to false)
32480      */
32481     selectOnFocus:false,
32482     /**
32483      * @cfg {String} queryParam Name of the query as it will be passed on the querystring (defaults to 'query')
32484      */
32485     queryParam: 'query',
32486     /**
32487      * @cfg {String} loadingText The text to display in the dropdown list while data is loading.  Only applies
32488      * when mode = 'remote' (defaults to 'Loading...')
32489      */
32490     loadingText: 'Loading...',
32491     /**
32492      * @cfg {Boolean} resizable True to add a resize handle to the bottom of the dropdown list (defaults to false)
32493      */
32494     resizable: false,
32495     /**
32496      * @cfg {Number} handleHeight The height in pixels of the dropdown list resize handle if resizable = true (defaults to 8)
32497      */
32498     handleHeight : 8,
32499     /**
32500      * @cfg {Boolean} editable False to prevent the user from typing text directly into the field, just like a
32501      * traditional select (defaults to true)
32502      */
32503     editable: true,
32504     /**
32505      * @cfg {String} allQuery The text query to send to the server to return all records for the list with no filtering (defaults to '')
32506      */
32507     allQuery: '',
32508     /**
32509      * @cfg {String} mode Set to 'local' if the ComboBox loads local data (defaults to 'remote' which loads from the server)
32510      */
32511     mode: 'remote',
32512     /**
32513      * @cfg {Number} minListWidth The minimum width of the dropdown list in pixels (defaults to 70, will be ignored if
32514      * listWidth has a higher value)
32515      */
32516     minListWidth : 70,
32517     /**
32518      * @cfg {Boolean} forceSelection True to restrict the selected value to one of the values in the list, false to
32519      * allow the user to set arbitrary text into the field (defaults to false)
32520      */
32521     forceSelection:false,
32522     /**
32523      * @cfg {Number} typeAheadDelay The length of time in milliseconds to wait until the typeahead text is displayed
32524      * if typeAhead = true (defaults to 250)
32525      */
32526     typeAheadDelay : 250,
32527     /**
32528      * @cfg {String} valueNotFoundText When using a name/value combo, if the value passed to setValue is not found in
32529      * the store, valueNotFoundText will be displayed as the field text if defined (defaults to undefined)
32530      */
32531     valueNotFoundText : undefined,
32532     
32533     /**
32534      * @cfg {String} defaultValue The value displayed after loading the store.
32535      */
32536     defaultValue: '',
32537     
32538     /**
32539      * @cfg {Boolean} blockFocus Prevents all focus calls, so it can work with things like HTML edtor bar
32540      */
32541     blockFocus : false,
32542     
32543     /**
32544      * @cfg {Boolean} disableClear Disable showing of clear button.
32545      */
32546     disableClear : false,
32547     /**
32548      * @cfg {Boolean} alwaysQuery  Disable caching of results, and always send query
32549      */
32550     alwaysQuery : false,
32551     
32552     //private
32553     addicon : false,
32554     editicon: false,
32555     
32556     // element that contains real text value.. (when hidden is used..)
32557      
32558     // private
32559     onRender : function(ct, position){
32560         Roo.form.Field.prototype.onRender.call(this, ct, position);
32561         
32562         if(this.store){
32563             this.store.on('beforeload', this.onBeforeLoad, this);
32564             this.store.on('load', this.onLoad, this);
32565             this.store.on('loadexception', this.onLoadException, this);
32566             this.store.load({});
32567         }
32568         
32569         
32570         
32571     },
32572
32573     // private
32574     initEvents : function(){
32575         //Roo.form.ComboBox.superclass.initEvents.call(this);
32576  
32577     },
32578
32579     onDestroy : function(){
32580        
32581         if(this.store){
32582             this.store.un('beforeload', this.onBeforeLoad, this);
32583             this.store.un('load', this.onLoad, this);
32584             this.store.un('loadexception', this.onLoadException, this);
32585         }
32586         //Roo.form.ComboBox.superclass.onDestroy.call(this);
32587     },
32588
32589     // private
32590     fireKey : function(e){
32591         if(e.isNavKeyPress() && !this.list.isVisible()){
32592             this.fireEvent("specialkey", this, e);
32593         }
32594     },
32595
32596     // private
32597     onResize: function(w, h){
32598         
32599         return; 
32600     
32601         
32602     },
32603
32604     /**
32605      * Allow or prevent the user from directly editing the field text.  If false is passed,
32606      * the user will only be able to select from the items defined in the dropdown list.  This method
32607      * is the runtime equivalent of setting the 'editable' config option at config time.
32608      * @param {Boolean} value True to allow the user to directly edit the field text
32609      */
32610     setEditable : function(value){
32611          
32612     },
32613
32614     // private
32615     onBeforeLoad : function(){
32616         
32617         Roo.log("Select before load");
32618         return;
32619     
32620         this.innerList.update(this.loadingText ?
32621                '<div class="loading-indicator">'+this.loadingText+'</div>' : '');
32622         //this.restrictHeight();
32623         this.selectedIndex = -1;
32624     },
32625
32626     // private
32627     onLoad : function(){
32628
32629     
32630         var dom = this.el.dom;
32631         dom.innerHTML = '';
32632          var od = dom.ownerDocument;
32633          
32634         if (this.emptyText) {
32635             var op = od.createElement('option');
32636             op.setAttribute('value', '');
32637             op.innerHTML = String.format('{0}', this.emptyText);
32638             dom.appendChild(op);
32639         }
32640         if(this.store.getCount() > 0){
32641            
32642             var vf = this.valueField;
32643             var df = this.displayField;
32644             this.store.data.each(function(r) {
32645                 // which colmsn to use... testing - cdoe / title..
32646                 var op = od.createElement('option');
32647                 op.setAttribute('value', r.data[vf]);
32648                 op.innerHTML = String.format('{0}', r.data[df]);
32649                 dom.appendChild(op);
32650             });
32651             if (typeof(this.defaultValue != 'undefined')) {
32652                 this.setValue(this.defaultValue);
32653             }
32654             
32655              
32656         }else{
32657             //this.onEmptyResults();
32658         }
32659         //this.el.focus();
32660     },
32661     // private
32662     onLoadException : function()
32663     {
32664         dom.innerHTML = '';
32665             
32666         Roo.log("Select on load exception");
32667         return;
32668     
32669         this.collapse();
32670         Roo.log(this.store.reader.jsonData);
32671         if (this.store && typeof(this.store.reader.jsonData.errorMsg) != 'undefined') {
32672             Roo.MessageBox.alert("Error loading",this.store.reader.jsonData.errorMsg);
32673         }
32674         
32675         
32676     },
32677     // private
32678     onTypeAhead : function(){
32679          
32680     },
32681
32682     // private
32683     onSelect : function(record, index){
32684         Roo.log('on select?');
32685         return;
32686         if(this.fireEvent('beforeselect', this, record, index) !== false){
32687             this.setFromData(index > -1 ? record.data : false);
32688             this.collapse();
32689             this.fireEvent('select', this, record, index);
32690         }
32691     },
32692
32693     /**
32694      * Returns the currently selected field value or empty string if no value is set.
32695      * @return {String} value The selected value
32696      */
32697     getValue : function(){
32698         var dom = this.el.dom;
32699         this.value = dom.options[dom.selectedIndex].value;
32700         return this.value;
32701         
32702     },
32703
32704     /**
32705      * Clears any text/value currently set in the field
32706      */
32707     clearValue : function(){
32708         this.value = '';
32709         this.el.dom.selectedIndex = this.emptyText ? 0 : -1;
32710         
32711     },
32712
32713     /**
32714      * Sets the specified value into the field.  If the value finds a match, the corresponding record text
32715      * will be displayed in the field.  If the value does not match the data value of an existing item,
32716      * and the valueNotFoundText config option is defined, it will be displayed as the default field text.
32717      * Otherwise the field will be blank (although the value will still be set).
32718      * @param {String} value The value to match
32719      */
32720     setValue : function(v){
32721         var d = this.el.dom;
32722         for (var i =0; i < d.options.length;i++) {
32723             if (v == d.options[i].value) {
32724                 d.selectedIndex = i;
32725                 this.value = v;
32726                 return;
32727             }
32728         }
32729         this.clearValue();
32730     },
32731     /**
32732      * @property {Object} the last set data for the element
32733      */
32734     
32735     lastData : false,
32736     /**
32737      * Sets the value of the field based on a object which is related to the record format for the store.
32738      * @param {Object} value the value to set as. or false on reset?
32739      */
32740     setFromData : function(o){
32741         Roo.log('setfrom data?');
32742          
32743         
32744         
32745     },
32746     // private
32747     reset : function(){
32748         this.clearValue();
32749     },
32750     // private
32751     findRecord : function(prop, value){
32752         
32753         return false;
32754     
32755         var record;
32756         if(this.store.getCount() > 0){
32757             this.store.each(function(r){
32758                 if(r.data[prop] == value){
32759                     record = r;
32760                     return false;
32761                 }
32762                 return true;
32763             });
32764         }
32765         return record;
32766     },
32767     
32768     getName: function()
32769     {
32770         // returns hidden if it's set..
32771         if (!this.rendered) {return ''};
32772         return !this.hiddenName && this.el.dom.name  ? this.el.dom.name : (this.hiddenName || '');
32773         
32774     },
32775      
32776
32777     
32778
32779     // private
32780     onEmptyResults : function(){
32781         Roo.log('empty results');
32782         //this.collapse();
32783     },
32784
32785     /**
32786      * Returns true if the dropdown list is expanded, else false.
32787      */
32788     isExpanded : function(){
32789         return false;
32790     },
32791
32792     /**
32793      * Select an item in the dropdown list by its data value. This function does NOT cause the select event to fire.
32794      * The store must be loaded and the list expanded for this function to work, otherwise use setValue.
32795      * @param {String} value The data value of the item to select
32796      * @param {Boolean} scrollIntoView False to prevent the dropdown list from autoscrolling to display the
32797      * selected item if it is not currently in view (defaults to true)
32798      * @return {Boolean} True if the value matched an item in the list, else false
32799      */
32800     selectByValue : function(v, scrollIntoView){
32801         Roo.log('select By Value');
32802         return false;
32803     
32804         if(v !== undefined && v !== null){
32805             var r = this.findRecord(this.valueField || this.displayField, v);
32806             if(r){
32807                 this.select(this.store.indexOf(r), scrollIntoView);
32808                 return true;
32809             }
32810         }
32811         return false;
32812     },
32813
32814     /**
32815      * Select an item in the dropdown list by its numeric index in the list. This function does NOT cause the select event to fire.
32816      * The store must be loaded and the list expanded for this function to work, otherwise use setValue.
32817      * @param {Number} index The zero-based index of the list item to select
32818      * @param {Boolean} scrollIntoView False to prevent the dropdown list from autoscrolling to display the
32819      * selected item if it is not currently in view (defaults to true)
32820      */
32821     select : function(index, scrollIntoView){
32822         Roo.log('select ');
32823         return  ;
32824         
32825         this.selectedIndex = index;
32826         this.view.select(index);
32827         if(scrollIntoView !== false){
32828             var el = this.view.getNode(index);
32829             if(el){
32830                 this.innerList.scrollChildIntoView(el, false);
32831             }
32832         }
32833     },
32834
32835       
32836
32837     // private
32838     validateBlur : function(){
32839         
32840         return;
32841         
32842     },
32843
32844     // private
32845     initQuery : function(){
32846         this.doQuery(this.getRawValue());
32847     },
32848
32849     // private
32850     doForce : function(){
32851         if(this.el.dom.value.length > 0){
32852             this.el.dom.value =
32853                 this.lastSelectionText === undefined ? '' : this.lastSelectionText;
32854              
32855         }
32856     },
32857
32858     /**
32859      * Execute a query to filter the dropdown list.  Fires the beforequery event prior to performing the
32860      * query allowing the query action to be canceled if needed.
32861      * @param {String} query The SQL query to execute
32862      * @param {Boolean} forceAll True to force the query to execute even if there are currently fewer characters
32863      * in the field than the minimum specified by the minChars config option.  It also clears any filter previously
32864      * saved in the current store (defaults to false)
32865      */
32866     doQuery : function(q, forceAll){
32867         
32868         Roo.log('doQuery?');
32869         if(q === undefined || q === null){
32870             q = '';
32871         }
32872         var qe = {
32873             query: q,
32874             forceAll: forceAll,
32875             combo: this,
32876             cancel:false
32877         };
32878         if(this.fireEvent('beforequery', qe)===false || qe.cancel){
32879             return false;
32880         }
32881         q = qe.query;
32882         forceAll = qe.forceAll;
32883         if(forceAll === true || (q.length >= this.minChars)){
32884             if(this.lastQuery != q || this.alwaysQuery){
32885                 this.lastQuery = q;
32886                 if(this.mode == 'local'){
32887                     this.selectedIndex = -1;
32888                     if(forceAll){
32889                         this.store.clearFilter();
32890                     }else{
32891                         this.store.filter(this.displayField, q);
32892                     }
32893                     this.onLoad();
32894                 }else{
32895                     this.store.baseParams[this.queryParam] = q;
32896                     this.store.load({
32897                         params: this.getParams(q)
32898                     });
32899                     this.expand();
32900                 }
32901             }else{
32902                 this.selectedIndex = -1;
32903                 this.onLoad();   
32904             }
32905         }
32906     },
32907
32908     // private
32909     getParams : function(q){
32910         var p = {};
32911         //p[this.queryParam] = q;
32912         if(this.pageSize){
32913             p.start = 0;
32914             p.limit = this.pageSize;
32915         }
32916         return p;
32917     },
32918
32919     /**
32920      * Hides the dropdown list if it is currently expanded. Fires the 'collapse' event on completion.
32921      */
32922     collapse : function(){
32923         
32924     },
32925
32926     // private
32927     collapseIf : function(e){
32928         
32929     },
32930
32931     /**
32932      * Expands the dropdown list if it is currently hidden. Fires the 'expand' event on completion.
32933      */
32934     expand : function(){
32935         
32936     } ,
32937
32938     // private
32939      
32940
32941     /** 
32942     * @cfg {Boolean} grow 
32943     * @hide 
32944     */
32945     /** 
32946     * @cfg {Number} growMin 
32947     * @hide 
32948     */
32949     /** 
32950     * @cfg {Number} growMax 
32951     * @hide 
32952     */
32953     /**
32954      * @hide
32955      * @method autoSize
32956      */
32957     
32958     setWidth : function()
32959     {
32960         
32961     },
32962     getResizeEl : function(){
32963         return this.el;
32964     }
32965 });//<script type="text/javasscript">
32966  
32967
32968 /**
32969  * @class Roo.DDView
32970  * A DnD enabled version of Roo.View.
32971  * @param {Element/String} container The Element in which to create the View.
32972  * @param {String} tpl The template string used to create the markup for each element of the View
32973  * @param {Object} config The configuration properties. These include all the config options of
32974  * {@link Roo.View} plus some specific to this class.<br>
32975  * <p>
32976  * Drag/drop is implemented by adding {@link Roo.data.Record}s to the target DDView. If copying is
32977  * not being performed, the original {@link Roo.data.Record} is removed from the source DDView.<br>
32978  * <p>
32979  * The following extra CSS rules are needed to provide insertion point highlighting:<pre><code>
32980 .x-view-drag-insert-above {
32981         border-top:1px dotted #3366cc;
32982 }
32983 .x-view-drag-insert-below {
32984         border-bottom:1px dotted #3366cc;
32985 }
32986 </code></pre>
32987  * 
32988  */
32989  
32990 Roo.DDView = function(container, tpl, config) {
32991     Roo.DDView.superclass.constructor.apply(this, arguments);
32992     this.getEl().setStyle("outline", "0px none");
32993     this.getEl().unselectable();
32994     if (this.dragGroup) {
32995         this.setDraggable(this.dragGroup.split(","));
32996     }
32997     if (this.dropGroup) {
32998         this.setDroppable(this.dropGroup.split(","));
32999     }
33000     if (this.deletable) {
33001         this.setDeletable();
33002     }
33003     this.isDirtyFlag = false;
33004         this.addEvents({
33005                 "drop" : true
33006         });
33007 };
33008
33009 Roo.extend(Roo.DDView, Roo.View, {
33010 /**     @cfg {String/Array} dragGroup The ddgroup name(s) for the View's DragZone. */
33011 /**     @cfg {String/Array} dropGroup The ddgroup name(s) for the View's DropZone. */
33012 /**     @cfg {Boolean} copy Causes drag operations to copy nodes rather than move. */
33013 /**     @cfg {Boolean} allowCopy Causes ctrl/drag operations to copy nodes rather than move. */
33014
33015         isFormField: true,
33016
33017         reset: Roo.emptyFn,
33018         
33019         clearInvalid: Roo.form.Field.prototype.clearInvalid,
33020
33021         validate: function() {
33022                 return true;
33023         },
33024         
33025         destroy: function() {
33026                 this.purgeListeners();
33027                 this.getEl.removeAllListeners();
33028                 this.getEl().remove();
33029                 if (this.dragZone) {
33030                         if (this.dragZone.destroy) {
33031                                 this.dragZone.destroy();
33032                         }
33033                 }
33034                 if (this.dropZone) {
33035                         if (this.dropZone.destroy) {
33036                                 this.dropZone.destroy();
33037                         }
33038                 }
33039         },
33040
33041 /**     Allows this class to be an Roo.form.Field so it can be found using {@link Roo.form.BasicForm#findField}. */
33042         getName: function() {
33043                 return this.name;
33044         },
33045
33046 /**     Loads the View from a JSON string representing the Records to put into the Store. */
33047         setValue: function(v) {
33048                 if (!this.store) {
33049                         throw "DDView.setValue(). DDView must be constructed with a valid Store";
33050                 }
33051                 var data = {};
33052                 data[this.store.reader.meta.root] = v ? [].concat(v) : [];
33053                 this.store.proxy = new Roo.data.MemoryProxy(data);
33054                 this.store.load();
33055         },
33056
33057 /**     @return {String} a parenthesised list of the ids of the Records in the View. */
33058         getValue: function() {
33059                 var result = '(';
33060                 this.store.each(function(rec) {
33061                         result += rec.id + ',';
33062                 });
33063                 return result.substr(0, result.length - 1) + ')';
33064         },
33065         
33066         getIds: function() {
33067                 var i = 0, result = new Array(this.store.getCount());
33068                 this.store.each(function(rec) {
33069                         result[i++] = rec.id;
33070                 });
33071                 return result;
33072         },
33073         
33074         isDirty: function() {
33075                 return this.isDirtyFlag;
33076         },
33077
33078 /**
33079  *      Part of the Roo.dd.DropZone interface. If no target node is found, the
33080  *      whole Element becomes the target, and this causes the drop gesture to append.
33081  */
33082     getTargetFromEvent : function(e) {
33083                 var target = e.getTarget();
33084                 while ((target !== null) && (target.parentNode != this.el.dom)) {
33085                 target = target.parentNode;
33086                 }
33087                 if (!target) {
33088                         target = this.el.dom.lastChild || this.el.dom;
33089                 }
33090                 return target;
33091     },
33092
33093 /**
33094  *      Create the drag data which consists of an object which has the property "ddel" as
33095  *      the drag proxy element. 
33096  */
33097     getDragData : function(e) {
33098         var target = this.findItemFromChild(e.getTarget());
33099                 if(target) {
33100                         this.handleSelection(e);
33101                         var selNodes = this.getSelectedNodes();
33102             var dragData = {
33103                 source: this,
33104                 copy: this.copy || (this.allowCopy && e.ctrlKey),
33105                 nodes: selNodes,
33106                 records: []
33107                         };
33108                         var selectedIndices = this.getSelectedIndexes();
33109                         for (var i = 0; i < selectedIndices.length; i++) {
33110                                 dragData.records.push(this.store.getAt(selectedIndices[i]));
33111                         }
33112                         if (selNodes.length == 1) {
33113                                 dragData.ddel = target.cloneNode(true); // the div element
33114                         } else {
33115                                 var div = document.createElement('div'); // create the multi element drag "ghost"
33116                                 div.className = 'multi-proxy';
33117                                 for (var i = 0, len = selNodes.length; i < len; i++) {
33118                                         div.appendChild(selNodes[i].cloneNode(true));
33119                                 }
33120                                 dragData.ddel = div;
33121                         }
33122             //console.log(dragData)
33123             //console.log(dragData.ddel.innerHTML)
33124                         return dragData;
33125                 }
33126         //console.log('nodragData')
33127                 return false;
33128     },
33129     
33130 /**     Specify to which ddGroup items in this DDView may be dragged. */
33131     setDraggable: function(ddGroup) {
33132         if (ddGroup instanceof Array) {
33133                 Roo.each(ddGroup, this.setDraggable, this);
33134                 return;
33135         }
33136         if (this.dragZone) {
33137                 this.dragZone.addToGroup(ddGroup);
33138         } else {
33139                         this.dragZone = new Roo.dd.DragZone(this.getEl(), {
33140                                 containerScroll: true,
33141                                 ddGroup: ddGroup 
33142
33143                         });
33144 //                      Draggability implies selection. DragZone's mousedown selects the element.
33145                         if (!this.multiSelect) { this.singleSelect = true; }
33146
33147 //                      Wire the DragZone's handlers up to methods in *this*
33148                         this.dragZone.getDragData = this.getDragData.createDelegate(this);
33149                 }
33150     },
33151
33152 /**     Specify from which ddGroup this DDView accepts drops. */
33153     setDroppable: function(ddGroup) {
33154         if (ddGroup instanceof Array) {
33155                 Roo.each(ddGroup, this.setDroppable, this);
33156                 return;
33157         }
33158         if (this.dropZone) {
33159                 this.dropZone.addToGroup(ddGroup);
33160         } else {
33161                         this.dropZone = new Roo.dd.DropZone(this.getEl(), {
33162                                 containerScroll: true,
33163                                 ddGroup: ddGroup
33164                         });
33165
33166 //                      Wire the DropZone's handlers up to methods in *this*
33167                         this.dropZone.getTargetFromEvent = this.getTargetFromEvent.createDelegate(this);
33168                         this.dropZone.onNodeEnter = this.onNodeEnter.createDelegate(this);
33169                         this.dropZone.onNodeOver = this.onNodeOver.createDelegate(this);
33170                         this.dropZone.onNodeOut = this.onNodeOut.createDelegate(this);
33171                         this.dropZone.onNodeDrop = this.onNodeDrop.createDelegate(this);
33172                 }
33173     },
33174
33175 /**     Decide whether to drop above or below a View node. */
33176     getDropPoint : function(e, n, dd){
33177         if (n == this.el.dom) { return "above"; }
33178                 var t = Roo.lib.Dom.getY(n), b = t + n.offsetHeight;
33179                 var c = t + (b - t) / 2;
33180                 var y = Roo.lib.Event.getPageY(e);
33181                 if(y <= c) {
33182                         return "above";
33183                 }else{
33184                         return "below";
33185                 }
33186     },
33187
33188     onNodeEnter : function(n, dd, e, data){
33189                 return false;
33190     },
33191     
33192     onNodeOver : function(n, dd, e, data){
33193                 var pt = this.getDropPoint(e, n, dd);
33194                 // set the insert point style on the target node
33195                 var dragElClass = this.dropNotAllowed;
33196                 if (pt) {
33197                         var targetElClass;
33198                         if (pt == "above"){
33199                                 dragElClass = n.previousSibling ? "x-tree-drop-ok-between" : "x-tree-drop-ok-above";
33200                                 targetElClass = "x-view-drag-insert-above";
33201                         } else {
33202                                 dragElClass = n.nextSibling ? "x-tree-drop-ok-between" : "x-tree-drop-ok-below";
33203                                 targetElClass = "x-view-drag-insert-below";
33204                         }
33205                         if (this.lastInsertClass != targetElClass){
33206                                 Roo.fly(n).replaceClass(this.lastInsertClass, targetElClass);
33207                                 this.lastInsertClass = targetElClass;
33208                         }
33209                 }
33210                 return dragElClass;
33211         },
33212
33213     onNodeOut : function(n, dd, e, data){
33214                 this.removeDropIndicators(n);
33215     },
33216
33217     onNodeDrop : function(n, dd, e, data){
33218         if (this.fireEvent("drop", this, n, dd, e, data) === false) {
33219                 return false;
33220         }
33221         var pt = this.getDropPoint(e, n, dd);
33222                 var insertAt = (n == this.el.dom) ? this.nodes.length : n.nodeIndex;
33223                 if (pt == "below") { insertAt++; }
33224                 for (var i = 0; i < data.records.length; i++) {
33225                         var r = data.records[i];
33226                         var dup = this.store.getById(r.id);
33227                         if (dup && (dd != this.dragZone)) {
33228                                 Roo.fly(this.getNode(this.store.indexOf(dup))).frame("red", 1);
33229                         } else {
33230                                 if (data.copy) {
33231                                         this.store.insert(insertAt++, r.copy());
33232                                 } else {
33233                                         data.source.isDirtyFlag = true;
33234                                         r.store.remove(r);
33235                                         this.store.insert(insertAt++, r);
33236                                 }
33237                                 this.isDirtyFlag = true;
33238                         }
33239                 }
33240                 this.dragZone.cachedTarget = null;
33241                 return true;
33242     },
33243
33244     removeDropIndicators : function(n){
33245                 if(n){
33246                         Roo.fly(n).removeClass([
33247                                 "x-view-drag-insert-above",
33248                                 "x-view-drag-insert-below"]);
33249                         this.lastInsertClass = "_noclass";
33250                 }
33251     },
33252
33253 /**
33254  *      Utility method. Add a delete option to the DDView's context menu.
33255  *      @param {String} imageUrl The URL of the "delete" icon image.
33256  */
33257         setDeletable: function(imageUrl) {
33258                 if (!this.singleSelect && !this.multiSelect) {
33259                         this.singleSelect = true;
33260                 }
33261                 var c = this.getContextMenu();
33262                 this.contextMenu.on("itemclick", function(item) {
33263                         switch (item.id) {
33264                                 case "delete":
33265                                         this.remove(this.getSelectedIndexes());
33266                                         break;
33267                         }
33268                 }, this);
33269                 this.contextMenu.add({
33270                         icon: imageUrl,
33271                         id: "delete",
33272                         text: 'Delete'
33273                 });
33274         },
33275         
33276 /**     Return the context menu for this DDView. */
33277         getContextMenu: function() {
33278                 if (!this.contextMenu) {
33279 //                      Create the View's context menu
33280                         this.contextMenu = new Roo.menu.Menu({
33281                                 id: this.id + "-contextmenu"
33282                         });
33283                         this.el.on("contextmenu", this.showContextMenu, this);
33284                 }
33285                 return this.contextMenu;
33286         },
33287         
33288         disableContextMenu: function() {
33289                 if (this.contextMenu) {
33290                         this.el.un("contextmenu", this.showContextMenu, this);
33291                 }
33292         },
33293
33294         showContextMenu: function(e, item) {
33295         item = this.findItemFromChild(e.getTarget());
33296                 if (item) {
33297                         e.stopEvent();
33298                         this.select(this.getNode(item), this.multiSelect && e.ctrlKey, true);
33299                         this.contextMenu.showAt(e.getXY());
33300             }
33301     },
33302
33303 /**
33304  *      Remove {@link Roo.data.Record}s at the specified indices.
33305  *      @param {Array/Number} selectedIndices The index (or Array of indices) of Records to remove.
33306  */
33307     remove: function(selectedIndices) {
33308                 selectedIndices = [].concat(selectedIndices);
33309                 for (var i = 0; i < selectedIndices.length; i++) {
33310                         var rec = this.store.getAt(selectedIndices[i]);
33311                         this.store.remove(rec);
33312                 }
33313     },
33314
33315 /**
33316  *      Double click fires the event, but also, if this is draggable, and there is only one other
33317  *      related DropZone, it transfers the selected node.
33318  */
33319     onDblClick : function(e){
33320         var item = this.findItemFromChild(e.getTarget());
33321         if(item){
33322             if (this.fireEvent("dblclick", this, this.indexOf(item), item, e) === false) {
33323                 return false;
33324             }
33325             if (this.dragGroup) {
33326                     var targets = Roo.dd.DragDropMgr.getRelated(this.dragZone, true);
33327                     while (targets.indexOf(this.dropZone) > -1) {
33328                             targets.remove(this.dropZone);
33329                                 }
33330                     if (targets.length == 1) {
33331                                         this.dragZone.cachedTarget = null;
33332                         var el = Roo.get(targets[0].getEl());
33333                         var box = el.getBox(true);
33334                         targets[0].onNodeDrop(el.dom, {
33335                                 target: el.dom,
33336                                 xy: [box.x, box.y + box.height - 1]
33337                         }, null, this.getDragData(e));
33338                     }
33339                 }
33340         }
33341     },
33342     
33343     handleSelection: function(e) {
33344                 this.dragZone.cachedTarget = null;
33345         var item = this.findItemFromChild(e.getTarget());
33346         if (!item) {
33347                 this.clearSelections(true);
33348                 return;
33349         }
33350                 if (item && (this.multiSelect || this.singleSelect)){
33351                         if(this.multiSelect && e.shiftKey && (!e.ctrlKey) && this.lastSelection){
33352                                 this.select(this.getNodes(this.indexOf(this.lastSelection), item.nodeIndex), false);
33353                         }else if (this.isSelected(this.getNode(item)) && e.ctrlKey){
33354                                 this.unselect(item);
33355                         } else {
33356                                 this.select(item, this.multiSelect && e.ctrlKey);
33357                                 this.lastSelection = item;
33358                         }
33359                 }
33360     },
33361
33362     onItemClick : function(item, index, e){
33363                 if(this.fireEvent("beforeclick", this, index, item, e) === false){
33364                         return false;
33365                 }
33366                 return true;
33367     },
33368
33369     unselect : function(nodeInfo, suppressEvent){
33370                 var node = this.getNode(nodeInfo);
33371                 if(node && this.isSelected(node)){
33372                         if(this.fireEvent("beforeselect", this, node, this.selections) !== false){
33373                                 Roo.fly(node).removeClass(this.selectedClass);
33374                                 this.selections.remove(node);
33375                                 if(!suppressEvent){
33376                                         this.fireEvent("selectionchange", this, this.selections);
33377                                 }
33378                         }
33379                 }
33380     }
33381 });
33382 /*
33383  * Based on:
33384  * Ext JS Library 1.1.1
33385  * Copyright(c) 2006-2007, Ext JS, LLC.
33386  *
33387  * Originally Released Under LGPL - original licence link has changed is not relivant.
33388  *
33389  * Fork - LGPL
33390  * <script type="text/javascript">
33391  */
33392  
33393 /**
33394  * @class Roo.LayoutManager
33395  * @extends Roo.util.Observable
33396  * Base class for layout managers.
33397  */
33398 Roo.LayoutManager = function(container, config){
33399     Roo.LayoutManager.superclass.constructor.call(this);
33400     this.el = Roo.get(container);
33401     // ie scrollbar fix
33402     if(this.el.dom == document.body && Roo.isIE && !config.allowScroll){
33403         document.body.scroll = "no";
33404     }else if(this.el.dom != document.body && this.el.getStyle('position') == 'static'){
33405         this.el.position('relative');
33406     }
33407     this.id = this.el.id;
33408     this.el.addClass("x-layout-container");
33409     /** false to disable window resize monitoring @type Boolean */
33410     this.monitorWindowResize = true;
33411     this.regions = {};
33412     this.addEvents({
33413         /**
33414          * @event layout
33415          * Fires when a layout is performed. 
33416          * @param {Roo.LayoutManager} this
33417          */
33418         "layout" : true,
33419         /**
33420          * @event regionresized
33421          * Fires when the user resizes a region. 
33422          * @param {Roo.LayoutRegion} region The resized region
33423          * @param {Number} newSize The new size (width for east/west, height for north/south)
33424          */
33425         "regionresized" : true,
33426         /**
33427          * @event regioncollapsed
33428          * Fires when a region is collapsed. 
33429          * @param {Roo.LayoutRegion} region The collapsed region
33430          */
33431         "regioncollapsed" : true,
33432         /**
33433          * @event regionexpanded
33434          * Fires when a region is expanded.  
33435          * @param {Roo.LayoutRegion} region The expanded region
33436          */
33437         "regionexpanded" : true
33438     });
33439     this.updating = false;
33440     Roo.EventManager.onWindowResize(this.onWindowResize, this, true);
33441 };
33442
33443 Roo.extend(Roo.LayoutManager, Roo.util.Observable, {
33444     /**
33445      * Returns true if this layout is currently being updated
33446      * @return {Boolean}
33447      */
33448     isUpdating : function(){
33449         return this.updating; 
33450     },
33451     
33452     /**
33453      * Suspend the LayoutManager from doing auto-layouts while
33454      * making multiple add or remove calls
33455      */
33456     beginUpdate : function(){
33457         this.updating = true;    
33458     },
33459     
33460     /**
33461      * Restore auto-layouts and optionally disable the manager from performing a layout
33462      * @param {Boolean} noLayout true to disable a layout update 
33463      */
33464     endUpdate : function(noLayout){
33465         this.updating = false;
33466         if(!noLayout){
33467             this.layout();
33468         }    
33469     },
33470     
33471     layout: function(){
33472         
33473     },
33474     
33475     onRegionResized : function(region, newSize){
33476         this.fireEvent("regionresized", region, newSize);
33477         this.layout();
33478     },
33479     
33480     onRegionCollapsed : function(region){
33481         this.fireEvent("regioncollapsed", region);
33482     },
33483     
33484     onRegionExpanded : function(region){
33485         this.fireEvent("regionexpanded", region);
33486     },
33487         
33488     /**
33489      * Returns the size of the current view. This method normalizes document.body and element embedded layouts and
33490      * performs box-model adjustments.
33491      * @return {Object} The size as an object {width: (the width), height: (the height)}
33492      */
33493     getViewSize : function(){
33494         var size;
33495         if(this.el.dom != document.body){
33496             size = this.el.getSize();
33497         }else{
33498             size = {width: Roo.lib.Dom.getViewWidth(), height: Roo.lib.Dom.getViewHeight()};
33499         }
33500         size.width -= this.el.getBorderWidth("lr")-this.el.getPadding("lr");
33501         size.height -= this.el.getBorderWidth("tb")-this.el.getPadding("tb");
33502         return size;
33503     },
33504     
33505     /**
33506      * Returns the Element this layout is bound to.
33507      * @return {Roo.Element}
33508      */
33509     getEl : function(){
33510         return this.el;
33511     },
33512     
33513     /**
33514      * Returns the specified region.
33515      * @param {String} target The region key ('center', 'north', 'south', 'east' or 'west')
33516      * @return {Roo.LayoutRegion}
33517      */
33518     getRegion : function(target){
33519         return this.regions[target.toLowerCase()];
33520     },
33521     
33522     onWindowResize : function(){
33523         if(this.monitorWindowResize){
33524             this.layout();
33525         }
33526     }
33527 });/*
33528  * Based on:
33529  * Ext JS Library 1.1.1
33530  * Copyright(c) 2006-2007, Ext JS, LLC.
33531  *
33532  * Originally Released Under LGPL - original licence link has changed is not relivant.
33533  *
33534  * Fork - LGPL
33535  * <script type="text/javascript">
33536  */
33537 /**
33538  * @class Roo.BorderLayout
33539  * @extends Roo.LayoutManager
33540  * @children Roo.ContentPanel
33541  * This class represents a common layout manager used in desktop applications. For screenshots and more details,
33542  * please see: <br><br>
33543  * <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>
33544  * <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>
33545  * Example:
33546  <pre><code>
33547  var layout = new Roo.BorderLayout(document.body, {
33548     north: {
33549         initialSize: 25,
33550         titlebar: false
33551     },
33552     west: {
33553         split:true,
33554         initialSize: 200,
33555         minSize: 175,
33556         maxSize: 400,
33557         titlebar: true,
33558         collapsible: true
33559     },
33560     east: {
33561         split:true,
33562         initialSize: 202,
33563         minSize: 175,
33564         maxSize: 400,
33565         titlebar: true,
33566         collapsible: true
33567     },
33568     south: {
33569         split:true,
33570         initialSize: 100,
33571         minSize: 100,
33572         maxSize: 200,
33573         titlebar: true,
33574         collapsible: true
33575     },
33576     center: {
33577         titlebar: true,
33578         autoScroll:true,
33579         resizeTabs: true,
33580         minTabWidth: 50,
33581         preferredTabWidth: 150
33582     }
33583 });
33584
33585 // shorthand
33586 var CP = Roo.ContentPanel;
33587
33588 layout.beginUpdate();
33589 layout.add("north", new CP("north", "North"));
33590 layout.add("south", new CP("south", {title: "South", closable: true}));
33591 layout.add("west", new CP("west", {title: "West"}));
33592 layout.add("east", new CP("autoTabs", {title: "Auto Tabs", closable: true}));
33593 layout.add("center", new CP("center1", {title: "Close Me", closable: true}));
33594 layout.add("center", new CP("center2", {title: "Center Panel", closable: false}));
33595 layout.getRegion("center").showPanel("center1");
33596 layout.endUpdate();
33597 </code></pre>
33598
33599 <b>The container the layout is rendered into can be either the body element or any other element.
33600 If it is not the body element, the container needs to either be an absolute positioned element,
33601 or you will need to add "position:relative" to the css of the container.  You will also need to specify
33602 the container size if it is not the body element.</b>
33603
33604 * @constructor
33605 * Create a new BorderLayout
33606 * @param {String/HTMLElement/Element} container The container this layout is bound to
33607 * @param {Object} config Configuration options
33608  */
33609 Roo.BorderLayout = function(container, config){
33610     config = config || {};
33611     Roo.BorderLayout.superclass.constructor.call(this, container, config);
33612     this.factory = config.factory || Roo.BorderLayout.RegionFactory;
33613     for(var i = 0, len = this.factory.validRegions.length; i < len; i++) {
33614         var target = this.factory.validRegions[i];
33615         if(config[target]){
33616             this.addRegion(target, config[target]);
33617         }
33618     }
33619 };
33620
33621 Roo.extend(Roo.BorderLayout, Roo.LayoutManager, {
33622         
33623         /**
33624          * @cfg {Roo.LayoutRegion} east
33625          */
33626         /**
33627          * @cfg {Roo.LayoutRegion} west
33628          */
33629         /**
33630          * @cfg {Roo.LayoutRegion} north
33631          */
33632         /**
33633          * @cfg {Roo.LayoutRegion} south
33634          */
33635         /**
33636          * @cfg {Roo.LayoutRegion} center
33637          */
33638     /**
33639      * Creates and adds a new region if it doesn't already exist.
33640      * @param {String} target The target region key (north, south, east, west or center).
33641      * @param {Object} config The regions config object
33642      * @return {BorderLayoutRegion} The new region
33643      */
33644     addRegion : function(target, config){
33645         if(!this.regions[target]){
33646             var r = this.factory.create(target, this, config);
33647             this.bindRegion(target, r);
33648         }
33649         return this.regions[target];
33650     },
33651
33652     // private (kinda)
33653     bindRegion : function(name, r){
33654         this.regions[name] = r;
33655         r.on("visibilitychange", this.layout, this);
33656         r.on("paneladded", this.layout, this);
33657         r.on("panelremoved", this.layout, this);
33658         r.on("invalidated", this.layout, this);
33659         r.on("resized", this.onRegionResized, this);
33660         r.on("collapsed", this.onRegionCollapsed, this);
33661         r.on("expanded", this.onRegionExpanded, this);
33662     },
33663
33664     /**
33665      * Performs a layout update.
33666      */
33667     layout : function(){
33668         if(this.updating) {
33669             return;
33670         }
33671         var size = this.getViewSize();
33672         var w = size.width;
33673         var h = size.height;
33674         var centerW = w;
33675         var centerH = h;
33676         var centerY = 0;
33677         var centerX = 0;
33678         //var x = 0, y = 0;
33679
33680         var rs = this.regions;
33681         var north = rs["north"];
33682         var south = rs["south"]; 
33683         var west = rs["west"];
33684         var east = rs["east"];
33685         var center = rs["center"];
33686         //if(this.hideOnLayout){ // not supported anymore
33687             //c.el.setStyle("display", "none");
33688         //}
33689         if(north && north.isVisible()){
33690             var b = north.getBox();
33691             var m = north.getMargins();
33692             b.width = w - (m.left+m.right);
33693             b.x = m.left;
33694             b.y = m.top;
33695             centerY = b.height + b.y + m.bottom;
33696             centerH -= centerY;
33697             north.updateBox(this.safeBox(b));
33698         }
33699         if(south && south.isVisible()){
33700             var b = south.getBox();
33701             var m = south.getMargins();
33702             b.width = w - (m.left+m.right);
33703             b.x = m.left;
33704             var totalHeight = (b.height + m.top + m.bottom);
33705             b.y = h - totalHeight + m.top;
33706             centerH -= totalHeight;
33707             south.updateBox(this.safeBox(b));
33708         }
33709         if(west && west.isVisible()){
33710             var b = west.getBox();
33711             var m = west.getMargins();
33712             b.height = centerH - (m.top+m.bottom);
33713             b.x = m.left;
33714             b.y = centerY + m.top;
33715             var totalWidth = (b.width + m.left + m.right);
33716             centerX += totalWidth;
33717             centerW -= totalWidth;
33718             west.updateBox(this.safeBox(b));
33719         }
33720         if(east && east.isVisible()){
33721             var b = east.getBox();
33722             var m = east.getMargins();
33723             b.height = centerH - (m.top+m.bottom);
33724             var totalWidth = (b.width + m.left + m.right);
33725             b.x = w - totalWidth + m.left;
33726             b.y = centerY + m.top;
33727             centerW -= totalWidth;
33728             east.updateBox(this.safeBox(b));
33729         }
33730         if(center){
33731             var m = center.getMargins();
33732             var centerBox = {
33733                 x: centerX + m.left,
33734                 y: centerY + m.top,
33735                 width: centerW - (m.left+m.right),
33736                 height: centerH - (m.top+m.bottom)
33737             };
33738             //if(this.hideOnLayout){
33739                 //center.el.setStyle("display", "block");
33740             //}
33741             center.updateBox(this.safeBox(centerBox));
33742         }
33743         this.el.repaint();
33744         this.fireEvent("layout", this);
33745     },
33746
33747     // private
33748     safeBox : function(box){
33749         box.width = Math.max(0, box.width);
33750         box.height = Math.max(0, box.height);
33751         return box;
33752     },
33753
33754     /**
33755      * Adds a ContentPanel (or subclass) to this layout.
33756      * @param {String} target The target region key (north, south, east, west or center).
33757      * @param {Roo.ContentPanel} panel The panel to add
33758      * @return {Roo.ContentPanel} The added panel
33759      */
33760     add : function(target, panel){
33761          
33762         target = target.toLowerCase();
33763         return this.regions[target].add(panel);
33764     },
33765
33766     /**
33767      * Remove a ContentPanel (or subclass) to this layout.
33768      * @param {String} target The target region key (north, south, east, west or center).
33769      * @param {Number/String/Roo.ContentPanel} panel The index, id or panel to remove
33770      * @return {Roo.ContentPanel} The removed panel
33771      */
33772     remove : function(target, panel){
33773         target = target.toLowerCase();
33774         return this.regions[target].remove(panel);
33775     },
33776
33777     /**
33778      * Searches all regions for a panel with the specified id
33779      * @param {String} panelId
33780      * @return {Roo.ContentPanel} The panel or null if it wasn't found
33781      */
33782     findPanel : function(panelId){
33783         var rs = this.regions;
33784         for(var target in rs){
33785             if(typeof rs[target] != "function"){
33786                 var p = rs[target].getPanel(panelId);
33787                 if(p){
33788                     return p;
33789                 }
33790             }
33791         }
33792         return null;
33793     },
33794
33795     /**
33796      * Searches all regions for a panel with the specified id and activates (shows) it.
33797      * @param {String/ContentPanel} panelId The panels id or the panel itself
33798      * @return {Roo.ContentPanel} The shown panel or null
33799      */
33800     showPanel : function(panelId) {
33801       var rs = this.regions;
33802       for(var target in rs){
33803          var r = rs[target];
33804          if(typeof r != "function"){
33805             if(r.hasPanel(panelId)){
33806                return r.showPanel(panelId);
33807             }
33808          }
33809       }
33810       return null;
33811    },
33812
33813    /**
33814      * Restores this layout's state using Roo.state.Manager or the state provided by the passed provider.
33815      * @param {Roo.state.Provider} provider (optional) An alternate state provider
33816      */
33817     restoreState : function(provider){
33818         if(!provider){
33819             provider = Roo.state.Manager;
33820         }
33821         var sm = new Roo.LayoutStateManager();
33822         sm.init(this, provider);
33823     },
33824
33825     /**
33826      * Adds a batch of multiple ContentPanels dynamically by passing a special regions config object.  This config
33827      * object should contain properties for each region to add ContentPanels to, and each property's value should be
33828      * a valid ContentPanel config object.  Example:
33829      * <pre><code>
33830 // Create the main layout
33831 var layout = new Roo.BorderLayout('main-ct', {
33832     west: {
33833         split:true,
33834         minSize: 175,
33835         titlebar: true
33836     },
33837     center: {
33838         title:'Components'
33839     }
33840 }, 'main-ct');
33841
33842 // Create and add multiple ContentPanels at once via configs
33843 layout.batchAdd({
33844    west: {
33845        id: 'source-files',
33846        autoCreate:true,
33847        title:'Ext Source Files',
33848        autoScroll:true,
33849        fitToFrame:true
33850    },
33851    center : {
33852        el: cview,
33853        autoScroll:true,
33854        fitToFrame:true,
33855        toolbar: tb,
33856        resizeEl:'cbody'
33857    }
33858 });
33859 </code></pre>
33860      * @param {Object} regions An object containing ContentPanel configs by region name
33861      */
33862     batchAdd : function(regions){
33863         this.beginUpdate();
33864         for(var rname in regions){
33865             var lr = this.regions[rname];
33866             if(lr){
33867                 this.addTypedPanels(lr, regions[rname]);
33868             }
33869         }
33870         this.endUpdate();
33871     },
33872
33873     // private
33874     addTypedPanels : function(lr, ps){
33875         if(typeof ps == 'string'){
33876             lr.add(new Roo.ContentPanel(ps));
33877         }
33878         else if(ps instanceof Array){
33879             for(var i =0, len = ps.length; i < len; i++){
33880                 this.addTypedPanels(lr, ps[i]);
33881             }
33882         }
33883         else if(!ps.events){ // raw config?
33884             var el = ps.el;
33885             delete ps.el; // prevent conflict
33886             lr.add(new Roo.ContentPanel(el || Roo.id(), ps));
33887         }
33888         else {  // panel object assumed!
33889             lr.add(ps);
33890         }
33891     },
33892     /**
33893      * Adds a xtype elements to the layout.
33894      * <pre><code>
33895
33896 layout.addxtype({
33897        xtype : 'ContentPanel',
33898        region: 'west',
33899        items: [ .... ]
33900    }
33901 );
33902
33903 layout.addxtype({
33904         xtype : 'NestedLayoutPanel',
33905         region: 'west',
33906         layout: {
33907            center: { },
33908            west: { }   
33909         },
33910         items : [ ... list of content panels or nested layout panels.. ]
33911    }
33912 );
33913 </code></pre>
33914      * @param {Object} cfg Xtype definition of item to add.
33915      */
33916     addxtype : function(cfg)
33917     {
33918         // basically accepts a pannel...
33919         // can accept a layout region..!?!?
33920         //Roo.log('Roo.BorderLayout add ' + cfg.xtype)
33921         
33922         if (!cfg.xtype.match(/Panel$/)) {
33923             return false;
33924         }
33925         var ret = false;
33926         
33927         if (typeof(cfg.region) == 'undefined') {
33928             Roo.log("Failed to add Panel, region was not set");
33929             Roo.log(cfg);
33930             return false;
33931         }
33932         var region = cfg.region;
33933         delete cfg.region;
33934         
33935           
33936         var xitems = [];
33937         if (cfg.items) {
33938             xitems = cfg.items;
33939             delete cfg.items;
33940         }
33941         var nb = false;
33942         
33943         switch(cfg.xtype) 
33944         {
33945             case 'ContentPanel':  // ContentPanel (el, cfg)
33946             case 'ScrollPanel':  // ContentPanel (el, cfg)
33947             case 'ViewPanel': 
33948                 if(cfg.autoCreate) {
33949                     ret = new Roo[cfg.xtype](cfg); // new panel!!!!!
33950                 } else {
33951                     var el = this.el.createChild();
33952                     ret = new Roo[cfg.xtype](el, cfg); // new panel!!!!!
33953                 }
33954                 
33955                 this.add(region, ret);
33956                 break;
33957             
33958             
33959             case 'TreePanel': // our new panel!
33960                 cfg.el = this.el.createChild();
33961                 ret = new Roo[cfg.xtype](cfg); // new panel!!!!!
33962                 this.add(region, ret);
33963                 break;
33964             
33965             case 'NestedLayoutPanel': 
33966                 // create a new Layout (which is  a Border Layout...
33967                 var el = this.el.createChild();
33968                 var clayout = cfg.layout;
33969                 delete cfg.layout;
33970                 clayout.items   = clayout.items  || [];
33971                 // replace this exitems with the clayout ones..
33972                 xitems = clayout.items;
33973                  
33974                 
33975                 if (region == 'center' && this.active && this.getRegion('center').panels.length < 1) {
33976                     cfg.background = false;
33977                 }
33978                 var layout = new Roo.BorderLayout(el, clayout);
33979                 
33980                 ret = new Roo[cfg.xtype](layout, cfg); // new panel!!!!!
33981                 //console.log('adding nested layout panel '  + cfg.toSource());
33982                 this.add(region, ret);
33983                 nb = {}; /// find first...
33984                 break;
33985                 
33986             case 'GridPanel': 
33987             
33988                 // needs grid and region
33989                 
33990                 //var el = this.getRegion(region).el.createChild();
33991                 var el = this.el.createChild();
33992                 // create the grid first...
33993                 
33994                 var grid = new Roo.grid[cfg.grid.xtype](el, cfg.grid);
33995                 delete cfg.grid;
33996                 if (region == 'center' && this.active ) {
33997                     cfg.background = false;
33998                 }
33999                 ret = new Roo[cfg.xtype](grid, cfg); // new panel!!!!!
34000                 
34001                 this.add(region, ret);
34002                 if (cfg.background) {
34003                     ret.on('activate', function(gp) {
34004                         if (!gp.grid.rendered) {
34005                             gp.grid.render();
34006                         }
34007                     });
34008                 } else {
34009                     grid.render();
34010                 }
34011                 break;
34012            
34013            
34014            
34015                 
34016                 
34017                 
34018             default:
34019                 if (typeof(Roo[cfg.xtype]) != 'undefined') {
34020                     
34021                     ret = new Roo[cfg.xtype](cfg); // new panel!!!!!
34022                     this.add(region, ret);
34023                 } else {
34024                 
34025                     alert("Can not add '" + cfg.xtype + "' to BorderLayout");
34026                     return null;
34027                 }
34028                 
34029              // GridPanel (grid, cfg)
34030             
34031         }
34032         this.beginUpdate();
34033         // add children..
34034         var region = '';
34035         var abn = {};
34036         Roo.each(xitems, function(i)  {
34037             region = nb && i.region ? i.region : false;
34038             
34039             var add = ret.addxtype(i);
34040            
34041             if (region) {
34042                 nb[region] = nb[region] == undefined ? 0 : nb[region]+1;
34043                 if (!i.background) {
34044                     abn[region] = nb[region] ;
34045                 }
34046             }
34047             
34048         });
34049         this.endUpdate();
34050
34051         // make the last non-background panel active..
34052         //if (nb) { Roo.log(abn); }
34053         if (nb) {
34054             
34055             for(var r in abn) {
34056                 region = this.getRegion(r);
34057                 if (region) {
34058                     // tried using nb[r], but it does not work..
34059                      
34060                     region.showPanel(abn[r]);
34061                    
34062                 }
34063             }
34064         }
34065         return ret;
34066         
34067     }
34068 });
34069
34070 /**
34071  * Shortcut for creating a new BorderLayout object and adding one or more ContentPanels to it in a single step, handling
34072  * the beginUpdate and endUpdate calls internally.  The key to this method is the <b>panels</b> property that can be
34073  * provided with each region config, which allows you to add ContentPanel configs in addition to the region configs
34074  * during creation.  The following code is equivalent to the constructor-based example at the beginning of this class:
34075  * <pre><code>
34076 // shorthand
34077 var CP = Roo.ContentPanel;
34078
34079 var layout = Roo.BorderLayout.create({
34080     north: {
34081         initialSize: 25,
34082         titlebar: false,
34083         panels: [new CP("north", "North")]
34084     },
34085     west: {
34086         split:true,
34087         initialSize: 200,
34088         minSize: 175,
34089         maxSize: 400,
34090         titlebar: true,
34091         collapsible: true,
34092         panels: [new CP("west", {title: "West"})]
34093     },
34094     east: {
34095         split:true,
34096         initialSize: 202,
34097         minSize: 175,
34098         maxSize: 400,
34099         titlebar: true,
34100         collapsible: true,
34101         panels: [new CP("autoTabs", {title: "Auto Tabs", closable: true})]
34102     },
34103     south: {
34104         split:true,
34105         initialSize: 100,
34106         minSize: 100,
34107         maxSize: 200,
34108         titlebar: true,
34109         collapsible: true,
34110         panels: [new CP("south", {title: "South", closable: true})]
34111     },
34112     center: {
34113         titlebar: true,
34114         autoScroll:true,
34115         resizeTabs: true,
34116         minTabWidth: 50,
34117         preferredTabWidth: 150,
34118         panels: [
34119             new CP("center1", {title: "Close Me", closable: true}),
34120             new CP("center2", {title: "Center Panel", closable: false})
34121         ]
34122     }
34123 }, document.body);
34124
34125 layout.getRegion("center").showPanel("center1");
34126 </code></pre>
34127  * @param config
34128  * @param targetEl
34129  */
34130 Roo.BorderLayout.create = function(config, targetEl){
34131     var layout = new Roo.BorderLayout(targetEl || document.body, config);
34132     layout.beginUpdate();
34133     var regions = Roo.BorderLayout.RegionFactory.validRegions;
34134     for(var j = 0, jlen = regions.length; j < jlen; j++){
34135         var lr = regions[j];
34136         if(layout.regions[lr] && config[lr].panels){
34137             var r = layout.regions[lr];
34138             var ps = config[lr].panels;
34139             layout.addTypedPanels(r, ps);
34140         }
34141     }
34142     layout.endUpdate();
34143     return layout;
34144 };
34145
34146 // private
34147 Roo.BorderLayout.RegionFactory = {
34148     // private
34149     validRegions : ["north","south","east","west","center"],
34150
34151     // private
34152     create : function(target, mgr, config){
34153         target = target.toLowerCase();
34154         if(config.lightweight || config.basic){
34155             return new Roo.BasicLayoutRegion(mgr, config, target);
34156         }
34157         switch(target){
34158             case "north":
34159                 return new Roo.NorthLayoutRegion(mgr, config);
34160             case "south":
34161                 return new Roo.SouthLayoutRegion(mgr, config);
34162             case "east":
34163                 return new Roo.EastLayoutRegion(mgr, config);
34164             case "west":
34165                 return new Roo.WestLayoutRegion(mgr, config);
34166             case "center":
34167                 return new Roo.CenterLayoutRegion(mgr, config);
34168         }
34169         throw 'Layout region "'+target+'" not supported.';
34170     }
34171 };/*
34172  * Based on:
34173  * Ext JS Library 1.1.1
34174  * Copyright(c) 2006-2007, Ext JS, LLC.
34175  *
34176  * Originally Released Under LGPL - original licence link has changed is not relivant.
34177  *
34178  * Fork - LGPL
34179  * <script type="text/javascript">
34180  */
34181  
34182 /**
34183  * @class Roo.BasicLayoutRegion
34184  * @extends Roo.util.Observable
34185  * This class represents a lightweight region in a layout manager. This region does not move dom nodes
34186  * and does not have a titlebar, tabs or any other features. All it does is size and position 
34187  * panels. To create a BasicLayoutRegion, add lightweight:true or basic:true to your regions config.
34188  */
34189 Roo.BasicLayoutRegion = function(mgr, config, pos, skipConfig){
34190     this.mgr = mgr;
34191     this.position  = pos;
34192     this.events = {
34193         /**
34194          * @scope Roo.BasicLayoutRegion
34195          */
34196         
34197         /**
34198          * @event beforeremove
34199          * Fires before a panel is removed (or closed). To cancel the removal set "e.cancel = true" on the event argument.
34200          * @param {Roo.LayoutRegion} this
34201          * @param {Roo.ContentPanel} panel The panel
34202          * @param {Object} e The cancel event object
34203          */
34204         "beforeremove" : true,
34205         /**
34206          * @event invalidated
34207          * Fires when the layout for this region is changed.
34208          * @param {Roo.LayoutRegion} this
34209          */
34210         "invalidated" : true,
34211         /**
34212          * @event visibilitychange
34213          * Fires when this region is shown or hidden 
34214          * @param {Roo.LayoutRegion} this
34215          * @param {Boolean} visibility true or false
34216          */
34217         "visibilitychange" : true,
34218         /**
34219          * @event paneladded
34220          * Fires when a panel is added. 
34221          * @param {Roo.LayoutRegion} this
34222          * @param {Roo.ContentPanel} panel The panel
34223          */
34224         "paneladded" : true,
34225         /**
34226          * @event panelremoved
34227          * Fires when a panel is removed. 
34228          * @param {Roo.LayoutRegion} this
34229          * @param {Roo.ContentPanel} panel The panel
34230          */
34231         "panelremoved" : true,
34232         /**
34233          * @event beforecollapse
34234          * Fires when this region before collapse.
34235          * @param {Roo.LayoutRegion} this
34236          */
34237         "beforecollapse" : true,
34238         /**
34239          * @event collapsed
34240          * Fires when this region is collapsed.
34241          * @param {Roo.LayoutRegion} this
34242          */
34243         "collapsed" : true,
34244         /**
34245          * @event expanded
34246          * Fires when this region is expanded.
34247          * @param {Roo.LayoutRegion} this
34248          */
34249         "expanded" : true,
34250         /**
34251          * @event slideshow
34252          * Fires when this region is slid into view.
34253          * @param {Roo.LayoutRegion} this
34254          */
34255         "slideshow" : true,
34256         /**
34257          * @event slidehide
34258          * Fires when this region slides out of view. 
34259          * @param {Roo.LayoutRegion} this
34260          */
34261         "slidehide" : true,
34262         /**
34263          * @event panelactivated
34264          * Fires when a panel is activated. 
34265          * @param {Roo.LayoutRegion} this
34266          * @param {Roo.ContentPanel} panel The activated panel
34267          */
34268         "panelactivated" : true,
34269         /**
34270          * @event resized
34271          * Fires when the user resizes this region. 
34272          * @param {Roo.LayoutRegion} this
34273          * @param {Number} newSize The new size (width for east/west, height for north/south)
34274          */
34275         "resized" : true
34276     };
34277     /** A collection of panels in this region. @type Roo.util.MixedCollection */
34278     this.panels = new Roo.util.MixedCollection();
34279     this.panels.getKey = this.getPanelId.createDelegate(this);
34280     this.box = null;
34281     this.activePanel = null;
34282     // ensure listeners are added...
34283     
34284     if (config.listeners || config.events) {
34285         Roo.BasicLayoutRegion.superclass.constructor.call(this, {
34286             listeners : config.listeners || {},
34287             events : config.events || {}
34288         });
34289     }
34290     
34291     if(skipConfig !== true){
34292         this.applyConfig(config);
34293     }
34294 };
34295
34296 Roo.extend(Roo.BasicLayoutRegion, Roo.util.Observable, {
34297     getPanelId : function(p){
34298         return p.getId();
34299     },
34300     
34301     applyConfig : function(config){
34302         this.margins = config.margins || this.margins || {top: 0, left: 0, right:0, bottom: 0};
34303         this.config = config;
34304         
34305     },
34306     
34307     /**
34308      * Resizes the region to the specified size. For vertical regions (west, east) this adjusts 
34309      * the width, for horizontal (north, south) the height.
34310      * @param {Number} newSize The new width or height
34311      */
34312     resizeTo : function(newSize){
34313         var el = this.el ? this.el :
34314                  (this.activePanel ? this.activePanel.getEl() : null);
34315         if(el){
34316             switch(this.position){
34317                 case "east":
34318                 case "west":
34319                     el.setWidth(newSize);
34320                     this.fireEvent("resized", this, newSize);
34321                 break;
34322                 case "north":
34323                 case "south":
34324                     el.setHeight(newSize);
34325                     this.fireEvent("resized", this, newSize);
34326                 break;                
34327             }
34328         }
34329     },
34330     
34331     getBox : function(){
34332         return this.activePanel ? this.activePanel.getEl().getBox(false, true) : null;
34333     },
34334     
34335     getMargins : function(){
34336         return this.margins;
34337     },
34338     
34339     updateBox : function(box){
34340         this.box = box;
34341         var el = this.activePanel.getEl();
34342         el.dom.style.left = box.x + "px";
34343         el.dom.style.top = box.y + "px";
34344         this.activePanel.setSize(box.width, box.height);
34345     },
34346     
34347     /**
34348      * Returns the container element for this region.
34349      * @return {Roo.Element}
34350      */
34351     getEl : function(){
34352         return this.activePanel;
34353     },
34354     
34355     /**
34356      * Returns true if this region is currently visible.
34357      * @return {Boolean}
34358      */
34359     isVisible : function(){
34360         return this.activePanel ? true : false;
34361     },
34362     
34363     setActivePanel : function(panel){
34364         panel = this.getPanel(panel);
34365         if(this.activePanel && this.activePanel != panel){
34366             this.activePanel.setActiveState(false);
34367             this.activePanel.getEl().setLeftTop(-10000,-10000);
34368         }
34369         this.activePanel = panel;
34370         panel.setActiveState(true);
34371         if(this.box){
34372             panel.setSize(this.box.width, this.box.height);
34373         }
34374         this.fireEvent("panelactivated", this, panel);
34375         this.fireEvent("invalidated");
34376     },
34377     
34378     /**
34379      * Show the specified panel.
34380      * @param {Number/String/ContentPanel} panelId The panels index, id or the panel itself
34381      * @return {Roo.ContentPanel} The shown panel or null
34382      */
34383     showPanel : function(panel){
34384         if(panel = this.getPanel(panel)){
34385             this.setActivePanel(panel);
34386         }
34387         return panel;
34388     },
34389     
34390     /**
34391      * Get the active panel for this region.
34392      * @return {Roo.ContentPanel} The active panel or null
34393      */
34394     getActivePanel : function(){
34395         return this.activePanel;
34396     },
34397     
34398     /**
34399      * Add the passed ContentPanel(s)
34400      * @param {ContentPanel...} panel The ContentPanel(s) to add (you can pass more than one)
34401      * @return {Roo.ContentPanel} The panel added (if only one was added)
34402      */
34403     add : function(panel){
34404         if(arguments.length > 1){
34405             for(var i = 0, len = arguments.length; i < len; i++) {
34406                 this.add(arguments[i]);
34407             }
34408             return null;
34409         }
34410         if(this.hasPanel(panel)){
34411             this.showPanel(panel);
34412             return panel;
34413         }
34414         var el = panel.getEl();
34415         if(el.dom.parentNode != this.mgr.el.dom){
34416             this.mgr.el.dom.appendChild(el.dom);
34417         }
34418         if(panel.setRegion){
34419             panel.setRegion(this);
34420         }
34421         this.panels.add(panel);
34422         el.setStyle("position", "absolute");
34423         if(!panel.background){
34424             this.setActivePanel(panel);
34425             if(this.config.initialSize && this.panels.getCount()==1){
34426                 this.resizeTo(this.config.initialSize);
34427             }
34428         }
34429         this.fireEvent("paneladded", this, panel);
34430         return panel;
34431     },
34432     
34433     /**
34434      * Returns true if the panel is in this region.
34435      * @param {Number/String/ContentPanel} panel The panels index, id or the panel itself
34436      * @return {Boolean}
34437      */
34438     hasPanel : function(panel){
34439         if(typeof panel == "object"){ // must be panel obj
34440             panel = panel.getId();
34441         }
34442         return this.getPanel(panel) ? true : false;
34443     },
34444     
34445     /**
34446      * Removes the specified panel. If preservePanel is not true (either here or in the config), the panel is destroyed.
34447      * @param {Number/String/ContentPanel} panel The panels index, id or the panel itself
34448      * @param {Boolean} preservePanel Overrides the config preservePanel option
34449      * @return {Roo.ContentPanel} The panel that was removed
34450      */
34451     remove : function(panel, preservePanel){
34452         panel = this.getPanel(panel);
34453         if(!panel){
34454             return null;
34455         }
34456         var e = {};
34457         this.fireEvent("beforeremove", this, panel, e);
34458         if(e.cancel === true){
34459             return null;
34460         }
34461         var panelId = panel.getId();
34462         this.panels.removeKey(panelId);
34463         return panel;
34464     },
34465     
34466     /**
34467      * Returns the panel specified or null if it's not in this region.
34468      * @param {Number/String/ContentPanel} panel The panels index, id or the panel itself
34469      * @return {Roo.ContentPanel}
34470      */
34471     getPanel : function(id){
34472         if(typeof id == "object"){ // must be panel obj
34473             return id;
34474         }
34475         return this.panels.get(id);
34476     },
34477     
34478     /**
34479      * Returns this regions position (north/south/east/west/center).
34480      * @return {String} 
34481      */
34482     getPosition: function(){
34483         return this.position;    
34484     }
34485 });/*
34486  * Based on:
34487  * Ext JS Library 1.1.1
34488  * Copyright(c) 2006-2007, Ext JS, LLC.
34489  *
34490  * Originally Released Under LGPL - original licence link has changed is not relivant.
34491  *
34492  * Fork - LGPL
34493  * <script type="text/javascript">
34494  */
34495  
34496 /**
34497  * @class Roo.LayoutRegion
34498  * @extends Roo.BasicLayoutRegion
34499  * This class represents a region in a layout manager.
34500  * @cfg {Boolean}   collapsible     False to disable collapsing (defaults to true)
34501  * @cfg {Boolean}   collapsed       True to set the initial display to collapsed (defaults to false)
34502  * @cfg {Boolean}   floatable       False to disable floating (defaults to true)
34503  * @cfg {Object}    margins         Margins for the element (defaults to {top: 0, left: 0, right:0, bottom: 0})
34504  * @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})
34505  * @cfg {String}    tabPosition     (top|bottom) "top" or "bottom" (defaults to "bottom")
34506  * @cfg {String}    collapsedTitle  Optional string message to display in the collapsed block of a north or south region
34507  * @cfg {Boolean}   alwaysShowTabs  True to always display tabs even when there is only 1 panel (defaults to false)
34508  * @cfg {Boolean}   autoScroll      True to enable overflow scrolling (defaults to false)
34509  * @cfg {Boolean}   titlebar        True to display a title bar (defaults to true)
34510  * @cfg {String}    title           The title for the region (overrides panel titles)
34511  * @cfg {Boolean}   animate         True to animate expand/collapse (defaults to false)
34512  * @cfg {Boolean}   autoHide        False to disable auto hiding when the mouse leaves the "floated" region (defaults to true)
34513  * @cfg {Boolean}   preservePanels  True to preserve removed panels so they can be readded later (defaults to false)
34514  * @cfg {Boolean}   closeOnTab      True to place the close icon on the tabs instead of the region titlebar (defaults to false)
34515  * @cfg {Boolean}   hideTabs        True to hide the tab strip (defaults to false)
34516  * @cfg {Boolean}   resizeTabs      True to enable automatic tab resizing. This will resize the tabs so they are all the same size and fit within
34517  *                      the space available, similar to FireFox 1.5 tabs (defaults to false)
34518  * @cfg {Number}    minTabWidth     The minimum tab width (defaults to 40)
34519  * @cfg {Number}    preferredTabWidth The preferred tab width (defaults to 150)
34520  * @cfg {Boolean}   showPin         True to show a pin button
34521  * @cfg {Boolean}   hidden          True to start the region hidden (defaults to false)
34522  * @cfg {Boolean}   hideWhenEmpty   True to hide the region when it has no panels
34523  * @cfg {Boolean}   disableTabTips  True to disable tab tooltips
34524  * @cfg {Number}    width           For East/West panels
34525  * @cfg {Number}    height          For North/South panels
34526  * @cfg {Boolean}   split           To show the splitter
34527  * @cfg {Boolean}   toolbar         xtype configuration for a toolbar - shows on right of tabbar
34528  */
34529 Roo.LayoutRegion = function(mgr, config, pos){
34530     Roo.LayoutRegion.superclass.constructor.call(this, mgr, config, pos, true);
34531     var dh = Roo.DomHelper;
34532     /** This region's container element 
34533     * @type Roo.Element */
34534     this.el = dh.append(mgr.el.dom, {tag: "div", cls: "x-layout-panel x-layout-panel-" + this.position}, true);
34535     /** This region's title element 
34536     * @type Roo.Element */
34537
34538     this.titleEl = dh.append(this.el.dom, {tag: "div", unselectable: "on", cls: "x-unselectable x-layout-panel-hd x-layout-title-"+this.position, children:[
34539         {tag: "span", cls: "x-unselectable x-layout-panel-hd-text", unselectable: "on", html: "&#160;"},
34540         {tag: "div", cls: "x-unselectable x-layout-panel-hd-tools", unselectable: "on"}
34541     ]}, true);
34542     this.titleEl.enableDisplayMode();
34543     /** This region's title text element 
34544     * @type HTMLElement */
34545     this.titleTextEl = this.titleEl.dom.firstChild;
34546     this.tools = Roo.get(this.titleEl.dom.childNodes[1], true);
34547     this.closeBtn = this.createTool(this.tools.dom, "x-layout-close");
34548     this.closeBtn.enableDisplayMode();
34549     this.closeBtn.on("click", this.closeClicked, this);
34550     this.closeBtn.hide();
34551
34552     this.createBody(config);
34553     this.visible = true;
34554     this.collapsed = false;
34555
34556     if(config.hideWhenEmpty){
34557         this.hide();
34558         this.on("paneladded", this.validateVisibility, this);
34559         this.on("panelremoved", this.validateVisibility, this);
34560     }
34561     this.applyConfig(config);
34562 };
34563
34564 Roo.extend(Roo.LayoutRegion, Roo.BasicLayoutRegion, {
34565
34566     createBody : function(){
34567         /** This region's body element 
34568         * @type Roo.Element */
34569         this.bodyEl = this.el.createChild({tag: "div", cls: "x-layout-panel-body"});
34570     },
34571
34572     applyConfig : function(c){
34573         if(c.collapsible && this.position != "center" && !this.collapsedEl){
34574             var dh = Roo.DomHelper;
34575             if(c.titlebar !== false){
34576                 this.collapseBtn = this.createTool(this.tools.dom, "x-layout-collapse-"+this.position);
34577                 this.collapseBtn.on("click", this.collapse, this);
34578                 this.collapseBtn.enableDisplayMode();
34579
34580                 if(c.showPin === true || this.showPin){
34581                     this.stickBtn = this.createTool(this.tools.dom, "x-layout-stick");
34582                     this.stickBtn.enableDisplayMode();
34583                     this.stickBtn.on("click", this.expand, this);
34584                     this.stickBtn.hide();
34585                 }
34586             }
34587             /** This region's collapsed element
34588             * @type Roo.Element */
34589             this.collapsedEl = dh.append(this.mgr.el.dom, {cls: "x-layout-collapsed x-layout-collapsed-"+this.position, children:[
34590                 {cls: "x-layout-collapsed-tools", children:[{cls: "x-layout-ctools-inner"}]}
34591             ]}, true);
34592             if(c.floatable !== false){
34593                this.collapsedEl.addClassOnOver("x-layout-collapsed-over");
34594                this.collapsedEl.on("click", this.collapseClick, this);
34595             }
34596
34597             if(c.collapsedTitle && (this.position == "north" || this.position== "south")) {
34598                 this.collapsedTitleTextEl = dh.append(this.collapsedEl.dom, {tag: "div", cls: "x-unselectable x-layout-panel-hd-text",
34599                    id: "message", unselectable: "on", style:{"float":"left"}});
34600                this.collapsedTitleTextEl.innerHTML = c.collapsedTitle;
34601              }
34602             this.expandBtn = this.createTool(this.collapsedEl.dom.firstChild.firstChild, "x-layout-expand-"+this.position);
34603             this.expandBtn.on("click", this.expand, this);
34604         }
34605         if(this.collapseBtn){
34606             this.collapseBtn.setVisible(c.collapsible == true);
34607         }
34608         this.cmargins = c.cmargins || this.cmargins ||
34609                          (this.position == "west" || this.position == "east" ?
34610                              {top: 0, left: 2, right:2, bottom: 0} :
34611                              {top: 2, left: 0, right:0, bottom: 2});
34612         this.margins = c.margins || this.margins || {top: 0, left: 0, right:0, bottom: 0};
34613         this.bottomTabs = c.tabPosition != "top";
34614         this.autoScroll = c.autoScroll || false;
34615         if(this.autoScroll){
34616             this.bodyEl.setStyle("overflow", "auto");
34617         }else{
34618             this.bodyEl.setStyle("overflow", "hidden");
34619         }
34620         //if(c.titlebar !== false){
34621             if((!c.titlebar && !c.title) || c.titlebar === false){
34622                 this.titleEl.hide();
34623             }else{
34624                 this.titleEl.show();
34625                 if(c.title){
34626                     this.titleTextEl.innerHTML = c.title;
34627                 }
34628             }
34629         //}
34630         this.duration = c.duration || .30;
34631         this.slideDuration = c.slideDuration || .45;
34632         this.config = c;
34633         if(c.collapsed){
34634             this.collapse(true);
34635         }
34636         if(c.hidden){
34637             this.hide();
34638         }
34639     },
34640     /**
34641      * Returns true if this region is currently visible.
34642      * @return {Boolean}
34643      */
34644     isVisible : function(){
34645         return this.visible;
34646     },
34647
34648     /**
34649      * Updates the title for collapsed north/south regions (used with {@link #collapsedTitle} config option)
34650      * @param {String} title (optional) The title text (accepts HTML markup, defaults to the numeric character reference for a non-breaking space, "&amp;#160;")
34651      */
34652     setCollapsedTitle : function(title){
34653         title = title || "&#160;";
34654         if(this.collapsedTitleTextEl){
34655             this.collapsedTitleTextEl.innerHTML = title;
34656         }
34657     },
34658
34659     getBox : function(){
34660         var b;
34661         if(!this.collapsed){
34662             b = this.el.getBox(false, true);
34663         }else{
34664             b = this.collapsedEl.getBox(false, true);
34665         }
34666         return b;
34667     },
34668
34669     getMargins : function(){
34670         return this.collapsed ? this.cmargins : this.margins;
34671     },
34672
34673     highlight : function(){
34674         this.el.addClass("x-layout-panel-dragover");
34675     },
34676
34677     unhighlight : function(){
34678         this.el.removeClass("x-layout-panel-dragover");
34679     },
34680
34681     updateBox : function(box){
34682         this.box = box;
34683         if(!this.collapsed){
34684             this.el.dom.style.left = box.x + "px";
34685             this.el.dom.style.top = box.y + "px";
34686             this.updateBody(box.width, box.height);
34687         }else{
34688             this.collapsedEl.dom.style.left = box.x + "px";
34689             this.collapsedEl.dom.style.top = box.y + "px";
34690             this.collapsedEl.setSize(box.width, box.height);
34691         }
34692         if(this.tabs){
34693             this.tabs.autoSizeTabs();
34694         }
34695     },
34696
34697     updateBody : function(w, h){
34698         if(w !== null){
34699             this.el.setWidth(w);
34700             w -= this.el.getBorderWidth("rl");
34701             if(this.config.adjustments){
34702                 w += this.config.adjustments[0];
34703             }
34704         }
34705         if(h !== null){
34706             this.el.setHeight(h);
34707             h = this.titleEl && this.titleEl.isDisplayed() ? h - (this.titleEl.getHeight()||0) : h;
34708             h -= this.el.getBorderWidth("tb");
34709             if(this.config.adjustments){
34710                 h += this.config.adjustments[1];
34711             }
34712             this.bodyEl.setHeight(h);
34713             if(this.tabs){
34714                 h = this.tabs.syncHeight(h);
34715             }
34716         }
34717         if(this.panelSize){
34718             w = w !== null ? w : this.panelSize.width;
34719             h = h !== null ? h : this.panelSize.height;
34720         }
34721         if(this.activePanel){
34722             var el = this.activePanel.getEl();
34723             w = w !== null ? w : el.getWidth();
34724             h = h !== null ? h : el.getHeight();
34725             this.panelSize = {width: w, height: h};
34726             this.activePanel.setSize(w, h);
34727         }
34728         if(Roo.isIE && this.tabs){
34729             this.tabs.el.repaint();
34730         }
34731     },
34732
34733     /**
34734      * Returns the container element for this region.
34735      * @return {Roo.Element}
34736      */
34737     getEl : function(){
34738         return this.el;
34739     },
34740
34741     /**
34742      * Hides this region.
34743      */
34744     hide : function(){
34745         if(!this.collapsed){
34746             this.el.dom.style.left = "-2000px";
34747             this.el.hide();
34748         }else{
34749             this.collapsedEl.dom.style.left = "-2000px";
34750             this.collapsedEl.hide();
34751         }
34752         this.visible = false;
34753         this.fireEvent("visibilitychange", this, false);
34754     },
34755
34756     /**
34757      * Shows this region if it was previously hidden.
34758      */
34759     show : function(){
34760         if(!this.collapsed){
34761             this.el.show();
34762         }else{
34763             this.collapsedEl.show();
34764         }
34765         this.visible = true;
34766         this.fireEvent("visibilitychange", this, true);
34767     },
34768
34769     closeClicked : function(){
34770         if(this.activePanel){
34771             this.remove(this.activePanel);
34772         }
34773     },
34774
34775     collapseClick : function(e){
34776         if(this.isSlid){
34777            e.stopPropagation();
34778            this.slideIn();
34779         }else{
34780            e.stopPropagation();
34781            this.slideOut();
34782         }
34783     },
34784
34785     /**
34786      * Collapses this region.
34787      * @param {Boolean} skipAnim (optional) true to collapse the element without animation (if animate is true)
34788      */
34789     collapse : function(skipAnim, skipCheck){
34790         if(this.collapsed) {
34791             return;
34792         }
34793         
34794         if(skipCheck || this.fireEvent("beforecollapse", this) != false){
34795             
34796             this.collapsed = true;
34797             if(this.split){
34798                 this.split.el.hide();
34799             }
34800             if(this.config.animate && skipAnim !== true){
34801                 this.fireEvent("invalidated", this);
34802                 this.animateCollapse();
34803             }else{
34804                 this.el.setLocation(-20000,-20000);
34805                 this.el.hide();
34806                 this.collapsedEl.show();
34807                 this.fireEvent("collapsed", this);
34808                 this.fireEvent("invalidated", this);
34809             }
34810         }
34811         
34812     },
34813
34814     animateCollapse : function(){
34815         // overridden
34816     },
34817
34818     /**
34819      * Expands this region if it was previously collapsed.
34820      * @param {Roo.EventObject} e The event that triggered the expand (or null if calling manually)
34821      * @param {Boolean} skipAnim (optional) true to expand the element without animation (if animate is true)
34822      */
34823     expand : function(e, skipAnim){
34824         if(e) {
34825             e.stopPropagation();
34826         }
34827         if(!this.collapsed || this.el.hasActiveFx()) {
34828             return;
34829         }
34830         if(this.isSlid){
34831             this.afterSlideIn();
34832             skipAnim = true;
34833         }
34834         this.collapsed = false;
34835         if(this.config.animate && skipAnim !== true){
34836             this.animateExpand();
34837         }else{
34838             this.el.show();
34839             if(this.split){
34840                 this.split.el.show();
34841             }
34842             this.collapsedEl.setLocation(-2000,-2000);
34843             this.collapsedEl.hide();
34844             this.fireEvent("invalidated", this);
34845             this.fireEvent("expanded", this);
34846         }
34847     },
34848
34849     animateExpand : function(){
34850         // overridden
34851     },
34852
34853     initTabs : function()
34854     {
34855         this.bodyEl.setStyle("overflow", "hidden");
34856         var ts = new Roo.TabPanel(
34857                 this.bodyEl.dom,
34858                 {
34859                     tabPosition: this.bottomTabs ? 'bottom' : 'top',
34860                     disableTooltips: this.config.disableTabTips,
34861                     toolbar : this.config.toolbar
34862                 }
34863         );
34864         if(this.config.hideTabs){
34865             ts.stripWrap.setDisplayed(false);
34866         }
34867         this.tabs = ts;
34868         ts.resizeTabs = this.config.resizeTabs === true;
34869         ts.minTabWidth = this.config.minTabWidth || 40;
34870         ts.maxTabWidth = this.config.maxTabWidth || 250;
34871         ts.preferredTabWidth = this.config.preferredTabWidth || 150;
34872         ts.monitorResize = false;
34873         ts.bodyEl.setStyle("overflow", this.config.autoScroll ? "auto" : "hidden");
34874         ts.bodyEl.addClass('x-layout-tabs-body');
34875         this.panels.each(this.initPanelAsTab, this);
34876     },
34877
34878     initPanelAsTab : function(panel){
34879         var ti = this.tabs.addTab(panel.getEl().id, panel.getTitle(), null,
34880                     this.config.closeOnTab && panel.isClosable());
34881         if(panel.tabTip !== undefined){
34882             ti.setTooltip(panel.tabTip);
34883         }
34884         ti.on("activate", function(){
34885               this.setActivePanel(panel);
34886         }, this);
34887         if(this.config.closeOnTab){
34888             ti.on("beforeclose", function(t, e){
34889                 e.cancel = true;
34890                 this.remove(panel);
34891             }, this);
34892         }
34893         return ti;
34894     },
34895
34896     updatePanelTitle : function(panel, title){
34897         if(this.activePanel == panel){
34898             this.updateTitle(title);
34899         }
34900         if(this.tabs){
34901             var ti = this.tabs.getTab(panel.getEl().id);
34902             ti.setText(title);
34903             if(panel.tabTip !== undefined){
34904                 ti.setTooltip(panel.tabTip);
34905             }
34906         }
34907     },
34908
34909     updateTitle : function(title){
34910         if(this.titleTextEl && !this.config.title){
34911             this.titleTextEl.innerHTML = (typeof title != "undefined" && title.length > 0 ? title : "&#160;");
34912         }
34913     },
34914
34915     setActivePanel : function(panel){
34916         panel = this.getPanel(panel);
34917         if(this.activePanel && this.activePanel != panel){
34918             this.activePanel.setActiveState(false);
34919         }
34920         this.activePanel = panel;
34921         panel.setActiveState(true);
34922         if(this.panelSize){
34923             panel.setSize(this.panelSize.width, this.panelSize.height);
34924         }
34925         if(this.closeBtn){
34926             this.closeBtn.setVisible(!this.config.closeOnTab && !this.isSlid && panel.isClosable());
34927         }
34928         this.updateTitle(panel.getTitle());
34929         if(this.tabs){
34930             this.fireEvent("invalidated", this);
34931         }
34932         this.fireEvent("panelactivated", this, panel);
34933     },
34934
34935     /**
34936      * Shows the specified panel.
34937      * @param {Number/String/ContentPanel} panelId The panel's index, id or the panel itself
34938      * @return {Roo.ContentPanel} The shown panel, or null if a panel could not be found from panelId
34939      */
34940     showPanel : function(panel)
34941     {
34942         panel = this.getPanel(panel);
34943         if(panel){
34944             if(this.tabs){
34945                 var tab = this.tabs.getTab(panel.getEl().id);
34946                 if(tab.isHidden()){
34947                     this.tabs.unhideTab(tab.id);
34948                 }
34949                 tab.activate();
34950             }else{
34951                 this.setActivePanel(panel);
34952             }
34953         }
34954         return panel;
34955     },
34956
34957     /**
34958      * Get the active panel for this region.
34959      * @return {Roo.ContentPanel} The active panel or null
34960      */
34961     getActivePanel : function(){
34962         return this.activePanel;
34963     },
34964
34965     validateVisibility : function(){
34966         if(this.panels.getCount() < 1){
34967             this.updateTitle("&#160;");
34968             this.closeBtn.hide();
34969             this.hide();
34970         }else{
34971             if(!this.isVisible()){
34972                 this.show();
34973             }
34974         }
34975     },
34976
34977     /**
34978      * Adds the passed ContentPanel(s) to this region.
34979      * @param {ContentPanel...} panel The ContentPanel(s) to add (you can pass more than one)
34980      * @return {Roo.ContentPanel} The panel added (if only one was added; null otherwise)
34981      */
34982     add : function(panel){
34983         if(arguments.length > 1){
34984             for(var i = 0, len = arguments.length; i < len; i++) {
34985                 this.add(arguments[i]);
34986             }
34987             return null;
34988         }
34989         if(this.hasPanel(panel)){
34990             this.showPanel(panel);
34991             return panel;
34992         }
34993         panel.setRegion(this);
34994         this.panels.add(panel);
34995         if(this.panels.getCount() == 1 && !this.config.alwaysShowTabs){
34996             this.bodyEl.dom.appendChild(panel.getEl().dom);
34997             if(panel.background !== true){
34998                 this.setActivePanel(panel);
34999             }
35000             this.fireEvent("paneladded", this, panel);
35001             return panel;
35002         }
35003         if(!this.tabs){
35004             this.initTabs();
35005         }else{
35006             this.initPanelAsTab(panel);
35007         }
35008         if(panel.background !== true){
35009             this.tabs.activate(panel.getEl().id);
35010         }
35011         this.fireEvent("paneladded", this, panel);
35012         return panel;
35013     },
35014
35015     /**
35016      * Hides the tab for the specified panel.
35017      * @param {Number/String/ContentPanel} panel The panel's index, id or the panel itself
35018      */
35019     hidePanel : function(panel){
35020         if(this.tabs && (panel = this.getPanel(panel))){
35021             this.tabs.hideTab(panel.getEl().id);
35022         }
35023     },
35024
35025     /**
35026      * Unhides the tab for a previously hidden panel.
35027      * @param {Number/String/ContentPanel} panel The panel's index, id or the panel itself
35028      */
35029     unhidePanel : function(panel){
35030         if(this.tabs && (panel = this.getPanel(panel))){
35031             this.tabs.unhideTab(panel.getEl().id);
35032         }
35033     },
35034
35035     clearPanels : function(){
35036         while(this.panels.getCount() > 0){
35037              this.remove(this.panels.first());
35038         }
35039     },
35040
35041     /**
35042      * Removes the specified panel. If preservePanel is not true (either here or in the config), the panel is destroyed.
35043      * @param {Number/String/ContentPanel} panel The panel's index, id or the panel itself
35044      * @param {Boolean} preservePanel Overrides the config preservePanel option
35045      * @return {Roo.ContentPanel} The panel that was removed
35046      */
35047     remove : function(panel, preservePanel){
35048         panel = this.getPanel(panel);
35049         if(!panel){
35050             return null;
35051         }
35052         var e = {};
35053         this.fireEvent("beforeremove", this, panel, e);
35054         if(e.cancel === true){
35055             return null;
35056         }
35057         preservePanel = (typeof preservePanel != "undefined" ? preservePanel : (this.config.preservePanels === true || panel.preserve === true));
35058         var panelId = panel.getId();
35059         this.panels.removeKey(panelId);
35060         if(preservePanel){
35061             document.body.appendChild(panel.getEl().dom);
35062         }
35063         if(this.tabs){
35064             this.tabs.removeTab(panel.getEl().id);
35065         }else if (!preservePanel){
35066             this.bodyEl.dom.removeChild(panel.getEl().dom);
35067         }
35068         if(this.panels.getCount() == 1 && this.tabs && !this.config.alwaysShowTabs){
35069             var p = this.panels.first();
35070             var tempEl = document.createElement("div"); // temp holder to keep IE from deleting the node
35071             tempEl.appendChild(p.getEl().dom);
35072             this.bodyEl.update("");
35073             this.bodyEl.dom.appendChild(p.getEl().dom);
35074             tempEl = null;
35075             this.updateTitle(p.getTitle());
35076             this.tabs = null;
35077             this.bodyEl.setStyle("overflow", this.config.autoScroll ? "auto" : "hidden");
35078             this.setActivePanel(p);
35079         }
35080         panel.setRegion(null);
35081         if(this.activePanel == panel){
35082             this.activePanel = null;
35083         }
35084         if(this.config.autoDestroy !== false && preservePanel !== true){
35085             try{panel.destroy();}catch(e){}
35086         }
35087         this.fireEvent("panelremoved", this, panel);
35088         return panel;
35089     },
35090
35091     /**
35092      * Returns the TabPanel component used by this region
35093      * @return {Roo.TabPanel}
35094      */
35095     getTabs : function(){
35096         return this.tabs;
35097     },
35098
35099     createTool : function(parentEl, className){
35100         var btn = Roo.DomHelper.append(parentEl, {tag: "div", cls: "x-layout-tools-button",
35101             children: [{tag: "div", cls: "x-layout-tools-button-inner " + className, html: "&#160;"}]}, true);
35102         btn.addClassOnOver("x-layout-tools-button-over");
35103         return btn;
35104     }
35105 });/*
35106  * Based on:
35107  * Ext JS Library 1.1.1
35108  * Copyright(c) 2006-2007, Ext JS, LLC.
35109  *
35110  * Originally Released Under LGPL - original licence link has changed is not relivant.
35111  *
35112  * Fork - LGPL
35113  * <script type="text/javascript">
35114  */
35115  
35116
35117
35118 /**
35119  * @class Roo.SplitLayoutRegion
35120  * @extends Roo.LayoutRegion
35121  * Adds a splitbar and other (private) useful functionality to a {@link Roo.LayoutRegion}.
35122  */
35123 Roo.SplitLayoutRegion = function(mgr, config, pos, cursor){
35124     this.cursor = cursor;
35125     Roo.SplitLayoutRegion.superclass.constructor.call(this, mgr, config, pos);
35126 };
35127
35128 Roo.extend(Roo.SplitLayoutRegion, Roo.LayoutRegion, {
35129     splitTip : "Drag to resize.",
35130     collapsibleSplitTip : "Drag to resize. Double click to hide.",
35131     useSplitTips : false,
35132
35133     applyConfig : function(config){
35134         Roo.SplitLayoutRegion.superclass.applyConfig.call(this, config);
35135         if(config.split){
35136             if(!this.split){
35137                 var splitEl = Roo.DomHelper.append(this.mgr.el.dom, 
35138                         {tag: "div", id: this.el.id + "-split", cls: "x-layout-split x-layout-split-"+this.position, html: "&#160;"});
35139                 /** The SplitBar for this region 
35140                 * @type Roo.SplitBar */
35141                 this.split = new Roo.SplitBar(splitEl, this.el, this.orientation);
35142                 this.split.on("moved", this.onSplitMove, this);
35143                 this.split.useShim = config.useShim === true;
35144                 this.split.getMaximumSize = this[this.position == 'north' || this.position == 'south' ? 'getVMaxSize' : 'getHMaxSize'].createDelegate(this);
35145                 if(this.useSplitTips){
35146                     this.split.el.dom.title = config.collapsible ? this.collapsibleSplitTip : this.splitTip;
35147                 }
35148                 if(config.collapsible){
35149                     this.split.el.on("dblclick", this.collapse,  this);
35150                 }
35151             }
35152             if(typeof config.minSize != "undefined"){
35153                 this.split.minSize = config.minSize;
35154             }
35155             if(typeof config.maxSize != "undefined"){
35156                 this.split.maxSize = config.maxSize;
35157             }
35158             if(config.hideWhenEmpty || config.hidden || config.collapsed){
35159                 this.hideSplitter();
35160             }
35161         }
35162     },
35163
35164     getHMaxSize : function(){
35165          var cmax = this.config.maxSize || 10000;
35166          var center = this.mgr.getRegion("center");
35167          return Math.min(cmax, (this.el.getWidth()+center.getEl().getWidth())-center.getMinWidth());
35168     },
35169
35170     getVMaxSize : function(){
35171          var cmax = this.config.maxSize || 10000;
35172          var center = this.mgr.getRegion("center");
35173          return Math.min(cmax, (this.el.getHeight()+center.getEl().getHeight())-center.getMinHeight());
35174     },
35175
35176     onSplitMove : function(split, newSize){
35177         this.fireEvent("resized", this, newSize);
35178     },
35179     
35180     /** 
35181      * Returns the {@link Roo.SplitBar} for this region.
35182      * @return {Roo.SplitBar}
35183      */
35184     getSplitBar : function(){
35185         return this.split;
35186     },
35187     
35188     hide : function(){
35189         this.hideSplitter();
35190         Roo.SplitLayoutRegion.superclass.hide.call(this);
35191     },
35192
35193     hideSplitter : function(){
35194         if(this.split){
35195             this.split.el.setLocation(-2000,-2000);
35196             this.split.el.hide();
35197         }
35198     },
35199
35200     show : function(){
35201         if(this.split){
35202             this.split.el.show();
35203         }
35204         Roo.SplitLayoutRegion.superclass.show.call(this);
35205     },
35206     
35207     beforeSlide: function(){
35208         if(Roo.isGecko){// firefox overflow auto bug workaround
35209             this.bodyEl.clip();
35210             if(this.tabs) {
35211                 this.tabs.bodyEl.clip();
35212             }
35213             if(this.activePanel){
35214                 this.activePanel.getEl().clip();
35215                 
35216                 if(this.activePanel.beforeSlide){
35217                     this.activePanel.beforeSlide();
35218                 }
35219             }
35220         }
35221     },
35222     
35223     afterSlide : function(){
35224         if(Roo.isGecko){// firefox overflow auto bug workaround
35225             this.bodyEl.unclip();
35226             if(this.tabs) {
35227                 this.tabs.bodyEl.unclip();
35228             }
35229             if(this.activePanel){
35230                 this.activePanel.getEl().unclip();
35231                 if(this.activePanel.afterSlide){
35232                     this.activePanel.afterSlide();
35233                 }
35234             }
35235         }
35236     },
35237
35238     initAutoHide : function(){
35239         if(this.autoHide !== false){
35240             if(!this.autoHideHd){
35241                 var st = new Roo.util.DelayedTask(this.slideIn, this);
35242                 this.autoHideHd = {
35243                     "mouseout": function(e){
35244                         if(!e.within(this.el, true)){
35245                             st.delay(500);
35246                         }
35247                     },
35248                     "mouseover" : function(e){
35249                         st.cancel();
35250                     },
35251                     scope : this
35252                 };
35253             }
35254             this.el.on(this.autoHideHd);
35255         }
35256     },
35257
35258     clearAutoHide : function(){
35259         if(this.autoHide !== false){
35260             this.el.un("mouseout", this.autoHideHd.mouseout);
35261             this.el.un("mouseover", this.autoHideHd.mouseover);
35262         }
35263     },
35264
35265     clearMonitor : function(){
35266         Roo.get(document).un("click", this.slideInIf, this);
35267     },
35268
35269     // these names are backwards but not changed for compat
35270     slideOut : function(){
35271         if(this.isSlid || this.el.hasActiveFx()){
35272             return;
35273         }
35274         this.isSlid = true;
35275         if(this.collapseBtn){
35276             this.collapseBtn.hide();
35277         }
35278         this.closeBtnState = this.closeBtn.getStyle('display');
35279         this.closeBtn.hide();
35280         if(this.stickBtn){
35281             this.stickBtn.show();
35282         }
35283         this.el.show();
35284         this.el.alignTo(this.collapsedEl, this.getCollapseAnchor());
35285         this.beforeSlide();
35286         this.el.setStyle("z-index", 10001);
35287         this.el.slideIn(this.getSlideAnchor(), {
35288             callback: function(){
35289                 this.afterSlide();
35290                 this.initAutoHide();
35291                 Roo.get(document).on("click", this.slideInIf, this);
35292                 this.fireEvent("slideshow", this);
35293             },
35294             scope: this,
35295             block: true
35296         });
35297     },
35298
35299     afterSlideIn : function(){
35300         this.clearAutoHide();
35301         this.isSlid = false;
35302         this.clearMonitor();
35303         this.el.setStyle("z-index", "");
35304         if(this.collapseBtn){
35305             this.collapseBtn.show();
35306         }
35307         this.closeBtn.setStyle('display', this.closeBtnState);
35308         if(this.stickBtn){
35309             this.stickBtn.hide();
35310         }
35311         this.fireEvent("slidehide", this);
35312     },
35313
35314     slideIn : function(cb){
35315         if(!this.isSlid || this.el.hasActiveFx()){
35316             Roo.callback(cb);
35317             return;
35318         }
35319         this.isSlid = false;
35320         this.beforeSlide();
35321         this.el.slideOut(this.getSlideAnchor(), {
35322             callback: function(){
35323                 this.el.setLeftTop(-10000, -10000);
35324                 this.afterSlide();
35325                 this.afterSlideIn();
35326                 Roo.callback(cb);
35327             },
35328             scope: this,
35329             block: true
35330         });
35331     },
35332     
35333     slideInIf : function(e){
35334         if(!e.within(this.el)){
35335             this.slideIn();
35336         }
35337     },
35338
35339     animateCollapse : function(){
35340         this.beforeSlide();
35341         this.el.setStyle("z-index", 20000);
35342         var anchor = this.getSlideAnchor();
35343         this.el.slideOut(anchor, {
35344             callback : function(){
35345                 this.el.setStyle("z-index", "");
35346                 this.collapsedEl.slideIn(anchor, {duration:.3});
35347                 this.afterSlide();
35348                 this.el.setLocation(-10000,-10000);
35349                 this.el.hide();
35350                 this.fireEvent("collapsed", this);
35351             },
35352             scope: this,
35353             block: true
35354         });
35355     },
35356
35357     animateExpand : function(){
35358         this.beforeSlide();
35359         this.el.alignTo(this.collapsedEl, this.getCollapseAnchor(), this.getExpandAdj());
35360         this.el.setStyle("z-index", 20000);
35361         this.collapsedEl.hide({
35362             duration:.1
35363         });
35364         this.el.slideIn(this.getSlideAnchor(), {
35365             callback : function(){
35366                 this.el.setStyle("z-index", "");
35367                 this.afterSlide();
35368                 if(this.split){
35369                     this.split.el.show();
35370                 }
35371                 this.fireEvent("invalidated", this);
35372                 this.fireEvent("expanded", this);
35373             },
35374             scope: this,
35375             block: true
35376         });
35377     },
35378
35379     anchors : {
35380         "west" : "left",
35381         "east" : "right",
35382         "north" : "top",
35383         "south" : "bottom"
35384     },
35385
35386     sanchors : {
35387         "west" : "l",
35388         "east" : "r",
35389         "north" : "t",
35390         "south" : "b"
35391     },
35392
35393     canchors : {
35394         "west" : "tl-tr",
35395         "east" : "tr-tl",
35396         "north" : "tl-bl",
35397         "south" : "bl-tl"
35398     },
35399
35400     getAnchor : function(){
35401         return this.anchors[this.position];
35402     },
35403
35404     getCollapseAnchor : function(){
35405         return this.canchors[this.position];
35406     },
35407
35408     getSlideAnchor : function(){
35409         return this.sanchors[this.position];
35410     },
35411
35412     getAlignAdj : function(){
35413         var cm = this.cmargins;
35414         switch(this.position){
35415             case "west":
35416                 return [0, 0];
35417             break;
35418             case "east":
35419                 return [0, 0];
35420             break;
35421             case "north":
35422                 return [0, 0];
35423             break;
35424             case "south":
35425                 return [0, 0];
35426             break;
35427         }
35428     },
35429
35430     getExpandAdj : function(){
35431         var c = this.collapsedEl, cm = this.cmargins;
35432         switch(this.position){
35433             case "west":
35434                 return [-(cm.right+c.getWidth()+cm.left), 0];
35435             break;
35436             case "east":
35437                 return [cm.right+c.getWidth()+cm.left, 0];
35438             break;
35439             case "north":
35440                 return [0, -(cm.top+cm.bottom+c.getHeight())];
35441             break;
35442             case "south":
35443                 return [0, cm.top+cm.bottom+c.getHeight()];
35444             break;
35445         }
35446     }
35447 });/*
35448  * Based on:
35449  * Ext JS Library 1.1.1
35450  * Copyright(c) 2006-2007, Ext JS, LLC.
35451  *
35452  * Originally Released Under LGPL - original licence link has changed is not relivant.
35453  *
35454  * Fork - LGPL
35455  * <script type="text/javascript">
35456  */
35457 /*
35458  * These classes are private internal classes
35459  */
35460 Roo.CenterLayoutRegion = function(mgr, config){
35461     Roo.LayoutRegion.call(this, mgr, config, "center");
35462     this.visible = true;
35463     this.minWidth = config.minWidth || 20;
35464     this.minHeight = config.minHeight || 20;
35465 };
35466
35467 Roo.extend(Roo.CenterLayoutRegion, Roo.LayoutRegion, {
35468     hide : function(){
35469         // center panel can't be hidden
35470     },
35471     
35472     show : function(){
35473         // center panel can't be hidden
35474     },
35475     
35476     getMinWidth: function(){
35477         return this.minWidth;
35478     },
35479     
35480     getMinHeight: function(){
35481         return this.minHeight;
35482     }
35483 });
35484
35485
35486 Roo.NorthLayoutRegion = function(mgr, config){
35487     Roo.LayoutRegion.call(this, mgr, config, "north", "n-resize");
35488     if(this.split){
35489         this.split.placement = Roo.SplitBar.TOP;
35490         this.split.orientation = Roo.SplitBar.VERTICAL;
35491         this.split.el.addClass("x-layout-split-v");
35492     }
35493     var size = config.initialSize || config.height;
35494     if(typeof size != "undefined"){
35495         this.el.setHeight(size);
35496     }
35497 };
35498 Roo.extend(Roo.NorthLayoutRegion, Roo.SplitLayoutRegion, {
35499     orientation: Roo.SplitBar.VERTICAL,
35500     getBox : function(){
35501         if(this.collapsed){
35502             return this.collapsedEl.getBox();
35503         }
35504         var box = this.el.getBox();
35505         if(this.split){
35506             box.height += this.split.el.getHeight();
35507         }
35508         return box;
35509     },
35510     
35511     updateBox : function(box){
35512         if(this.split && !this.collapsed){
35513             box.height -= this.split.el.getHeight();
35514             this.split.el.setLeft(box.x);
35515             this.split.el.setTop(box.y+box.height);
35516             this.split.el.setWidth(box.width);
35517         }
35518         if(this.collapsed){
35519             this.updateBody(box.width, null);
35520         }
35521         Roo.LayoutRegion.prototype.updateBox.call(this, box);
35522     }
35523 });
35524
35525 Roo.SouthLayoutRegion = function(mgr, config){
35526     Roo.SplitLayoutRegion.call(this, mgr, config, "south", "s-resize");
35527     if(this.split){
35528         this.split.placement = Roo.SplitBar.BOTTOM;
35529         this.split.orientation = Roo.SplitBar.VERTICAL;
35530         this.split.el.addClass("x-layout-split-v");
35531     }
35532     var size = config.initialSize || config.height;
35533     if(typeof size != "undefined"){
35534         this.el.setHeight(size);
35535     }
35536 };
35537 Roo.extend(Roo.SouthLayoutRegion, Roo.SplitLayoutRegion, {
35538     orientation: Roo.SplitBar.VERTICAL,
35539     getBox : function(){
35540         if(this.collapsed){
35541             return this.collapsedEl.getBox();
35542         }
35543         var box = this.el.getBox();
35544         if(this.split){
35545             var sh = this.split.el.getHeight();
35546             box.height += sh;
35547             box.y -= sh;
35548         }
35549         return box;
35550     },
35551     
35552     updateBox : function(box){
35553         if(this.split && !this.collapsed){
35554             var sh = this.split.el.getHeight();
35555             box.height -= sh;
35556             box.y += sh;
35557             this.split.el.setLeft(box.x);
35558             this.split.el.setTop(box.y-sh);
35559             this.split.el.setWidth(box.width);
35560         }
35561         if(this.collapsed){
35562             this.updateBody(box.width, null);
35563         }
35564         Roo.LayoutRegion.prototype.updateBox.call(this, box);
35565     }
35566 });
35567
35568 Roo.EastLayoutRegion = function(mgr, config){
35569     Roo.SplitLayoutRegion.call(this, mgr, config, "east", "e-resize");
35570     if(this.split){
35571         this.split.placement = Roo.SplitBar.RIGHT;
35572         this.split.orientation = Roo.SplitBar.HORIZONTAL;
35573         this.split.el.addClass("x-layout-split-h");
35574     }
35575     var size = config.initialSize || config.width;
35576     if(typeof size != "undefined"){
35577         this.el.setWidth(size);
35578     }
35579 };
35580 Roo.extend(Roo.EastLayoutRegion, Roo.SplitLayoutRegion, {
35581     orientation: Roo.SplitBar.HORIZONTAL,
35582     getBox : function(){
35583         if(this.collapsed){
35584             return this.collapsedEl.getBox();
35585         }
35586         var box = this.el.getBox();
35587         if(this.split){
35588             var sw = this.split.el.getWidth();
35589             box.width += sw;
35590             box.x -= sw;
35591         }
35592         return box;
35593     },
35594
35595     updateBox : function(box){
35596         if(this.split && !this.collapsed){
35597             var sw = this.split.el.getWidth();
35598             box.width -= sw;
35599             this.split.el.setLeft(box.x);
35600             this.split.el.setTop(box.y);
35601             this.split.el.setHeight(box.height);
35602             box.x += sw;
35603         }
35604         if(this.collapsed){
35605             this.updateBody(null, box.height);
35606         }
35607         Roo.LayoutRegion.prototype.updateBox.call(this, box);
35608     }
35609 });
35610
35611 Roo.WestLayoutRegion = function(mgr, config){
35612     Roo.SplitLayoutRegion.call(this, mgr, config, "west", "w-resize");
35613     if(this.split){
35614         this.split.placement = Roo.SplitBar.LEFT;
35615         this.split.orientation = Roo.SplitBar.HORIZONTAL;
35616         this.split.el.addClass("x-layout-split-h");
35617     }
35618     var size = config.initialSize || config.width;
35619     if(typeof size != "undefined"){
35620         this.el.setWidth(size);
35621     }
35622 };
35623 Roo.extend(Roo.WestLayoutRegion, Roo.SplitLayoutRegion, {
35624     orientation: Roo.SplitBar.HORIZONTAL,
35625     getBox : function(){
35626         if(this.collapsed){
35627             return this.collapsedEl.getBox();
35628         }
35629         var box = this.el.getBox();
35630         if(this.split){
35631             box.width += this.split.el.getWidth();
35632         }
35633         return box;
35634     },
35635     
35636     updateBox : function(box){
35637         if(this.split && !this.collapsed){
35638             var sw = this.split.el.getWidth();
35639             box.width -= sw;
35640             this.split.el.setLeft(box.x+box.width);
35641             this.split.el.setTop(box.y);
35642             this.split.el.setHeight(box.height);
35643         }
35644         if(this.collapsed){
35645             this.updateBody(null, box.height);
35646         }
35647         Roo.LayoutRegion.prototype.updateBox.call(this, box);
35648     }
35649 });
35650 /*
35651  * Based on:
35652  * Ext JS Library 1.1.1
35653  * Copyright(c) 2006-2007, Ext JS, LLC.
35654  *
35655  * Originally Released Under LGPL - original licence link has changed is not relivant.
35656  *
35657  * Fork - LGPL
35658  * <script type="text/javascript">
35659  */
35660  
35661  
35662 /*
35663  * Private internal class for reading and applying state
35664  */
35665 Roo.LayoutStateManager = function(layout){
35666      // default empty state
35667      this.state = {
35668         north: {},
35669         south: {},
35670         east: {},
35671         west: {}       
35672     };
35673 };
35674
35675 Roo.LayoutStateManager.prototype = {
35676     init : function(layout, provider){
35677         this.provider = provider;
35678         var state = provider.get(layout.id+"-layout-state");
35679         if(state){
35680             var wasUpdating = layout.isUpdating();
35681             if(!wasUpdating){
35682                 layout.beginUpdate();
35683             }
35684             for(var key in state){
35685                 if(typeof state[key] != "function"){
35686                     var rstate = state[key];
35687                     var r = layout.getRegion(key);
35688                     if(r && rstate){
35689                         if(rstate.size){
35690                             r.resizeTo(rstate.size);
35691                         }
35692                         if(rstate.collapsed == true){
35693                             r.collapse(true);
35694                         }else{
35695                             r.expand(null, true);
35696                         }
35697                     }
35698                 }
35699             }
35700             if(!wasUpdating){
35701                 layout.endUpdate();
35702             }
35703             this.state = state; 
35704         }
35705         this.layout = layout;
35706         layout.on("regionresized", this.onRegionResized, this);
35707         layout.on("regioncollapsed", this.onRegionCollapsed, this);
35708         layout.on("regionexpanded", this.onRegionExpanded, this);
35709     },
35710     
35711     storeState : function(){
35712         this.provider.set(this.layout.id+"-layout-state", this.state);
35713     },
35714     
35715     onRegionResized : function(region, newSize){
35716         this.state[region.getPosition()].size = newSize;
35717         this.storeState();
35718     },
35719     
35720     onRegionCollapsed : function(region){
35721         this.state[region.getPosition()].collapsed = true;
35722         this.storeState();
35723     },
35724     
35725     onRegionExpanded : function(region){
35726         this.state[region.getPosition()].collapsed = false;
35727         this.storeState();
35728     }
35729 };/*
35730  * Based on:
35731  * Ext JS Library 1.1.1
35732  * Copyright(c) 2006-2007, Ext JS, LLC.
35733  *
35734  * Originally Released Under LGPL - original licence link has changed is not relivant.
35735  *
35736  * Fork - LGPL
35737  * <script type="text/javascript">
35738  */
35739 /**
35740  * @class Roo.ContentPanel
35741  * @extends Roo.util.Observable
35742  * @children Roo.form.Form Roo.JsonView Roo.View
35743  * @parent Roo.BorderLayout Roo.LayoutDialog builder
35744  * A basic ContentPanel element.
35745  * @cfg {Boolean}   fitToFrame    True for this panel to adjust its size to fit when the region resizes  (defaults to false)
35746  * @cfg {Boolean}   fitContainer   When using {@link #fitToFrame} and {@link #resizeEl}, you can also fit the parent container  (defaults to false)
35747  * @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
35748  * @cfg {Boolean}   closable      True if the panel can be closed/removed
35749  * @cfg {Boolean}   background    True if the panel should not be activated when it is added (defaults to false)
35750  * @cfg {String|HTMLElement|Element} resizeEl An element to resize if {@link #fitToFrame} is true (instead of this panel's element)
35751  * @cfg {Roo.Toolbar}   toolbar       A toolbar for this panel
35752  * @cfg {Boolean} autoScroll    True to scroll overflow in this panel (use with {@link #fitToFrame})
35753  * @cfg {String} title          The title for this panel
35754  * @cfg {Array} adjustments     Values to <b>add</b> to the width/height when doing a {@link #fitToFrame} (default is [0, 0])
35755  * @cfg {String} url            Calls {@link #setUrl} with this value
35756  * @cfg {String} region (center|north|south|east|west) [required] which region to put this panel on (when used with xtype constructors)
35757  * @cfg {String|Object} params  When used with {@link #url}, calls {@link #setUrl} with this value
35758  * @cfg {Boolean} loadOnce      When used with {@link #url}, calls {@link #setUrl} with this value
35759  * @cfg {String}    content        Raw content to fill content panel with (uses setContent on construction.)
35760  * @cfg {String}    style  Extra style to add to the content panel
35761  * @cfg {Roo.menu.Menu} menu  popup menu
35762
35763  * @constructor
35764  * Create a new ContentPanel.
35765  * @param {String/HTMLElement/Roo.Element} el The container element for this panel
35766  * @param {String/Object} config A string to set only the title or a config object
35767  * @param {String} content (optional) Set the HTML content for this panel
35768  * @param {String} region (optional) Used by xtype constructors to add to regions. (values center,east,west,south,north)
35769  */
35770 Roo.ContentPanel = function(el, config, content){
35771     
35772      
35773     /*
35774     if(el.autoCreate || el.xtype){ // xtype is available if this is called from factory
35775         config = el;
35776         el = Roo.id();
35777     }
35778     if (config && config.parentLayout) { 
35779         el = config.parentLayout.el.createChild(); 
35780     }
35781     */
35782     if(el.autoCreate){ // xtype is available if this is called from factory
35783         config = el;
35784         el = Roo.id();
35785     }
35786     this.el = Roo.get(el);
35787     if(!this.el && config && config.autoCreate){
35788         if(typeof config.autoCreate == "object"){
35789             if(!config.autoCreate.id){
35790                 config.autoCreate.id = config.id||el;
35791             }
35792             this.el = Roo.DomHelper.append(document.body,
35793                         config.autoCreate, true);
35794         }else{
35795             this.el = Roo.DomHelper.append(document.body,
35796                         {tag: "div", cls: "x-layout-inactive-content", id: config.id||el}, true);
35797         }
35798     }
35799     
35800     
35801     this.closable = false;
35802     this.loaded = false;
35803     this.active = false;
35804     if(typeof config == "string"){
35805         this.title = config;
35806     }else{
35807         Roo.apply(this, config);
35808     }
35809     
35810     if (this.toolbar && !this.toolbar.el && this.toolbar.xtype) {
35811         this.wrapEl = this.el.wrap();
35812         this.toolbar.container = this.el.insertSibling(false, 'before');
35813         this.toolbar = new Roo.Toolbar(this.toolbar);
35814     }
35815     
35816     // xtype created footer. - not sure if will work as we normally have to render first..
35817     if (this.footer && !this.footer.el && this.footer.xtype) {
35818         if (!this.wrapEl) {
35819             this.wrapEl = this.el.wrap();
35820         }
35821     
35822         this.footer.container = this.wrapEl.createChild();
35823          
35824         this.footer = Roo.factory(this.footer, Roo);
35825         
35826     }
35827     
35828     if(this.resizeEl){
35829         this.resizeEl = Roo.get(this.resizeEl, true);
35830     }else{
35831         this.resizeEl = this.el;
35832     }
35833     // handle view.xtype
35834     
35835  
35836     
35837     
35838     this.addEvents({
35839         /**
35840          * @event activate
35841          * Fires when this panel is activated. 
35842          * @param {Roo.ContentPanel} this
35843          */
35844         "activate" : true,
35845         /**
35846          * @event deactivate
35847          * Fires when this panel is activated. 
35848          * @param {Roo.ContentPanel} this
35849          */
35850         "deactivate" : true,
35851
35852         /**
35853          * @event resize
35854          * Fires when this panel is resized if fitToFrame is true.
35855          * @param {Roo.ContentPanel} this
35856          * @param {Number} width The width after any component adjustments
35857          * @param {Number} height The height after any component adjustments
35858          */
35859         "resize" : true,
35860         
35861          /**
35862          * @event render
35863          * Fires when this tab is created
35864          * @param {Roo.ContentPanel} this
35865          */
35866         "render" : true
35867          
35868         
35869     });
35870     
35871
35872     
35873     
35874     if(this.autoScroll){
35875         this.resizeEl.setStyle("overflow", "auto");
35876     } else {
35877         // fix randome scrolling
35878         this.el.on('scroll', function() {
35879             Roo.log('fix random scolling');
35880             this.scrollTo('top',0); 
35881         });
35882     }
35883     content = content || this.content;
35884     if(content){
35885         this.setContent(content);
35886     }
35887     if(config && config.url){
35888         this.setUrl(this.url, this.params, this.loadOnce);
35889     }
35890     
35891     
35892     
35893     Roo.ContentPanel.superclass.constructor.call(this);
35894     
35895     if (this.view && typeof(this.view.xtype) != 'undefined') {
35896         this.view.el = this.el.appendChild(document.createElement("div"));
35897         this.view = Roo.factory(this.view); 
35898         this.view.render  &&  this.view.render(false, '');  
35899     }
35900     
35901     
35902     this.fireEvent('render', this);
35903 };
35904
35905 Roo.extend(Roo.ContentPanel, Roo.util.Observable, {
35906     tabTip:'',
35907     setRegion : function(region){
35908         this.region = region;
35909         if(region){
35910            this.el.replaceClass("x-layout-inactive-content", "x-layout-active-content");
35911         }else{
35912            this.el.replaceClass("x-layout-active-content", "x-layout-inactive-content");
35913         } 
35914     },
35915     
35916     /**
35917      * Returns the toolbar for this Panel if one was configured. 
35918      * @return {Roo.Toolbar} 
35919      */
35920     getToolbar : function(){
35921         return this.toolbar;
35922     },
35923     
35924     setActiveState : function(active){
35925         this.active = active;
35926         if(!active){
35927             this.fireEvent("deactivate", this);
35928         }else{
35929             this.fireEvent("activate", this);
35930         }
35931     },
35932     /**
35933      * Updates this panel's element
35934      * @param {String} content The new content
35935      * @param {Boolean} loadScripts (optional) true to look for and process scripts
35936     */
35937     setContent : function(content, loadScripts){
35938         this.el.update(content, loadScripts);
35939     },
35940
35941     ignoreResize : function(w, h){
35942         if(this.lastSize && this.lastSize.width == w && this.lastSize.height == h){
35943             return true;
35944         }else{
35945             this.lastSize = {width: w, height: h};
35946             return false;
35947         }
35948     },
35949     /**
35950      * Get the {@link Roo.UpdateManager} for this panel. Enables you to perform Ajax updates.
35951      * @return {Roo.UpdateManager} The UpdateManager
35952      */
35953     getUpdateManager : function(){
35954         return this.el.getUpdateManager();
35955     },
35956      /**
35957      * Loads this content panel immediately with content from XHR. Note: to delay loading until the panel is activated, use {@link #setUrl}.
35958      * @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:
35959 <pre><code>
35960 panel.load({
35961     url: "your-url.php",
35962     params: {param1: "foo", param2: "bar"}, // or a URL encoded string
35963     callback: yourFunction,
35964     scope: yourObject, //(optional scope)
35965     discardUrl: false,
35966     nocache: false,
35967     text: "Loading...",
35968     timeout: 30,
35969     scripts: false
35970 });
35971 </code></pre>
35972      * The only required property is <i>url</i>. The optional properties <i>nocache</i>, <i>text</i> and <i>scripts</i>
35973      * 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.
35974      * @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}
35975      * @param {Function} callback (optional) Callback when transaction is complete -- called with signature (oElement, bSuccess, oResponse)
35976      * @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.
35977      * @return {Roo.ContentPanel} this
35978      */
35979     load : function(){
35980         var um = this.el.getUpdateManager();
35981         um.update.apply(um, arguments);
35982         return this;
35983     },
35984
35985
35986     /**
35987      * 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.
35988      * @param {String/Function} url The URL to load the content from or a function to call to get the URL
35989      * @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)
35990      * @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)
35991      * @return {Roo.UpdateManager} The UpdateManager
35992      */
35993     setUrl : function(url, params, loadOnce){
35994         if(this.refreshDelegate){
35995             this.removeListener("activate", this.refreshDelegate);
35996         }
35997         this.refreshDelegate = this._handleRefresh.createDelegate(this, [url, params, loadOnce]);
35998         this.on("activate", this.refreshDelegate);
35999         return this.el.getUpdateManager();
36000     },
36001     
36002     _handleRefresh : function(url, params, loadOnce){
36003         if(!loadOnce || !this.loaded){
36004             var updater = this.el.getUpdateManager();
36005             updater.update(url, params, this._setLoaded.createDelegate(this));
36006         }
36007     },
36008     
36009     _setLoaded : function(){
36010         this.loaded = true;
36011     }, 
36012     
36013     /**
36014      * Returns this panel's id
36015      * @return {String} 
36016      */
36017     getId : function(){
36018         return this.el.id;
36019     },
36020     
36021     /** 
36022      * Returns this panel's element - used by regiosn to add.
36023      * @return {Roo.Element} 
36024      */
36025     getEl : function(){
36026         return this.wrapEl || this.el;
36027     },
36028     
36029     adjustForComponents : function(width, height)
36030     {
36031         //Roo.log('adjustForComponents ');
36032         if(this.resizeEl != this.el){
36033             width -= this.el.getFrameWidth('lr');
36034             height -= this.el.getFrameWidth('tb');
36035         }
36036         if(this.toolbar){
36037             var te = this.toolbar.getEl();
36038             height -= te.getHeight();
36039             te.setWidth(width);
36040         }
36041         if(this.footer){
36042             var te = this.footer.getEl();
36043             //Roo.log("footer:" + te.getHeight());
36044             
36045             height -= te.getHeight();
36046             te.setWidth(width);
36047         }
36048         
36049         
36050         if(this.adjustments){
36051             width += this.adjustments[0];
36052             height += this.adjustments[1];
36053         }
36054         return {"width": width, "height": height};
36055     },
36056     
36057     setSize : function(width, height){
36058         if(this.fitToFrame && !this.ignoreResize(width, height)){
36059             if(this.fitContainer && this.resizeEl != this.el){
36060                 this.el.setSize(width, height);
36061             }
36062             var size = this.adjustForComponents(width, height);
36063             this.resizeEl.setSize(this.autoWidth ? "auto" : size.width, this.autoHeight ? "auto" : size.height);
36064             this.fireEvent('resize', this, size.width, size.height);
36065         }
36066     },
36067     
36068     /**
36069      * Returns this panel's title
36070      * @return {String} 
36071      */
36072     getTitle : function(){
36073         return this.title;
36074     },
36075     
36076     /**
36077      * Set this panel's title
36078      * @param {String} title
36079      */
36080     setTitle : function(title){
36081         this.title = title;
36082         if(this.region){
36083             this.region.updatePanelTitle(this, title);
36084         }
36085     },
36086     
36087     /**
36088      * Returns true is this panel was configured to be closable
36089      * @return {Boolean} 
36090      */
36091     isClosable : function(){
36092         return this.closable;
36093     },
36094     
36095     beforeSlide : function(){
36096         this.el.clip();
36097         this.resizeEl.clip();
36098     },
36099     
36100     afterSlide : function(){
36101         this.el.unclip();
36102         this.resizeEl.unclip();
36103     },
36104     
36105     /**
36106      *   Force a content refresh from the URL specified in the {@link #setUrl} method.
36107      *   Will fail silently if the {@link #setUrl} method has not been called.
36108      *   This does not activate the panel, just updates its content.
36109      */
36110     refresh : function(){
36111         if(this.refreshDelegate){
36112            this.loaded = false;
36113            this.refreshDelegate();
36114         }
36115     },
36116     
36117     /**
36118      * Destroys this panel
36119      */
36120     destroy : function(){
36121         this.el.removeAllListeners();
36122         var tempEl = document.createElement("span");
36123         tempEl.appendChild(this.el.dom);
36124         tempEl.innerHTML = "";
36125         this.el.remove();
36126         this.el = null;
36127     },
36128     
36129     /**
36130      * form - if the content panel contains a form - this is a reference to it.
36131      * @type {Roo.form.Form}
36132      */
36133     form : false,
36134     /**
36135      * view - if the content panel contains a view (Roo.DatePicker / Roo.View / Roo.JsonView)
36136      *    This contains a reference to it.
36137      * @type {Roo.View}
36138      */
36139     view : false,
36140     
36141       /**
36142      * Adds a xtype elements to the panel - currently only supports Forms, View, JsonView.
36143      * <pre><code>
36144
36145 layout.addxtype({
36146        xtype : 'Form',
36147        items: [ .... ]
36148    }
36149 );
36150
36151 </code></pre>
36152      * @param {Object} cfg Xtype definition of item to add.
36153      */
36154     
36155     addxtype : function(cfg) {
36156         // add form..
36157         if (cfg.xtype.match(/^Form$/)) {
36158             
36159             var el;
36160             //if (this.footer) {
36161             //    el = this.footer.container.insertSibling(false, 'before');
36162             //} else {
36163                 el = this.el.createChild();
36164             //}
36165
36166             this.form = new  Roo.form.Form(cfg);
36167             
36168             
36169             if ( this.form.allItems.length) {
36170                 this.form.render(el.dom);
36171             }
36172             return this.form;
36173         }
36174         // should only have one of theses..
36175         if ([ 'View', 'JsonView', 'DatePicker'].indexOf(cfg.xtype) > -1) {
36176             // views.. should not be just added - used named prop 'view''
36177             
36178             cfg.el = this.el.appendChild(document.createElement("div"));
36179             // factory?
36180             
36181             var ret = new Roo.factory(cfg);
36182              
36183              ret.render && ret.render(false, ''); // render blank..
36184             this.view = ret;
36185             return ret;
36186         }
36187         return false;
36188     }
36189 });
36190
36191
36192
36193
36194
36195
36196
36197
36198
36199
36200
36201
36202 /**
36203  * @class Roo.GridPanel
36204  * @extends Roo.ContentPanel
36205  * @parent Roo.BorderLayout Roo.LayoutDialog builder
36206  * @constructor
36207  * Create a new GridPanel.
36208  * @cfg {Roo.grid.Grid} grid The grid for this panel
36209  */
36210 Roo.GridPanel = function(grid, config){
36211     
36212     // universal ctor...
36213     if (typeof(grid.grid) != 'undefined') {
36214         config = grid;
36215         grid = config.grid;
36216     }
36217     this.wrapper = Roo.DomHelper.append(document.body, // wrapper for IE7 strict & safari scroll issue
36218         {tag: "div", cls: "x-layout-grid-wrapper x-layout-inactive-content"}, true);
36219         
36220     this.wrapper.dom.appendChild(grid.getGridEl().dom);
36221     
36222     Roo.GridPanel.superclass.constructor.call(this, this.wrapper, config);
36223     
36224     if(this.toolbar){
36225         this.toolbar.el.insertBefore(this.wrapper.dom.firstChild);
36226     }
36227     // xtype created footer. - not sure if will work as we normally have to render first..
36228     if (this.footer && !this.footer.el && this.footer.xtype) {
36229         
36230         this.footer.container = this.grid.getView().getFooterPanel(true);
36231         this.footer.dataSource = this.grid.dataSource;
36232         this.footer = Roo.factory(this.footer, Roo);
36233         
36234     }
36235     
36236     grid.monitorWindowResize = false; // turn off autosizing
36237     grid.autoHeight = false;
36238     grid.autoWidth = false;
36239     this.grid = grid;
36240     this.grid.getGridEl().replaceClass("x-layout-inactive-content", "x-layout-component-panel");
36241 };
36242
36243 Roo.extend(Roo.GridPanel, Roo.ContentPanel, {
36244     getId : function(){
36245         return this.grid.id;
36246     },
36247     
36248     /**
36249      * Returns the grid for this panel
36250      * @return {Roo.grid.Grid} 
36251      */
36252     getGrid : function(){
36253         return this.grid;    
36254     },
36255     
36256     setSize : function(width, height){
36257         if(!this.ignoreResize(width, height)){
36258             var grid = this.grid;
36259             var size = this.adjustForComponents(width, height);
36260             grid.getGridEl().setSize(size.width, size.height);
36261             grid.autoSize();
36262         }
36263     },
36264     
36265     beforeSlide : function(){
36266         this.grid.getView().scroller.clip();
36267     },
36268     
36269     afterSlide : function(){
36270         this.grid.getView().scroller.unclip();
36271     },
36272     
36273     destroy : function(){
36274         this.grid.destroy();
36275         delete this.grid;
36276         Roo.GridPanel.superclass.destroy.call(this); 
36277     }
36278 });
36279
36280
36281 /**
36282  * @class Roo.NestedLayoutPanel
36283  * @extends Roo.ContentPanel
36284  * @parent Roo.BorderLayout Roo.LayoutDialog builder
36285  * @cfg {Roo.BorderLayout} layout   [required] The layout for this panel
36286  *
36287  * 
36288  * @constructor
36289  * Create a new NestedLayoutPanel.
36290  * 
36291  * 
36292  * @param {Roo.BorderLayout} layout [required] The layout for this panel
36293  * @param {String/Object} config A string to set only the title or a config object
36294  */
36295 Roo.NestedLayoutPanel = function(layout, config)
36296 {
36297     // construct with only one argument..
36298     /* FIXME - implement nicer consturctors
36299     if (layout.layout) {
36300         config = layout;
36301         layout = config.layout;
36302         delete config.layout;
36303     }
36304     if (layout.xtype && !layout.getEl) {
36305         // then layout needs constructing..
36306         layout = Roo.factory(layout, Roo);
36307     }
36308     */
36309     
36310     
36311     Roo.NestedLayoutPanel.superclass.constructor.call(this, layout.getEl(), config);
36312     
36313     layout.monitorWindowResize = false; // turn off autosizing
36314     this.layout = layout;
36315     this.layout.getEl().addClass("x-layout-nested-layout");
36316     
36317     
36318     
36319     
36320 };
36321
36322 Roo.extend(Roo.NestedLayoutPanel, Roo.ContentPanel, {
36323
36324     layout : false,
36325
36326     setSize : function(width, height){
36327         if(!this.ignoreResize(width, height)){
36328             var size = this.adjustForComponents(width, height);
36329             var el = this.layout.getEl();
36330             el.setSize(size.width, size.height);
36331             var touch = el.dom.offsetWidth;
36332             this.layout.layout();
36333             // ie requires a double layout on the first pass
36334             if(Roo.isIE && !this.initialized){
36335                 this.initialized = true;
36336                 this.layout.layout();
36337             }
36338         }
36339     },
36340     
36341     // activate all subpanels if not currently active..
36342     
36343     setActiveState : function(active){
36344         this.active = active;
36345         if(!active){
36346             this.fireEvent("deactivate", this);
36347             return;
36348         }
36349         
36350         this.fireEvent("activate", this);
36351         // not sure if this should happen before or after..
36352         if (!this.layout) {
36353             return; // should not happen..
36354         }
36355         var reg = false;
36356         for (var r in this.layout.regions) {
36357             reg = this.layout.getRegion(r);
36358             if (reg.getActivePanel()) {
36359                 //reg.showPanel(reg.getActivePanel()); // force it to activate.. 
36360                 reg.setActivePanel(reg.getActivePanel());
36361                 continue;
36362             }
36363             if (!reg.panels.length) {
36364                 continue;
36365             }
36366             reg.showPanel(reg.getPanel(0));
36367         }
36368         
36369         
36370         
36371         
36372     },
36373     
36374     /**
36375      * Returns the nested BorderLayout for this panel
36376      * @return {Roo.BorderLayout}
36377      */
36378     getLayout : function(){
36379         return this.layout;
36380     },
36381     
36382      /**
36383      * Adds a xtype elements to the layout of the nested panel
36384      * <pre><code>
36385
36386 panel.addxtype({
36387        xtype : 'ContentPanel',
36388        region: 'west',
36389        items: [ .... ]
36390    }
36391 );
36392
36393 panel.addxtype({
36394         xtype : 'NestedLayoutPanel',
36395         region: 'west',
36396         layout: {
36397            center: { },
36398            west: { }   
36399         },
36400         items : [ ... list of content panels or nested layout panels.. ]
36401    }
36402 );
36403 </code></pre>
36404      * @param {Object} cfg Xtype definition of item to add.
36405      */
36406     addxtype : function(cfg) {
36407         return this.layout.addxtype(cfg);
36408     
36409     }
36410 });
36411
36412 Roo.ScrollPanel = function(el, config, content){
36413     config = config || {};
36414     config.fitToFrame = true;
36415     Roo.ScrollPanel.superclass.constructor.call(this, el, config, content);
36416     
36417     this.el.dom.style.overflow = "hidden";
36418     var wrap = this.el.wrap({cls: "x-scroller x-layout-inactive-content"});
36419     this.el.removeClass("x-layout-inactive-content");
36420     this.el.on("mousewheel", this.onWheel, this);
36421
36422     var up = wrap.createChild({cls: "x-scroller-up", html: "&#160;"}, this.el.dom);
36423     var down = wrap.createChild({cls: "x-scroller-down", html: "&#160;"});
36424     up.unselectable(); down.unselectable();
36425     up.on("click", this.scrollUp, this);
36426     down.on("click", this.scrollDown, this);
36427     up.addClassOnOver("x-scroller-btn-over");
36428     down.addClassOnOver("x-scroller-btn-over");
36429     up.addClassOnClick("x-scroller-btn-click");
36430     down.addClassOnClick("x-scroller-btn-click");
36431     this.adjustments = [0, -(up.getHeight() + down.getHeight())];
36432
36433     this.resizeEl = this.el;
36434     this.el = wrap; this.up = up; this.down = down;
36435 };
36436
36437 Roo.extend(Roo.ScrollPanel, Roo.ContentPanel, {
36438     increment : 100,
36439     wheelIncrement : 5,
36440     scrollUp : function(){
36441         this.resizeEl.scroll("up", this.increment, {callback: this.afterScroll, scope: this});
36442     },
36443
36444     scrollDown : function(){
36445         this.resizeEl.scroll("down", this.increment, {callback: this.afterScroll, scope: this});
36446     },
36447
36448     afterScroll : function(){
36449         var el = this.resizeEl;
36450         var t = el.dom.scrollTop, h = el.dom.scrollHeight, ch = el.dom.clientHeight;
36451         this.up[t == 0 ? "addClass" : "removeClass"]("x-scroller-btn-disabled");
36452         this.down[h - t <= ch ? "addClass" : "removeClass"]("x-scroller-btn-disabled");
36453     },
36454
36455     setSize : function(){
36456         Roo.ScrollPanel.superclass.setSize.apply(this, arguments);
36457         this.afterScroll();
36458     },
36459
36460     onWheel : function(e){
36461         var d = e.getWheelDelta();
36462         this.resizeEl.dom.scrollTop -= (d*this.wheelIncrement);
36463         this.afterScroll();
36464         e.stopEvent();
36465     },
36466
36467     setContent : function(content, loadScripts){
36468         this.resizeEl.update(content, loadScripts);
36469     }
36470
36471 });
36472
36473
36474
36475 /**
36476  * @class Roo.TreePanel
36477  * @extends Roo.ContentPanel
36478  * @parent Roo.BorderLayout Roo.LayoutDialog builder
36479  * Treepanel component
36480  * 
36481  * @constructor
36482  * Create a new TreePanel. - defaults to fit/scoll contents.
36483  * @param {String/Object} config A string to set only the panel's title, or a config object
36484  */
36485 Roo.TreePanel = function(config){
36486     var el = config.el;
36487     var tree = config.tree;
36488     delete config.tree; 
36489     delete config.el; // hopefull!
36490     
36491     // wrapper for IE7 strict & safari scroll issue
36492     
36493     var treeEl = el.createChild();
36494     config.resizeEl = treeEl;
36495     
36496     
36497     
36498     Roo.TreePanel.superclass.constructor.call(this, el, config);
36499  
36500  
36501     this.tree = new Roo.tree.TreePanel(treeEl , tree);
36502     //console.log(tree);
36503     this.on('activate', function()
36504     {
36505         if (this.tree.rendered) {
36506             return;
36507         }
36508         //console.log('render tree');
36509         this.tree.render();
36510     });
36511     // this should not be needed.. - it's actually the 'el' that resizes?
36512     // actuall it breaks the containerScroll - dragging nodes auto scroll at top
36513     
36514     //this.on('resize',  function (cp, w, h) {
36515     //        this.tree.innerCt.setWidth(w);
36516     //        this.tree.innerCt.setHeight(h);
36517     //        //this.tree.innerCt.setStyle('overflow-y', 'auto');
36518     //});
36519
36520         
36521     
36522 };
36523
36524 Roo.extend(Roo.TreePanel, Roo.ContentPanel, {   
36525     fitToFrame : true,
36526     autoScroll : true,
36527     /*
36528      * @cfg {Roo.tree.TreePanel} tree [required] The tree TreePanel, with config etc.
36529      */
36530     tree : false
36531
36532 });
36533 /*
36534  * Based on:
36535  * Ext JS Library 1.1.1
36536  * Copyright(c) 2006-2007, Ext JS, LLC.
36537  *
36538  * Originally Released Under LGPL - original licence link has changed is not relivant.
36539  *
36540  * Fork - LGPL
36541  * <script type="text/javascript">
36542  */
36543  
36544
36545 /**
36546  * @class Roo.ReaderLayout
36547  * @extends Roo.BorderLayout
36548  * This is a pre-built layout that represents a classic, 5-pane application.  It consists of a header, a primary
36549  * center region containing two nested regions (a top one for a list view and one for item preview below),
36550  * and regions on either side that can be used for navigation, application commands, informational displays, etc.
36551  * The setup and configuration work exactly the same as it does for a {@link Roo.BorderLayout} - this class simply
36552  * expedites the setup of the overall layout and regions for this common application style.
36553  * Example:
36554  <pre><code>
36555 var reader = new Roo.ReaderLayout();
36556 var CP = Roo.ContentPanel;  // shortcut for adding
36557
36558 reader.beginUpdate();
36559 reader.add("north", new CP("north", "North"));
36560 reader.add("west", new CP("west", {title: "West"}));
36561 reader.add("east", new CP("east", {title: "East"}));
36562
36563 reader.regions.listView.add(new CP("listView", "List"));
36564 reader.regions.preview.add(new CP("preview", "Preview"));
36565 reader.endUpdate();
36566 </code></pre>
36567 * @constructor
36568 * Create a new ReaderLayout
36569 * @param {Object} config Configuration options
36570 * @param {String/HTMLElement/Element} container (optional) The container this layout is bound to (defaults to
36571 * document.body if omitted)
36572 */
36573 Roo.ReaderLayout = function(config, renderTo){
36574     var c = config || {size:{}};
36575     Roo.ReaderLayout.superclass.constructor.call(this, renderTo || document.body, {
36576         north: c.north !== false ? Roo.apply({
36577             split:false,
36578             initialSize: 32,
36579             titlebar: false
36580         }, c.north) : false,
36581         west: c.west !== false ? Roo.apply({
36582             split:true,
36583             initialSize: 200,
36584             minSize: 175,
36585             maxSize: 400,
36586             titlebar: true,
36587             collapsible: true,
36588             animate: true,
36589             margins:{left:5,right:0,bottom:5,top:5},
36590             cmargins:{left:5,right:5,bottom:5,top:5}
36591         }, c.west) : false,
36592         east: c.east !== false ? Roo.apply({
36593             split:true,
36594             initialSize: 200,
36595             minSize: 175,
36596             maxSize: 400,
36597             titlebar: true,
36598             collapsible: true,
36599             animate: true,
36600             margins:{left:0,right:5,bottom:5,top:5},
36601             cmargins:{left:5,right:5,bottom:5,top:5}
36602         }, c.east) : false,
36603         center: Roo.apply({
36604             tabPosition: 'top',
36605             autoScroll:false,
36606             closeOnTab: true,
36607             titlebar:false,
36608             margins:{left:c.west!==false ? 0 : 5,right:c.east!==false ? 0 : 5,bottom:5,top:2}
36609         }, c.center)
36610     });
36611
36612     this.el.addClass('x-reader');
36613
36614     this.beginUpdate();
36615
36616     var inner = new Roo.BorderLayout(Roo.get(document.body).createChild(), {
36617         south: c.preview !== false ? Roo.apply({
36618             split:true,
36619             initialSize: 200,
36620             minSize: 100,
36621             autoScroll:true,
36622             collapsible:true,
36623             titlebar: true,
36624             cmargins:{top:5,left:0, right:0, bottom:0}
36625         }, c.preview) : false,
36626         center: Roo.apply({
36627             autoScroll:false,
36628             titlebar:false,
36629             minHeight:200
36630         }, c.listView)
36631     });
36632     this.add('center', new Roo.NestedLayoutPanel(inner,
36633             Roo.apply({title: c.mainTitle || '',tabTip:''},c.innerPanelCfg)));
36634
36635     this.endUpdate();
36636
36637     this.regions.preview = inner.getRegion('south');
36638     this.regions.listView = inner.getRegion('center');
36639 };
36640
36641 Roo.extend(Roo.ReaderLayout, Roo.BorderLayout);/*
36642  * Based on:
36643  * Ext JS Library 1.1.1
36644  * Copyright(c) 2006-2007, Ext JS, LLC.
36645  *
36646  * Originally Released Under LGPL - original licence link has changed is not relivant.
36647  *
36648  * Fork - LGPL
36649  * <script type="text/javascript">
36650  */
36651  
36652 /**
36653  * @class Roo.grid.Grid
36654  * @extends Roo.util.Observable
36655  * This class represents the primary interface of a component based grid control.
36656  * <br><br>Usage:<pre><code>
36657  var grid = new Roo.grid.Grid("my-container-id", {
36658      ds: myDataStore,
36659      cm: myColModel,
36660      selModel: mySelectionModel,
36661      autoSizeColumns: true,
36662      monitorWindowResize: false,
36663      trackMouseOver: true
36664  });
36665  // set any options
36666  grid.render();
36667  * </code></pre>
36668  * <b>Common Problems:</b><br/>
36669  * - Grid does not resize properly when going smaller: Setting overflow hidden on the container
36670  * element will correct this<br/>
36671  * - If you get el.style[camel]= NaNpx or -2px or something related, be certain you have given your container element
36672  * dimensions. The grid adapts to your container's size, if your container has no size defined then the results
36673  * are unpredictable.<br/>
36674  * - Do not render the grid into an element with display:none. Try using visibility:hidden. Otherwise there is no way for the
36675  * grid to calculate dimensions/offsets.<br/>
36676   * @constructor
36677  * @param {String/HTMLElement/Roo.Element} container The element into which this grid will be rendered -
36678  * The container MUST have some type of size defined for the grid to fill. The container will be
36679  * automatically set to position relative if it isn't already.
36680  * @param {Object} config A config object that sets properties on this grid.
36681  */
36682 Roo.grid.Grid = function(container, config){
36683         // initialize the container
36684         this.container = Roo.get(container);
36685         this.container.update("");
36686         this.container.setStyle("overflow", "hidden");
36687     this.container.addClass('x-grid-container');
36688
36689     this.id = this.container.id;
36690
36691     Roo.apply(this, config);
36692     // check and correct shorthanded configs
36693     if(this.ds){
36694         this.dataSource = this.ds;
36695         delete this.ds;
36696     }
36697     if(this.cm){
36698         this.colModel = this.cm;
36699         delete this.cm;
36700     }
36701     if(this.sm){
36702         this.selModel = this.sm;
36703         delete this.sm;
36704     }
36705
36706     if (this.selModel) {
36707         this.selModel = Roo.factory(this.selModel, Roo.grid);
36708         this.sm = this.selModel;
36709         this.sm.xmodule = this.xmodule || false;
36710     }
36711     if (typeof(this.colModel.config) == 'undefined') {
36712         this.colModel = new Roo.grid.ColumnModel(this.colModel);
36713         this.cm = this.colModel;
36714         this.cm.xmodule = this.xmodule || false;
36715     }
36716     if (this.dataSource) {
36717         this.dataSource= Roo.factory(this.dataSource, Roo.data);
36718         this.ds = this.dataSource;
36719         this.ds.xmodule = this.xmodule || false;
36720          
36721     }
36722     
36723     
36724     
36725     if(this.width){
36726         this.container.setWidth(this.width);
36727     }
36728
36729     if(this.height){
36730         this.container.setHeight(this.height);
36731     }
36732     /** @private */
36733         this.addEvents({
36734         // raw events
36735         /**
36736          * @event click
36737          * The raw click event for the entire grid.
36738          * @param {Roo.EventObject} e
36739          */
36740         "click" : true,
36741         /**
36742          * @event dblclick
36743          * The raw dblclick event for the entire grid.
36744          * @param {Roo.EventObject} e
36745          */
36746         "dblclick" : true,
36747         /**
36748          * @event contextmenu
36749          * The raw contextmenu event for the entire grid.
36750          * @param {Roo.EventObject} e
36751          */
36752         "contextmenu" : true,
36753         /**
36754          * @event mousedown
36755          * The raw mousedown event for the entire grid.
36756          * @param {Roo.EventObject} e
36757          */
36758         "mousedown" : true,
36759         /**
36760          * @event mouseup
36761          * The raw mouseup event for the entire grid.
36762          * @param {Roo.EventObject} e
36763          */
36764         "mouseup" : true,
36765         /**
36766          * @event mouseover
36767          * The raw mouseover event for the entire grid.
36768          * @param {Roo.EventObject} e
36769          */
36770         "mouseover" : true,
36771         /**
36772          * @event mouseout
36773          * The raw mouseout event for the entire grid.
36774          * @param {Roo.EventObject} e
36775          */
36776         "mouseout" : true,
36777         /**
36778          * @event keypress
36779          * The raw keypress event for the entire grid.
36780          * @param {Roo.EventObject} e
36781          */
36782         "keypress" : true,
36783         /**
36784          * @event keydown
36785          * The raw keydown event for the entire grid.
36786          * @param {Roo.EventObject} e
36787          */
36788         "keydown" : true,
36789
36790         // custom events
36791
36792         /**
36793          * @event cellclick
36794          * Fires when a cell is clicked
36795          * @param {Grid} this
36796          * @param {Number} rowIndex
36797          * @param {Number} columnIndex
36798          * @param {Roo.EventObject} e
36799          */
36800         "cellclick" : true,
36801         /**
36802          * @event celldblclick
36803          * Fires when a cell is double clicked
36804          * @param {Grid} this
36805          * @param {Number} rowIndex
36806          * @param {Number} columnIndex
36807          * @param {Roo.EventObject} e
36808          */
36809         "celldblclick" : true,
36810         /**
36811          * @event rowclick
36812          * Fires when a row is clicked
36813          * @param {Grid} this
36814          * @param {Number} rowIndex
36815          * @param {Roo.EventObject} e
36816          */
36817         "rowclick" : true,
36818         /**
36819          * @event rowdblclick
36820          * Fires when a row is double clicked
36821          * @param {Grid} this
36822          * @param {Number} rowIndex
36823          * @param {Roo.EventObject} e
36824          */
36825         "rowdblclick" : true,
36826         /**
36827          * @event headerclick
36828          * Fires when a header is clicked
36829          * @param {Grid} this
36830          * @param {Number} columnIndex
36831          * @param {Roo.EventObject} e
36832          */
36833         "headerclick" : true,
36834         /**
36835          * @event headerdblclick
36836          * Fires when a header cell is double clicked
36837          * @param {Grid} this
36838          * @param {Number} columnIndex
36839          * @param {Roo.EventObject} e
36840          */
36841         "headerdblclick" : true,
36842         /**
36843          * @event rowcontextmenu
36844          * Fires when a row is right clicked
36845          * @param {Grid} this
36846          * @param {Number} rowIndex
36847          * @param {Roo.EventObject} e
36848          */
36849         "rowcontextmenu" : true,
36850         /**
36851          * @event cellcontextmenu
36852          * Fires when a cell is right clicked
36853          * @param {Grid} this
36854          * @param {Number} rowIndex
36855          * @param {Number} cellIndex
36856          * @param {Roo.EventObject} e
36857          */
36858          "cellcontextmenu" : true,
36859         /**
36860          * @event headercontextmenu
36861          * Fires when a header is right clicked
36862          * @param {Grid} this
36863          * @param {Number} columnIndex
36864          * @param {Roo.EventObject} e
36865          */
36866         "headercontextmenu" : true,
36867         /**
36868          * @event bodyscroll
36869          * Fires when the body element is scrolled
36870          * @param {Number} scrollLeft
36871          * @param {Number} scrollTop
36872          */
36873         "bodyscroll" : true,
36874         /**
36875          * @event columnresize
36876          * Fires when the user resizes a column
36877          * @param {Number} columnIndex
36878          * @param {Number} newSize
36879          */
36880         "columnresize" : true,
36881         /**
36882          * @event columnmove
36883          * Fires when the user moves a column
36884          * @param {Number} oldIndex
36885          * @param {Number} newIndex
36886          */
36887         "columnmove" : true,
36888         /**
36889          * @event startdrag
36890          * Fires when row(s) start being dragged
36891          * @param {Grid} this
36892          * @param {Roo.GridDD} dd The drag drop object
36893          * @param {event} e The raw browser event
36894          */
36895         "startdrag" : true,
36896         /**
36897          * @event enddrag
36898          * Fires when a drag operation is complete
36899          * @param {Grid} this
36900          * @param {Roo.GridDD} dd The drag drop object
36901          * @param {event} e The raw browser event
36902          */
36903         "enddrag" : true,
36904         /**
36905          * @event dragdrop
36906          * Fires when dragged row(s) are dropped on a valid DD target
36907          * @param {Grid} this
36908          * @param {Roo.GridDD} dd The drag drop object
36909          * @param {String} targetId The target drag drop object
36910          * @param {event} e The raw browser event
36911          */
36912         "dragdrop" : true,
36913         /**
36914          * @event dragover
36915          * Fires while row(s) are being dragged. "targetId" is the id of the Yahoo.util.DD object the selected rows are being dragged over.
36916          * @param {Grid} this
36917          * @param {Roo.GridDD} dd The drag drop object
36918          * @param {String} targetId The target drag drop object
36919          * @param {event} e The raw browser event
36920          */
36921         "dragover" : true,
36922         /**
36923          * @event dragenter
36924          *  Fires when the dragged row(s) first cross another DD target while being dragged
36925          * @param {Grid} this
36926          * @param {Roo.GridDD} dd The drag drop object
36927          * @param {String} targetId The target drag drop object
36928          * @param {event} e The raw browser event
36929          */
36930         "dragenter" : true,
36931         /**
36932          * @event dragout
36933          * Fires when the dragged row(s) leave another DD target while being dragged
36934          * @param {Grid} this
36935          * @param {Roo.GridDD} dd The drag drop object
36936          * @param {String} targetId The target drag drop object
36937          * @param {event} e The raw browser event
36938          */
36939         "dragout" : true,
36940         /**
36941          * @event rowclass
36942          * Fires when a row is rendered, so you can change add a style to it.
36943          * @param {GridView} gridview   The grid view
36944          * @param {Object} rowcfg   contains record  rowIndex and rowClass - set rowClass to add a style.
36945          */
36946         'rowclass' : true,
36947
36948         /**
36949          * @event render
36950          * Fires when the grid is rendered
36951          * @param {Grid} grid
36952          */
36953         'render' : true
36954     });
36955
36956     Roo.grid.Grid.superclass.constructor.call(this);
36957 };
36958 Roo.extend(Roo.grid.Grid, Roo.util.Observable, {
36959     
36960     /**
36961          * @cfg {Roo.grid.AbstractSelectionModel} sm The selection Model (default = Roo.grid.RowSelectionModel)
36962          */
36963         /**
36964          * @cfg {Roo.grid.GridView} view  The view that renders the grid (default = Roo.grid.GridView)
36965          */
36966         /**
36967          * @cfg {Roo.grid.ColumnModel} cm[] The columns of the grid
36968          */
36969         /**
36970          * @cfg {Roo.data.Store} ds The data store for the grid
36971          */
36972         /**
36973          * @cfg {Roo.Toolbar} toolbar a toolbar for buttons etc.
36974          */
36975         /**
36976      * @cfg {String} ddGroup - drag drop group.
36977      */
36978       /**
36979      * @cfg {String} dragGroup - drag group (?? not sure if needed.)
36980      */
36981
36982     /**
36983      * @cfg {Number} minColumnWidth The minimum width a column can be resized to. Default is 25.
36984      */
36985     minColumnWidth : 25,
36986
36987     /**
36988      * @cfg {Boolean} autoSizeColumns True to automatically resize the columns to fit their content
36989      * <b>on initial render.</b> It is more efficient to explicitly size the columns
36990      * through the ColumnModel's {@link Roo.grid.ColumnModel#width} config option.  Default is false.
36991      */
36992     autoSizeColumns : false,
36993
36994     /**
36995      * @cfg {Boolean} autoSizeHeaders True to measure headers with column data when auto sizing columns. Default is true.
36996      */
36997     autoSizeHeaders : true,
36998
36999     /**
37000      * @cfg {Boolean} monitorWindowResize True to autoSize the grid when the window resizes. Default is true.
37001      */
37002     monitorWindowResize : true,
37003
37004     /**
37005      * @cfg {Boolean} maxRowsToMeasure If autoSizeColumns is on, maxRowsToMeasure can be used to limit the number of
37006      * rows measured to get a columns size. Default is 0 (all rows).
37007      */
37008     maxRowsToMeasure : 0,
37009
37010     /**
37011      * @cfg {Boolean} trackMouseOver True to highlight rows when the mouse is over. Default is true.
37012      */
37013     trackMouseOver : true,
37014
37015     /**
37016     * @cfg {Boolean} enableDrag  True to enable drag of rows. Default is false. (double check if this is needed?)
37017     */
37018       /**
37019     * @cfg {Boolean} enableDrop  True to enable drop of elements. Default is false. (double check if this is needed?)
37020     */
37021     
37022     /**
37023     * @cfg {Boolean} enableDragDrop True to enable drag and drop of rows. Default is false.
37024     */
37025     enableDragDrop : false,
37026     
37027     /**
37028     * @cfg {Boolean} enableColumnMove True to enable drag and drop reorder of columns. Default is true.
37029     */
37030     enableColumnMove : true,
37031     
37032     /**
37033     * @cfg {Boolean} enableColumnHide True to enable hiding of columns with the header context menu. Default is true.
37034     */
37035     enableColumnHide : true,
37036     
37037     /**
37038     * @cfg {Boolean} enableRowHeightSync True to manually sync row heights across locked and not locked rows. Default is false.
37039     */
37040     enableRowHeightSync : false,
37041     
37042     /**
37043     * @cfg {Boolean} stripeRows True to stripe the rows.  Default is true.
37044     */
37045     stripeRows : true,
37046     
37047     /**
37048     * @cfg {Boolean} autoHeight True to fit the height of the grid container to the height of the data. Default is false.
37049     */
37050     autoHeight : false,
37051
37052     /**
37053      * @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.
37054      */
37055     autoExpandColumn : false,
37056
37057     /**
37058     * @cfg {Number} autoExpandMin The minimum width the autoExpandColumn can have (if enabled).
37059     * Default is 50.
37060     */
37061     autoExpandMin : 50,
37062
37063     /**
37064     * @cfg {Number} autoExpandMax The maximum width the autoExpandColumn can have (if enabled). Default is 1000.
37065     */
37066     autoExpandMax : 1000,
37067
37068     /**
37069     * @cfg {Object} view The {@link Roo.grid.GridView} used by the grid. This can be set before a call to render().
37070     */
37071     view : null,
37072
37073     /**
37074     * @cfg {Object} loadMask An {@link Roo.LoadMask} config or true to mask the grid while loading. Default is false.
37075     */
37076     loadMask : false,
37077     /**
37078     * @cfg {Roo.dd.DropTarget} dropTarget An {@link Roo.dd.DropTarget} config
37079     */
37080     dropTarget: false,
37081      /**
37082     * @cfg {boolean} sortColMenu Sort the column order menu when it shows (usefull for long lists..) default false
37083     */ 
37084     sortColMenu : false,
37085     
37086     // private
37087     rendered : false,
37088
37089     /**
37090     * @cfg {Boolean} autoWidth True to set the grid's width to the default total width of the grid's columns instead
37091     * of a fixed width. Default is false.
37092     */
37093     /**
37094     * @cfg {Number} maxHeight Sets the maximum height of the grid - ignored if autoHeight is not on.
37095     */
37096     
37097     
37098     /**
37099     * @cfg {String} ddText Configures the text is the drag proxy (defaults to "%0 selected row(s)").
37100     * %0 is replaced with the number of selected rows.
37101     */
37102     ddText : "{0} selected row{1}",
37103     
37104     
37105     /**
37106      * Called once after all setup has been completed and the grid is ready to be rendered.
37107      * @return {Roo.grid.Grid} this
37108      */
37109     render : function()
37110     {
37111         var c = this.container;
37112         // try to detect autoHeight/width mode
37113         if((!c.dom.offsetHeight || c.dom.offsetHeight < 20) || c.getStyle("height") == "auto"){
37114             this.autoHeight = true;
37115         }
37116         var view = this.getView();
37117         view.init(this);
37118
37119         c.on("click", this.onClick, this);
37120         c.on("dblclick", this.onDblClick, this);
37121         c.on("contextmenu", this.onContextMenu, this);
37122         c.on("keydown", this.onKeyDown, this);
37123         if (Roo.isTouch) {
37124             c.on("touchstart", this.onTouchStart, this);
37125         }
37126
37127         this.relayEvents(c, ["mousedown","mouseup","mouseover","mouseout","keypress"]);
37128
37129         this.getSelectionModel().init(this);
37130
37131         view.render();
37132
37133         if(this.loadMask){
37134             this.loadMask = new Roo.LoadMask(this.container,
37135                     Roo.apply({store:this.dataSource}, this.loadMask));
37136         }
37137         
37138         
37139         if (this.toolbar && this.toolbar.xtype) {
37140             this.toolbar.container = this.getView().getHeaderPanel(true);
37141             this.toolbar = new Roo.Toolbar(this.toolbar);
37142         }
37143         if (this.footer && this.footer.xtype) {
37144             this.footer.dataSource = this.getDataSource();
37145             this.footer.container = this.getView().getFooterPanel(true);
37146             this.footer = Roo.factory(this.footer, Roo);
37147         }
37148         if (this.dropTarget && this.dropTarget.xtype) {
37149             delete this.dropTarget.xtype;
37150             this.dropTarget =  new Roo.dd.DropTarget(this.getView().mainBody, this.dropTarget);
37151         }
37152         
37153         
37154         this.rendered = true;
37155         this.fireEvent('render', this);
37156         return this;
37157     },
37158
37159     /**
37160      * Reconfigures the grid to use a different Store and Column Model.
37161      * The View will be bound to the new objects and refreshed.
37162      * @param {Roo.data.Store} dataSource The new {@link Roo.data.Store} object
37163      * @param {Roo.grid.ColumnModel} The new {@link Roo.grid.ColumnModel} object
37164      */
37165     reconfigure : function(dataSource, colModel){
37166         if(this.loadMask){
37167             this.loadMask.destroy();
37168             this.loadMask = new Roo.LoadMask(this.container,
37169                     Roo.apply({store:dataSource}, this.loadMask));
37170         }
37171         this.view.bind(dataSource, colModel);
37172         this.dataSource = dataSource;
37173         this.colModel = colModel;
37174         this.view.refresh(true);
37175     },
37176     /**
37177      * addColumns
37178      * Add's a column, default at the end..
37179      
37180      * @param {int} position to add (default end)
37181      * @param {Array} of objects of column configuration see {@link Roo.grid.ColumnModel} 
37182      */
37183     addColumns : function(pos, ar)
37184     {
37185         
37186         for (var i =0;i< ar.length;i++) {
37187             var cfg = ar[i];
37188             cfg.id = typeof(cfg.id) == 'undefined' ? Roo.id() : cfg.id; // don't normally use this..
37189             this.cm.lookup[cfg.id] = cfg;
37190         }
37191         
37192         
37193         if (typeof(pos) == 'undefined' || pos >= this.cm.config.length) {
37194             pos = this.cm.config.length; //this.cm.config.push(cfg);
37195         } 
37196         pos = Math.max(0,pos);
37197         ar.unshift(0);
37198         ar.unshift(pos);
37199         this.cm.config.splice.apply(this.cm.config, ar);
37200         
37201         
37202         
37203         this.view.generateRules(this.cm);
37204         this.view.refresh(true);
37205         
37206     },
37207     
37208     
37209     
37210     
37211     // private
37212     onKeyDown : function(e){
37213         this.fireEvent("keydown", e);
37214     },
37215
37216     /**
37217      * Destroy this grid.
37218      * @param {Boolean} removeEl True to remove the element
37219      */
37220     destroy : function(removeEl, keepListeners){
37221         if(this.loadMask){
37222             this.loadMask.destroy();
37223         }
37224         var c = this.container;
37225         c.removeAllListeners();
37226         this.view.destroy();
37227         this.colModel.purgeListeners();
37228         if(!keepListeners){
37229             this.purgeListeners();
37230         }
37231         c.update("");
37232         if(removeEl === true){
37233             c.remove();
37234         }
37235     },
37236
37237     // private
37238     processEvent : function(name, e){
37239         // does this fire select???
37240         //Roo.log('grid:processEvent '  + name);
37241         
37242         if (name != 'touchstart' ) {
37243             this.fireEvent(name, e);    
37244         }
37245         
37246         var t = e.getTarget();
37247         var v = this.view;
37248         var header = v.findHeaderIndex(t);
37249         if(header !== false){
37250             var ename = name == 'touchstart' ? 'click' : name;
37251              
37252             this.fireEvent("header" + ename, this, header, e);
37253         }else{
37254             var row = v.findRowIndex(t);
37255             var cell = v.findCellIndex(t);
37256             if (name == 'touchstart') {
37257                 // first touch is always a click.
37258                 // hopefull this happens after selection is updated.?
37259                 name = false;
37260                 
37261                 if (typeof(this.selModel.getSelectedCell) != 'undefined') {
37262                     var cs = this.selModel.getSelectedCell();
37263                     if (row == cs[0] && cell == cs[1]){
37264                         name = 'dblclick';
37265                     }
37266                 }
37267                 if (typeof(this.selModel.getSelections) != 'undefined') {
37268                     var cs = this.selModel.getSelections();
37269                     var ds = this.dataSource;
37270                     if (cs.length == 1 && ds.getAt(row) == cs[0]){
37271                         name = 'dblclick';
37272                     }
37273                 }
37274                 if (!name) {
37275                     return;
37276                 }
37277             }
37278             
37279             
37280             if(row !== false){
37281                 this.fireEvent("row" + name, this, row, e);
37282                 if(cell !== false){
37283                     this.fireEvent("cell" + name, this, row, cell, e);
37284                 }
37285             }
37286         }
37287     },
37288
37289     // private
37290     onClick : function(e){
37291         this.processEvent("click", e);
37292     },
37293    // private
37294     onTouchStart : function(e){
37295         this.processEvent("touchstart", e);
37296     },
37297
37298     // private
37299     onContextMenu : function(e, t){
37300         this.processEvent("contextmenu", e);
37301     },
37302
37303     // private
37304     onDblClick : function(e){
37305         this.processEvent("dblclick", e);
37306     },
37307
37308     // private
37309     walkCells : function(row, col, step, fn, scope){
37310         var cm = this.colModel, clen = cm.getColumnCount();
37311         var ds = this.dataSource, rlen = ds.getCount(), first = true;
37312         if(step < 0){
37313             if(col < 0){
37314                 row--;
37315                 first = false;
37316             }
37317             while(row >= 0){
37318                 if(!first){
37319                     col = clen-1;
37320                 }
37321                 first = false;
37322                 while(col >= 0){
37323                     if(fn.call(scope || this, row, col, cm) === true){
37324                         return [row, col];
37325                     }
37326                     col--;
37327                 }
37328                 row--;
37329             }
37330         } else {
37331             if(col >= clen){
37332                 row++;
37333                 first = false;
37334             }
37335             while(row < rlen){
37336                 if(!first){
37337                     col = 0;
37338                 }
37339                 first = false;
37340                 while(col < clen){
37341                     if(fn.call(scope || this, row, col, cm) === true){
37342                         return [row, col];
37343                     }
37344                     col++;
37345                 }
37346                 row++;
37347             }
37348         }
37349         return null;
37350     },
37351
37352     // private
37353     getSelections : function(){
37354         return this.selModel.getSelections();
37355     },
37356
37357     /**
37358      * Causes the grid to manually recalculate its dimensions. Generally this is done automatically,
37359      * but if manual update is required this method will initiate it.
37360      */
37361     autoSize : function(){
37362         if(this.rendered){
37363             this.view.layout();
37364             if(this.view.adjustForScroll){
37365                 this.view.adjustForScroll();
37366             }
37367         }
37368     },
37369
37370     /**
37371      * Returns the grid's underlying element.
37372      * @return {Element} The element
37373      */
37374     getGridEl : function(){
37375         return this.container;
37376     },
37377
37378     // private for compatibility, overridden by editor grid
37379     stopEditing : function(){},
37380
37381     /**
37382      * Returns the grid's SelectionModel.
37383      * @return {SelectionModel}
37384      */
37385     getSelectionModel : function(){
37386         if(!this.selModel){
37387             this.selModel = new Roo.grid.RowSelectionModel();
37388         }
37389         return this.selModel;
37390     },
37391
37392     /**
37393      * Returns the grid's DataSource.
37394      * @return {DataSource}
37395      */
37396     getDataSource : function(){
37397         return this.dataSource;
37398     },
37399
37400     /**
37401      * Returns the grid's ColumnModel.
37402      * @return {ColumnModel}
37403      */
37404     getColumnModel : function(){
37405         return this.colModel;
37406     },
37407
37408     /**
37409      * Returns the grid's GridView object.
37410      * @return {GridView}
37411      */
37412     getView : function(){
37413         if(!this.view){
37414             this.view = new Roo.grid.GridView(this.viewConfig);
37415             this.relayEvents(this.view, [
37416                 "beforerowremoved", "beforerowsinserted",
37417                 "beforerefresh", "rowremoved",
37418                 "rowsinserted", "rowupdated" ,"refresh"
37419             ]);
37420         }
37421         return this.view;
37422     },
37423     /**
37424      * Called to get grid's drag proxy text, by default returns this.ddText.
37425      * Override this to put something different in the dragged text.
37426      * @return {String}
37427      */
37428     getDragDropText : function(){
37429         var count = this.selModel.getCount();
37430         return String.format(this.ddText, count, count == 1 ? '' : 's');
37431     }
37432 });
37433 /*
37434  * Based on:
37435  * Ext JS Library 1.1.1
37436  * Copyright(c) 2006-2007, Ext JS, LLC.
37437  *
37438  * Originally Released Under LGPL - original licence link has changed is not relivant.
37439  *
37440  * Fork - LGPL
37441  * <script type="text/javascript">
37442  */
37443  /**
37444  * @class Roo.grid.AbstractGridView
37445  * @extends Roo.util.Observable
37446  * @abstract
37447  * Abstract base class for grid Views
37448  * @constructor
37449  */
37450 Roo.grid.AbstractGridView = function(){
37451         this.grid = null;
37452         
37453         this.events = {
37454             "beforerowremoved" : true,
37455             "beforerowsinserted" : true,
37456             "beforerefresh" : true,
37457             "rowremoved" : true,
37458             "rowsinserted" : true,
37459             "rowupdated" : true,
37460             "refresh" : true
37461         };
37462     Roo.grid.AbstractGridView.superclass.constructor.call(this);
37463 };
37464
37465 Roo.extend(Roo.grid.AbstractGridView, Roo.util.Observable, {
37466     rowClass : "x-grid-row",
37467     cellClass : "x-grid-cell",
37468     tdClass : "x-grid-td",
37469     hdClass : "x-grid-hd",
37470     splitClass : "x-grid-hd-split",
37471     
37472     init: function(grid){
37473         this.grid = grid;
37474                 var cid = this.grid.getGridEl().id;
37475         this.colSelector = "#" + cid + " ." + this.cellClass + "-";
37476         this.tdSelector = "#" + cid + " ." + this.tdClass + "-";
37477         this.hdSelector = "#" + cid + " ." + this.hdClass + "-";
37478         this.splitSelector = "#" + cid + " ." + this.splitClass + "-";
37479         },
37480         
37481     getColumnRenderers : function(){
37482         var renderers = [];
37483         var cm = this.grid.colModel;
37484         var colCount = cm.getColumnCount();
37485         for(var i = 0; i < colCount; i++){
37486             renderers[i] = cm.getRenderer(i);
37487         }
37488         return renderers;
37489     },
37490     
37491     getColumnIds : function(){
37492         var ids = [];
37493         var cm = this.grid.colModel;
37494         var colCount = cm.getColumnCount();
37495         for(var i = 0; i < colCount; i++){
37496             ids[i] = cm.getColumnId(i);
37497         }
37498         return ids;
37499     },
37500     
37501     getDataIndexes : function(){
37502         if(!this.indexMap){
37503             this.indexMap = this.buildIndexMap();
37504         }
37505         return this.indexMap.colToData;
37506     },
37507     
37508     getColumnIndexByDataIndex : function(dataIndex){
37509         if(!this.indexMap){
37510             this.indexMap = this.buildIndexMap();
37511         }
37512         return this.indexMap.dataToCol[dataIndex];
37513     },
37514     
37515     /**
37516      * Set a css style for a column dynamically. 
37517      * @param {Number} colIndex The index of the column
37518      * @param {String} name The css property name
37519      * @param {String} value The css value
37520      */
37521     setCSSStyle : function(colIndex, name, value){
37522         var selector = "#" + this.grid.id + " .x-grid-col-" + colIndex;
37523         Roo.util.CSS.updateRule(selector, name, value);
37524     },
37525     
37526     generateRules : function(cm){
37527         var ruleBuf = [], rulesId = this.grid.id + '-cssrules';
37528         Roo.util.CSS.removeStyleSheet(rulesId);
37529         for(var i = 0, len = cm.getColumnCount(); i < len; i++){
37530             var cid = cm.getColumnId(i);
37531             ruleBuf.push(this.colSelector, cid, " {\n", cm.config[i].css, "}\n",
37532                          this.tdSelector, cid, " {\n}\n",
37533                          this.hdSelector, cid, " {\n}\n",
37534                          this.splitSelector, cid, " {\n}\n");
37535         }
37536         return Roo.util.CSS.createStyleSheet(ruleBuf.join(""), rulesId);
37537     }
37538 });/*
37539  * Based on:
37540  * Ext JS Library 1.1.1
37541  * Copyright(c) 2006-2007, Ext JS, LLC.
37542  *
37543  * Originally Released Under LGPL - original licence link has changed is not relivant.
37544  *
37545  * Fork - LGPL
37546  * <script type="text/javascript">
37547  */
37548
37549 // private
37550 // This is a support class used internally by the Grid components
37551 Roo.grid.HeaderDragZone = function(grid, hd, hd2){
37552     this.grid = grid;
37553     this.view = grid.getView();
37554     this.ddGroup = "gridHeader" + this.grid.getGridEl().id;
37555     Roo.grid.HeaderDragZone.superclass.constructor.call(this, hd);
37556     if(hd2){
37557         this.setHandleElId(Roo.id(hd));
37558         this.setOuterHandleElId(Roo.id(hd2));
37559     }
37560     this.scroll = false;
37561 };
37562 Roo.extend(Roo.grid.HeaderDragZone, Roo.dd.DragZone, {
37563     maxDragWidth: 120,
37564     getDragData : function(e){
37565         var t = Roo.lib.Event.getTarget(e);
37566         var h = this.view.findHeaderCell(t);
37567         if(h){
37568             return {ddel: h.firstChild, header:h};
37569         }
37570         return false;
37571     },
37572
37573     onInitDrag : function(e){
37574         this.view.headersDisabled = true;
37575         var clone = this.dragData.ddel.cloneNode(true);
37576         clone.id = Roo.id();
37577         clone.style.width = Math.min(this.dragData.header.offsetWidth,this.maxDragWidth) + "px";
37578         this.proxy.update(clone);
37579         return true;
37580     },
37581
37582     afterValidDrop : function(){
37583         var v = this.view;
37584         setTimeout(function(){
37585             v.headersDisabled = false;
37586         }, 50);
37587     },
37588
37589     afterInvalidDrop : function(){
37590         var v = this.view;
37591         setTimeout(function(){
37592             v.headersDisabled = false;
37593         }, 50);
37594     }
37595 });
37596 /*
37597  * Based on:
37598  * Ext JS Library 1.1.1
37599  * Copyright(c) 2006-2007, Ext JS, LLC.
37600  *
37601  * Originally Released Under LGPL - original licence link has changed is not relivant.
37602  *
37603  * Fork - LGPL
37604  * <script type="text/javascript">
37605  */
37606 // private
37607 // This is a support class used internally by the Grid components
37608 Roo.grid.HeaderDropZone = function(grid, hd, hd2){
37609     this.grid = grid;
37610     this.view = grid.getView();
37611     // split the proxies so they don't interfere with mouse events
37612     this.proxyTop = Roo.DomHelper.append(document.body, {
37613         cls:"col-move-top", html:"&#160;"
37614     }, true);
37615     this.proxyBottom = Roo.DomHelper.append(document.body, {
37616         cls:"col-move-bottom", html:"&#160;"
37617     }, true);
37618     this.proxyTop.hide = this.proxyBottom.hide = function(){
37619         this.setLeftTop(-100,-100);
37620         this.setStyle("visibility", "hidden");
37621     };
37622     this.ddGroup = "gridHeader" + this.grid.getGridEl().id;
37623     // temporarily disabled
37624     //Roo.dd.ScrollManager.register(this.view.scroller.dom);
37625     Roo.grid.HeaderDropZone.superclass.constructor.call(this, grid.getGridEl().dom);
37626 };
37627 Roo.extend(Roo.grid.HeaderDropZone, Roo.dd.DropZone, {
37628     proxyOffsets : [-4, -9],
37629     fly: Roo.Element.fly,
37630
37631     getTargetFromEvent : function(e){
37632         var t = Roo.lib.Event.getTarget(e);
37633         var cindex = this.view.findCellIndex(t);
37634         if(cindex !== false){
37635             return this.view.getHeaderCell(cindex);
37636         }
37637         return null;
37638     },
37639
37640     nextVisible : function(h){
37641         var v = this.view, cm = this.grid.colModel;
37642         h = h.nextSibling;
37643         while(h){
37644             if(!cm.isHidden(v.getCellIndex(h))){
37645                 return h;
37646             }
37647             h = h.nextSibling;
37648         }
37649         return null;
37650     },
37651
37652     prevVisible : function(h){
37653         var v = this.view, cm = this.grid.colModel;
37654         h = h.prevSibling;
37655         while(h){
37656             if(!cm.isHidden(v.getCellIndex(h))){
37657                 return h;
37658             }
37659             h = h.prevSibling;
37660         }
37661         return null;
37662     },
37663
37664     positionIndicator : function(h, n, e){
37665         var x = Roo.lib.Event.getPageX(e);
37666         var r = Roo.lib.Dom.getRegion(n.firstChild);
37667         var px, pt, py = r.top + this.proxyOffsets[1];
37668         if((r.right - x) <= (r.right-r.left)/2){
37669             px = r.right+this.view.borderWidth;
37670             pt = "after";
37671         }else{
37672             px = r.left;
37673             pt = "before";
37674         }
37675         var oldIndex = this.view.getCellIndex(h);
37676         var newIndex = this.view.getCellIndex(n);
37677
37678         if(this.grid.colModel.isFixed(newIndex)){
37679             return false;
37680         }
37681
37682         var locked = this.grid.colModel.isLocked(newIndex);
37683
37684         if(pt == "after"){
37685             newIndex++;
37686         }
37687         if(oldIndex < newIndex){
37688             newIndex--;
37689         }
37690         if(oldIndex == newIndex && (locked == this.grid.colModel.isLocked(oldIndex))){
37691             return false;
37692         }
37693         px +=  this.proxyOffsets[0];
37694         this.proxyTop.setLeftTop(px, py);
37695         this.proxyTop.show();
37696         if(!this.bottomOffset){
37697             this.bottomOffset = this.view.mainHd.getHeight();
37698         }
37699         this.proxyBottom.setLeftTop(px, py+this.proxyTop.dom.offsetHeight+this.bottomOffset);
37700         this.proxyBottom.show();
37701         return pt;
37702     },
37703
37704     onNodeEnter : function(n, dd, e, data){
37705         if(data.header != n){
37706             this.positionIndicator(data.header, n, e);
37707         }
37708     },
37709
37710     onNodeOver : function(n, dd, e, data){
37711         var result = false;
37712         if(data.header != n){
37713             result = this.positionIndicator(data.header, n, e);
37714         }
37715         if(!result){
37716             this.proxyTop.hide();
37717             this.proxyBottom.hide();
37718         }
37719         return result ? this.dropAllowed : this.dropNotAllowed;
37720     },
37721
37722     onNodeOut : function(n, dd, e, data){
37723         this.proxyTop.hide();
37724         this.proxyBottom.hide();
37725     },
37726
37727     onNodeDrop : function(n, dd, e, data){
37728         var h = data.header;
37729         if(h != n){
37730             var cm = this.grid.colModel;
37731             var x = Roo.lib.Event.getPageX(e);
37732             var r = Roo.lib.Dom.getRegion(n.firstChild);
37733             var pt = (r.right - x) <= ((r.right-r.left)/2) ? "after" : "before";
37734             var oldIndex = this.view.getCellIndex(h);
37735             var newIndex = this.view.getCellIndex(n);
37736             var locked = cm.isLocked(newIndex);
37737             if(pt == "after"){
37738                 newIndex++;
37739             }
37740             if(oldIndex < newIndex){
37741                 newIndex--;
37742             }
37743             if(oldIndex == newIndex && (locked == cm.isLocked(oldIndex))){
37744                 return false;
37745             }
37746             cm.setLocked(oldIndex, locked, true);
37747             cm.moveColumn(oldIndex, newIndex);
37748             this.grid.fireEvent("columnmove", oldIndex, newIndex);
37749             return true;
37750         }
37751         return false;
37752     }
37753 });
37754 /*
37755  * Based on:
37756  * Ext JS Library 1.1.1
37757  * Copyright(c) 2006-2007, Ext JS, LLC.
37758  *
37759  * Originally Released Under LGPL - original licence link has changed is not relivant.
37760  *
37761  * Fork - LGPL
37762  * <script type="text/javascript">
37763  */
37764   
37765 /**
37766  * @class Roo.grid.GridView
37767  * @extends Roo.util.Observable
37768  *
37769  * @constructor
37770  * @param {Object} config
37771  */
37772 Roo.grid.GridView = function(config){
37773     Roo.grid.GridView.superclass.constructor.call(this);
37774     this.el = null;
37775
37776     Roo.apply(this, config);
37777 };
37778
37779 Roo.extend(Roo.grid.GridView, Roo.grid.AbstractGridView, {
37780
37781     unselectable :  'unselectable="on"',
37782     unselectableCls :  'x-unselectable',
37783     
37784     
37785     rowClass : "x-grid-row",
37786
37787     cellClass : "x-grid-col",
37788
37789     tdClass : "x-grid-td",
37790
37791     hdClass : "x-grid-hd",
37792
37793     splitClass : "x-grid-split",
37794
37795     sortClasses : ["sort-asc", "sort-desc"],
37796
37797     enableMoveAnim : false,
37798
37799     hlColor: "C3DAF9",
37800
37801     dh : Roo.DomHelper,
37802
37803     fly : Roo.Element.fly,
37804
37805     css : Roo.util.CSS,
37806
37807     borderWidth: 1,
37808
37809     splitOffset: 3,
37810
37811     scrollIncrement : 22,
37812
37813     cellRE: /(?:.*?)x-grid-(?:hd|cell|csplit)-(?:[\d]+)-([\d]+)(?:.*?)/,
37814
37815     findRE: /\s?(?:x-grid-hd|x-grid-col|x-grid-csplit)\s/,
37816
37817     bind : function(ds, cm){
37818         if(this.ds){
37819             this.ds.un("load", this.onLoad, this);
37820             this.ds.un("datachanged", this.onDataChange, this);
37821             this.ds.un("add", this.onAdd, this);
37822             this.ds.un("remove", this.onRemove, this);
37823             this.ds.un("update", this.onUpdate, this);
37824             this.ds.un("clear", this.onClear, this);
37825         }
37826         if(ds){
37827             ds.on("load", this.onLoad, this);
37828             ds.on("datachanged", this.onDataChange, this);
37829             ds.on("add", this.onAdd, this);
37830             ds.on("remove", this.onRemove, this);
37831             ds.on("update", this.onUpdate, this);
37832             ds.on("clear", this.onClear, this);
37833         }
37834         this.ds = ds;
37835
37836         if(this.cm){
37837             this.cm.un("widthchange", this.onColWidthChange, this);
37838             this.cm.un("headerchange", this.onHeaderChange, this);
37839             this.cm.un("hiddenchange", this.onHiddenChange, this);
37840             this.cm.un("columnmoved", this.onColumnMove, this);
37841             this.cm.un("columnlockchange", this.onColumnLock, this);
37842         }
37843         if(cm){
37844             this.generateRules(cm);
37845             cm.on("widthchange", this.onColWidthChange, this);
37846             cm.on("headerchange", this.onHeaderChange, this);
37847             cm.on("hiddenchange", this.onHiddenChange, this);
37848             cm.on("columnmoved", this.onColumnMove, this);
37849             cm.on("columnlockchange", this.onColumnLock, this);
37850         }
37851         this.cm = cm;
37852     },
37853
37854     init: function(grid){
37855         Roo.grid.GridView.superclass.init.call(this, grid);
37856
37857         this.bind(grid.dataSource, grid.colModel);
37858
37859         grid.on("headerclick", this.handleHeaderClick, this);
37860
37861         if(grid.trackMouseOver){
37862             grid.on("mouseover", this.onRowOver, this);
37863             grid.on("mouseout", this.onRowOut, this);
37864         }
37865         grid.cancelTextSelection = function(){};
37866         this.gridId = grid.id;
37867
37868         var tpls = this.templates || {};
37869
37870         if(!tpls.master){
37871             tpls.master = new Roo.Template(
37872                '<div class="x-grid" hidefocus="true">',
37873                 '<a href="#" class="x-grid-focus" tabIndex="-1"></a>',
37874                   '<div class="x-grid-topbar"></div>',
37875                   '<div class="x-grid-scroller"><div></div></div>',
37876                   '<div class="x-grid-locked">',
37877                       '<div class="x-grid-header">{lockedHeader}</div>',
37878                       '<div class="x-grid-body">{lockedBody}</div>',
37879                   "</div>",
37880                   '<div class="x-grid-viewport">',
37881                       '<div class="x-grid-header">{header}</div>',
37882                       '<div class="x-grid-body">{body}</div>',
37883                   "</div>",
37884                   '<div class="x-grid-bottombar"></div>',
37885                  
37886                   '<div class="x-grid-resize-proxy">&#160;</div>',
37887                "</div>"
37888             );
37889             tpls.master.disableformats = true;
37890         }
37891
37892         if(!tpls.header){
37893             tpls.header = new Roo.Template(
37894                '<table border="0" cellspacing="0" cellpadding="0">',
37895                '<tbody><tr class="x-grid-hd-row">{cells}</tr></tbody>',
37896                "</table>{splits}"
37897             );
37898             tpls.header.disableformats = true;
37899         }
37900         tpls.header.compile();
37901
37902         if(!tpls.hcell){
37903             tpls.hcell = new Roo.Template(
37904                 '<td class="x-grid-hd x-grid-td-{id} {cellId}"><div title="{title}" class="x-grid-hd-inner x-grid-hd-{id}">',
37905                 '<div class="x-grid-hd-text ' + this.unselectableCls +  '" ' + this.unselectable +'>{value}<img class="x-grid-sort-icon" src="', Roo.BLANK_IMAGE_URL, '" /></div>',
37906                 "</div></td>"
37907              );
37908              tpls.hcell.disableFormats = true;
37909         }
37910         tpls.hcell.compile();
37911
37912         if(!tpls.hsplit){
37913             tpls.hsplit = new Roo.Template('<div class="x-grid-split {splitId} x-grid-split-{id}" style="{style} ' +
37914                                             this.unselectableCls +  '" ' + this.unselectable +'>&#160;</div>');
37915             tpls.hsplit.disableFormats = true;
37916         }
37917         tpls.hsplit.compile();
37918
37919         if(!tpls.body){
37920             tpls.body = new Roo.Template(
37921                '<table border="0" cellspacing="0" cellpadding="0">',
37922                "<tbody>{rows}</tbody>",
37923                "</table>"
37924             );
37925             tpls.body.disableFormats = true;
37926         }
37927         tpls.body.compile();
37928
37929         if(!tpls.row){
37930             tpls.row = new Roo.Template('<tr class="x-grid-row {alt}">{cells}</tr>');
37931             tpls.row.disableFormats = true;
37932         }
37933         tpls.row.compile();
37934
37935         if(!tpls.cell){
37936             tpls.cell = new Roo.Template(
37937                 '<td class="x-grid-col x-grid-td-{id} {cellId} {css}" tabIndex="0">',
37938                 '<div class="x-grid-col-{id} x-grid-cell-inner"><div class="x-grid-cell-text ' +
37939                     this.unselectableCls +  '" ' + this.unselectable +'" {attr}>{value}</div></div>',
37940                 "</td>"
37941             );
37942             tpls.cell.disableFormats = true;
37943         }
37944         tpls.cell.compile();
37945
37946         this.templates = tpls;
37947     },
37948
37949     // remap these for backwards compat
37950     onColWidthChange : function(){
37951         this.updateColumns.apply(this, arguments);
37952     },
37953     onHeaderChange : function(){
37954         this.updateHeaders.apply(this, arguments);
37955     }, 
37956     onHiddenChange : function(){
37957         this.handleHiddenChange.apply(this, arguments);
37958     },
37959     onColumnMove : function(){
37960         this.handleColumnMove.apply(this, arguments);
37961     },
37962     onColumnLock : function(){
37963         this.handleLockChange.apply(this, arguments);
37964     },
37965
37966     onDataChange : function(){
37967         this.refresh();
37968         this.updateHeaderSortState();
37969     },
37970
37971     onClear : function(){
37972         this.refresh();
37973     },
37974
37975     onUpdate : function(ds, record){
37976         this.refreshRow(record);
37977     },
37978
37979     refreshRow : function(record){
37980         var ds = this.ds, index;
37981         if(typeof record == 'number'){
37982             index = record;
37983             record = ds.getAt(index);
37984         }else{
37985             index = ds.indexOf(record);
37986         }
37987         this.insertRows(ds, index, index, true);
37988         this.onRemove(ds, record, index+1, true);
37989         this.syncRowHeights(index, index);
37990         this.layout();
37991         this.fireEvent("rowupdated", this, index, record);
37992     },
37993
37994     onAdd : function(ds, records, index){
37995         this.insertRows(ds, index, index + (records.length-1));
37996     },
37997
37998     onRemove : function(ds, record, index, isUpdate){
37999         if(isUpdate !== true){
38000             this.fireEvent("beforerowremoved", this, index, record);
38001         }
38002         var bt = this.getBodyTable(), lt = this.getLockedTable();
38003         if(bt.rows[index]){
38004             bt.firstChild.removeChild(bt.rows[index]);
38005         }
38006         if(lt.rows[index]){
38007             lt.firstChild.removeChild(lt.rows[index]);
38008         }
38009         if(isUpdate !== true){
38010             this.stripeRows(index);
38011             this.syncRowHeights(index, index);
38012             this.layout();
38013             this.fireEvent("rowremoved", this, index, record);
38014         }
38015     },
38016
38017     onLoad : function(){
38018         this.scrollToTop();
38019     },
38020
38021     /**
38022      * Scrolls the grid to the top
38023      */
38024     scrollToTop : function(){
38025         if(this.scroller){
38026             this.scroller.dom.scrollTop = 0;
38027             this.syncScroll();
38028         }
38029     },
38030
38031     /**
38032      * Gets a panel in the header of the grid that can be used for toolbars etc.
38033      * After modifying the contents of this panel a call to grid.autoSize() may be
38034      * required to register any changes in size.
38035      * @param {Boolean} doShow By default the header is hidden. Pass true to show the panel
38036      * @return Roo.Element
38037      */
38038     getHeaderPanel : function(doShow){
38039         if(doShow){
38040             this.headerPanel.show();
38041         }
38042         return this.headerPanel;
38043     },
38044
38045     /**
38046      * Gets a panel in the footer of the grid that can be used for toolbars etc.
38047      * After modifying the contents of this panel a call to grid.autoSize() may be
38048      * required to register any changes in size.
38049      * @param {Boolean} doShow By default the footer is hidden. Pass true to show the panel
38050      * @return Roo.Element
38051      */
38052     getFooterPanel : function(doShow){
38053         if(doShow){
38054             this.footerPanel.show();
38055         }
38056         return this.footerPanel;
38057     },
38058
38059     initElements : function(){
38060         var E = Roo.Element;
38061         var el = this.grid.getGridEl().dom.firstChild;
38062         var cs = el.childNodes;
38063
38064         this.el = new E(el);
38065         
38066          this.focusEl = new E(el.firstChild);
38067         this.focusEl.swallowEvent("click", true);
38068         
38069         this.headerPanel = new E(cs[1]);
38070         this.headerPanel.enableDisplayMode("block");
38071
38072         this.scroller = new E(cs[2]);
38073         this.scrollSizer = new E(this.scroller.dom.firstChild);
38074
38075         this.lockedWrap = new E(cs[3]);
38076         this.lockedHd = new E(this.lockedWrap.dom.firstChild);
38077         this.lockedBody = new E(this.lockedWrap.dom.childNodes[1]);
38078
38079         this.mainWrap = new E(cs[4]);
38080         this.mainHd = new E(this.mainWrap.dom.firstChild);
38081         this.mainBody = new E(this.mainWrap.dom.childNodes[1]);
38082
38083         this.footerPanel = new E(cs[5]);
38084         this.footerPanel.enableDisplayMode("block");
38085
38086         this.resizeProxy = new E(cs[6]);
38087
38088         this.headerSelector = String.format(
38089            '#{0} td.x-grid-hd, #{1} td.x-grid-hd',
38090            this.lockedHd.id, this.mainHd.id
38091         );
38092
38093         this.splitterSelector = String.format(
38094            '#{0} div.x-grid-split, #{1} div.x-grid-split',
38095            this.idToCssName(this.lockedHd.id), this.idToCssName(this.mainHd.id)
38096         );
38097     },
38098     idToCssName : function(s)
38099     {
38100         return s.replace(/[^a-z0-9]+/ig, '-');
38101     },
38102
38103     getHeaderCell : function(index){
38104         return Roo.DomQuery.select(this.headerSelector)[index];
38105     },
38106
38107     getHeaderCellMeasure : function(index){
38108         return this.getHeaderCell(index).firstChild;
38109     },
38110
38111     getHeaderCellText : function(index){
38112         return this.getHeaderCell(index).firstChild.firstChild;
38113     },
38114
38115     getLockedTable : function(){
38116         return this.lockedBody.dom.firstChild;
38117     },
38118
38119     getBodyTable : function(){
38120         return this.mainBody.dom.firstChild;
38121     },
38122
38123     getLockedRow : function(index){
38124         return this.getLockedTable().rows[index];
38125     },
38126
38127     getRow : function(index){
38128         return this.getBodyTable().rows[index];
38129     },
38130
38131     getRowComposite : function(index){
38132         if(!this.rowEl){
38133             this.rowEl = new Roo.CompositeElementLite();
38134         }
38135         var els = [], lrow, mrow;
38136         if(lrow = this.getLockedRow(index)){
38137             els.push(lrow);
38138         }
38139         if(mrow = this.getRow(index)){
38140             els.push(mrow);
38141         }
38142         this.rowEl.elements = els;
38143         return this.rowEl;
38144     },
38145     /**
38146      * Gets the 'td' of the cell
38147      * 
38148      * @param {Integer} rowIndex row to select
38149      * @param {Integer} colIndex column to select
38150      * 
38151      * @return {Object} 
38152      */
38153     getCell : function(rowIndex, colIndex){
38154         var locked = this.cm.getLockedCount();
38155         var source;
38156         if(colIndex < locked){
38157             source = this.lockedBody.dom.firstChild;
38158         }else{
38159             source = this.mainBody.dom.firstChild;
38160             colIndex -= locked;
38161         }
38162         return source.rows[rowIndex].childNodes[colIndex];
38163     },
38164
38165     getCellText : function(rowIndex, colIndex){
38166         return this.getCell(rowIndex, colIndex).firstChild.firstChild;
38167     },
38168
38169     getCellBox : function(cell){
38170         var b = this.fly(cell).getBox();
38171         if(Roo.isOpera){ // opera fails to report the Y
38172             b.y = cell.offsetTop + this.mainBody.getY();
38173         }
38174         return b;
38175     },
38176
38177     getCellIndex : function(cell){
38178         var id = String(cell.className).match(this.cellRE);
38179         if(id){
38180             return parseInt(id[1], 10);
38181         }
38182         return 0;
38183     },
38184
38185     findHeaderIndex : function(n){
38186         var r = Roo.fly(n).findParent("td." + this.hdClass, 6);
38187         return r ? this.getCellIndex(r) : false;
38188     },
38189
38190     findHeaderCell : function(n){
38191         var r = Roo.fly(n).findParent("td." + this.hdClass, 6);
38192         return r ? r : false;
38193     },
38194
38195     findRowIndex : function(n){
38196         if(!n){
38197             return false;
38198         }
38199         var r = Roo.fly(n).findParent("tr." + this.rowClass, 6);
38200         return r ? r.rowIndex : false;
38201     },
38202
38203     findCellIndex : function(node){
38204         var stop = this.el.dom;
38205         while(node && node != stop){
38206             if(this.findRE.test(node.className)){
38207                 return this.getCellIndex(node);
38208             }
38209             node = node.parentNode;
38210         }
38211         return false;
38212     },
38213
38214     getColumnId : function(index){
38215         return this.cm.getColumnId(index);
38216     },
38217
38218     getSplitters : function()
38219     {
38220         if(this.splitterSelector){
38221            return Roo.DomQuery.select(this.splitterSelector);
38222         }else{
38223             return null;
38224       }
38225     },
38226
38227     getSplitter : function(index){
38228         return this.getSplitters()[index];
38229     },
38230
38231     onRowOver : function(e, t){
38232         var row;
38233         if((row = this.findRowIndex(t)) !== false){
38234             this.getRowComposite(row).addClass("x-grid-row-over");
38235         }
38236     },
38237
38238     onRowOut : function(e, t){
38239         var row;
38240         if((row = this.findRowIndex(t)) !== false && row !== this.findRowIndex(e.getRelatedTarget())){
38241             this.getRowComposite(row).removeClass("x-grid-row-over");
38242         }
38243     },
38244
38245     renderHeaders : function(){
38246         var cm = this.cm;
38247         var ct = this.templates.hcell, ht = this.templates.header, st = this.templates.hsplit;
38248         var cb = [], lb = [], sb = [], lsb = [], p = {};
38249         for(var i = 0, len = cm.getColumnCount(); i < len; i++){
38250             p.cellId = "x-grid-hd-0-" + i;
38251             p.splitId = "x-grid-csplit-0-" + i;
38252             p.id = cm.getColumnId(i);
38253             p.value = cm.getColumnHeader(i) || "";
38254             p.title = cm.getColumnTooltip(i) || (''+p.value).match(/\</)  ? '' :  p.value  || "";
38255             p.style = (this.grid.enableColumnResize === false || !cm.isResizable(i) || cm.isFixed(i)) ? 'cursor:default' : '';
38256             if(!cm.isLocked(i)){
38257                 cb[cb.length] = ct.apply(p);
38258                 sb[sb.length] = st.apply(p);
38259             }else{
38260                 lb[lb.length] = ct.apply(p);
38261                 lsb[lsb.length] = st.apply(p);
38262             }
38263         }
38264         return [ht.apply({cells: lb.join(""), splits:lsb.join("")}),
38265                 ht.apply({cells: cb.join(""), splits:sb.join("")})];
38266     },
38267
38268     updateHeaders : function(){
38269         var html = this.renderHeaders();
38270         this.lockedHd.update(html[0]);
38271         this.mainHd.update(html[1]);
38272     },
38273
38274     /**
38275      * Focuses the specified row.
38276      * @param {Number} row The row index
38277      */
38278     focusRow : function(row)
38279     {
38280         //Roo.log('GridView.focusRow');
38281         var x = this.scroller.dom.scrollLeft;
38282         this.focusCell(row, 0, false);
38283         this.scroller.dom.scrollLeft = x;
38284     },
38285
38286     /**
38287      * Focuses the specified cell.
38288      * @param {Number} row The row index
38289      * @param {Number} col The column index
38290      * @param {Boolean} hscroll false to disable horizontal scrolling
38291      */
38292     focusCell : function(row, col, hscroll)
38293     {
38294         //Roo.log('GridView.focusCell');
38295         var el = this.ensureVisible(row, col, hscroll);
38296         this.focusEl.alignTo(el, "tl-tl");
38297         if(Roo.isGecko){
38298             this.focusEl.focus();
38299         }else{
38300             this.focusEl.focus.defer(1, this.focusEl);
38301         }
38302     },
38303
38304     /**
38305      * Scrolls the specified cell into view
38306      * @param {Number} row The row index
38307      * @param {Number} col The column index
38308      * @param {Boolean} hscroll false to disable horizontal scrolling
38309      */
38310     ensureVisible : function(row, col, hscroll)
38311     {
38312         //Roo.log('GridView.ensureVisible,' + row + ',' + col);
38313         //return null; //disable for testing.
38314         if(typeof row != "number"){
38315             row = row.rowIndex;
38316         }
38317         if(row < 0 && row >= this.ds.getCount()){
38318             return  null;
38319         }
38320         col = (col !== undefined ? col : 0);
38321         var cm = this.grid.colModel;
38322         while(cm.isHidden(col)){
38323             col++;
38324         }
38325
38326         var el = this.getCell(row, col);
38327         if(!el){
38328             return null;
38329         }
38330         var c = this.scroller.dom;
38331
38332         var ctop = parseInt(el.offsetTop, 10);
38333         var cleft = parseInt(el.offsetLeft, 10);
38334         var cbot = ctop + el.offsetHeight;
38335         var cright = cleft + el.offsetWidth;
38336         
38337         var ch = c.clientHeight - this.mainHd.dom.offsetHeight;
38338         var stop = parseInt(c.scrollTop, 10);
38339         var sleft = parseInt(c.scrollLeft, 10);
38340         var sbot = stop + ch;
38341         var sright = sleft + c.clientWidth;
38342         /*
38343         Roo.log('GridView.ensureVisible:' +
38344                 ' ctop:' + ctop +
38345                 ' c.clientHeight:' + c.clientHeight +
38346                 ' this.mainHd.dom.offsetHeight:' + this.mainHd.dom.offsetHeight +
38347                 ' stop:' + stop +
38348                 ' cbot:' + cbot +
38349                 ' sbot:' + sbot +
38350                 ' ch:' + ch  
38351                 );
38352         */
38353         if(ctop < stop){
38354             c.scrollTop = ctop;
38355             //Roo.log("set scrolltop to ctop DISABLE?");
38356         }else if(cbot > sbot){
38357             //Roo.log("set scrolltop to cbot-ch");
38358             c.scrollTop = cbot-ch;
38359         }
38360         
38361         if(hscroll !== false){
38362             if(cleft < sleft){
38363                 c.scrollLeft = cleft;
38364             }else if(cright > sright){
38365                 c.scrollLeft = cright-c.clientWidth;
38366             }
38367         }
38368          
38369         return el;
38370     },
38371
38372     updateColumns : function(){
38373         this.grid.stopEditing();
38374         var cm = this.grid.colModel, colIds = this.getColumnIds();
38375         //var totalWidth = cm.getTotalWidth();
38376         var pos = 0;
38377         for(var i = 0, len = cm.getColumnCount(); i < len; i++){
38378             //if(cm.isHidden(i)) continue;
38379             var w = cm.getColumnWidth(i);
38380             this.css.updateRule(this.colSelector+this.idToCssName(colIds[i]), "width", (w - this.borderWidth) + "px");
38381             this.css.updateRule(this.hdSelector+this.idToCssName(colIds[i]), "width", (w - this.borderWidth) + "px");
38382         }
38383         this.updateSplitters();
38384     },
38385
38386     generateRules : function(cm){
38387         var ruleBuf = [], rulesId = this.idToCssName(this.grid.id)+ '-cssrules';
38388         Roo.util.CSS.removeStyleSheet(rulesId);
38389         for(var i = 0, len = cm.getColumnCount(); i < len; i++){
38390             var cid = cm.getColumnId(i);
38391             var align = '';
38392             if(cm.config[i].align){
38393                 align = 'text-align:'+cm.config[i].align+';';
38394             }
38395             var hidden = '';
38396             if(cm.isHidden(i)){
38397                 hidden = 'display:none;';
38398             }
38399             var width = "width:" + (cm.getColumnWidth(i) - this.borderWidth) + "px;";
38400             ruleBuf.push(
38401                     this.colSelector, cid, " {\n", cm.config[i].css, align, width, "\n}\n",
38402                     this.hdSelector, cid, " {\n", align, width, "}\n",
38403                     this.tdSelector, cid, " {\n",hidden,"\n}\n",
38404                     this.splitSelector, cid, " {\n", hidden , "\n}\n");
38405         }
38406         return Roo.util.CSS.createStyleSheet(ruleBuf.join(""), rulesId);
38407     },
38408
38409     updateSplitters : function(){
38410         var cm = this.cm, s = this.getSplitters();
38411         if(s){ // splitters not created yet
38412             var pos = 0, locked = true;
38413             for(var i = 0, len = cm.getColumnCount(); i < len; i++){
38414                 if(cm.isHidden(i)) {
38415                     continue;
38416                 }
38417                 var w = cm.getColumnWidth(i); // make sure it's a number
38418                 if(!cm.isLocked(i) && locked){
38419                     pos = 0;
38420                     locked = false;
38421                 }
38422                 pos += w;
38423                 s[i].style.left = (pos-this.splitOffset) + "px";
38424             }
38425         }
38426     },
38427
38428     handleHiddenChange : function(colModel, colIndex, hidden){
38429         if(hidden){
38430             this.hideColumn(colIndex);
38431         }else{
38432             this.unhideColumn(colIndex);
38433         }
38434     },
38435
38436     hideColumn : function(colIndex){
38437         var cid = this.getColumnId(colIndex);
38438         this.css.updateRule(this.tdSelector+this.idToCssName(cid), "display", "none");
38439         this.css.updateRule(this.splitSelector+this.idToCssName(cid), "display", "none");
38440         if(Roo.isSafari){
38441             this.updateHeaders();
38442         }
38443         this.updateSplitters();
38444         this.layout();
38445     },
38446
38447     unhideColumn : function(colIndex){
38448         var cid = this.getColumnId(colIndex);
38449         this.css.updateRule(this.tdSelector+this.idToCssName(cid), "display", "");
38450         this.css.updateRule(this.splitSelector+this.idToCssName(cid), "display", "");
38451
38452         if(Roo.isSafari){
38453             this.updateHeaders();
38454         }
38455         this.updateSplitters();
38456         this.layout();
38457     },
38458
38459     insertRows : function(dm, firstRow, lastRow, isUpdate){
38460         if(firstRow == 0 && lastRow == dm.getCount()-1){
38461             this.refresh();
38462         }else{
38463             if(!isUpdate){
38464                 this.fireEvent("beforerowsinserted", this, firstRow, lastRow);
38465             }
38466             var s = this.getScrollState();
38467             var markup = this.renderRows(firstRow, lastRow);
38468             this.bufferRows(markup[0], this.getLockedTable(), firstRow);
38469             this.bufferRows(markup[1], this.getBodyTable(), firstRow);
38470             this.restoreScroll(s);
38471             if(!isUpdate){
38472                 this.fireEvent("rowsinserted", this, firstRow, lastRow);
38473                 this.syncRowHeights(firstRow, lastRow);
38474                 this.stripeRows(firstRow);
38475                 this.layout();
38476             }
38477         }
38478     },
38479
38480     bufferRows : function(markup, target, index){
38481         var before = null, trows = target.rows, tbody = target.tBodies[0];
38482         if(index < trows.length){
38483             before = trows[index];
38484         }
38485         var b = document.createElement("div");
38486         b.innerHTML = "<table><tbody>"+markup+"</tbody></table>";
38487         var rows = b.firstChild.rows;
38488         for(var i = 0, len = rows.length; i < len; i++){
38489             if(before){
38490                 tbody.insertBefore(rows[0], before);
38491             }else{
38492                 tbody.appendChild(rows[0]);
38493             }
38494         }
38495         b.innerHTML = "";
38496         b = null;
38497     },
38498
38499     deleteRows : function(dm, firstRow, lastRow){
38500         if(dm.getRowCount()<1){
38501             this.fireEvent("beforerefresh", this);
38502             this.mainBody.update("");
38503             this.lockedBody.update("");
38504             this.fireEvent("refresh", this);
38505         }else{
38506             this.fireEvent("beforerowsdeleted", this, firstRow, lastRow);
38507             var bt = this.getBodyTable();
38508             var tbody = bt.firstChild;
38509             var rows = bt.rows;
38510             for(var rowIndex = firstRow; rowIndex <= lastRow; rowIndex++){
38511                 tbody.removeChild(rows[firstRow]);
38512             }
38513             this.stripeRows(firstRow);
38514             this.fireEvent("rowsdeleted", this, firstRow, lastRow);
38515         }
38516     },
38517
38518     updateRows : function(dataSource, firstRow, lastRow){
38519         var s = this.getScrollState();
38520         this.refresh();
38521         this.restoreScroll(s);
38522     },
38523
38524     handleSort : function(dataSource, sortColumnIndex, sortDir, noRefresh){
38525         if(!noRefresh){
38526            this.refresh();
38527         }
38528         this.updateHeaderSortState();
38529     },
38530
38531     getScrollState : function(){
38532         
38533         var sb = this.scroller.dom;
38534         return {left: sb.scrollLeft, top: sb.scrollTop};
38535     },
38536
38537     stripeRows : function(startRow){
38538         if(!this.grid.stripeRows || this.ds.getCount() < 1){
38539             return;
38540         }
38541         startRow = startRow || 0;
38542         var rows = this.getBodyTable().rows;
38543         var lrows = this.getLockedTable().rows;
38544         var cls = ' x-grid-row-alt ';
38545         for(var i = startRow, len = rows.length; i < len; i++){
38546             var row = rows[i], lrow = lrows[i];
38547             var isAlt = ((i+1) % 2 == 0);
38548             var hasAlt = (' '+row.className + ' ').indexOf(cls) != -1;
38549             if(isAlt == hasAlt){
38550                 continue;
38551             }
38552             if(isAlt){
38553                 row.className += " x-grid-row-alt";
38554             }else{
38555                 row.className = row.className.replace("x-grid-row-alt", "");
38556             }
38557             if(lrow){
38558                 lrow.className = row.className;
38559             }
38560         }
38561     },
38562
38563     restoreScroll : function(state){
38564         //Roo.log('GridView.restoreScroll');
38565         var sb = this.scroller.dom;
38566         sb.scrollLeft = state.left;
38567         sb.scrollTop = state.top;
38568         this.syncScroll();
38569     },
38570
38571     syncScroll : function(){
38572         //Roo.log('GridView.syncScroll');
38573         var sb = this.scroller.dom;
38574         var sh = this.mainHd.dom;
38575         var bs = this.mainBody.dom;
38576         var lv = this.lockedBody.dom;
38577         sh.scrollLeft = bs.scrollLeft = sb.scrollLeft;
38578         lv.scrollTop = bs.scrollTop = sb.scrollTop;
38579     },
38580
38581     handleScroll : function(e){
38582         this.syncScroll();
38583         var sb = this.scroller.dom;
38584         this.grid.fireEvent("bodyscroll", sb.scrollLeft, sb.scrollTop);
38585         e.stopEvent();
38586     },
38587
38588     handleWheel : function(e){
38589         var d = e.getWheelDelta();
38590         this.scroller.dom.scrollTop -= d*22;
38591         // set this here to prevent jumpy scrolling on large tables
38592         this.lockedBody.dom.scrollTop = this.mainBody.dom.scrollTop = this.scroller.dom.scrollTop;
38593         e.stopEvent();
38594     },
38595
38596     renderRows : function(startRow, endRow){
38597         // pull in all the crap needed to render rows
38598         var g = this.grid, cm = g.colModel, ds = g.dataSource, stripe = g.stripeRows;
38599         var colCount = cm.getColumnCount();
38600
38601         if(ds.getCount() < 1){
38602             return ["", ""];
38603         }
38604
38605         // build a map for all the columns
38606         var cs = [];
38607         for(var i = 0; i < colCount; i++){
38608             var name = cm.getDataIndex(i);
38609             cs[i] = {
38610                 name : typeof name == 'undefined' ? ds.fields.get(i).name : name,
38611                 renderer : cm.getRenderer(i),
38612                 id : cm.getColumnId(i),
38613                 locked : cm.isLocked(i),
38614                 has_editor : cm.isCellEditable(i)
38615             };
38616         }
38617
38618         startRow = startRow || 0;
38619         endRow = typeof endRow == "undefined"? ds.getCount()-1 : endRow;
38620
38621         // records to render
38622         var rs = ds.getRange(startRow, endRow);
38623
38624         return this.doRender(cs, rs, ds, startRow, colCount, stripe);
38625     },
38626
38627     // As much as I hate to duplicate code, this was branched because FireFox really hates
38628     // [].join("") on strings. The performance difference was substantial enough to
38629     // branch this function
38630     doRender : Roo.isGecko ?
38631             function(cs, rs, ds, startRow, colCount, stripe){
38632                 var ts = this.templates, ct = ts.cell, rt = ts.row;
38633                 // buffers
38634                 var buf = "", lbuf = "", cb, lcb, c, p = {}, rp = {}, r, rowIndex;
38635                 
38636                 var hasListener = this.grid.hasListener('rowclass');
38637                 var rowcfg = {};
38638                 for(var j = 0, len = rs.length; j < len; j++){
38639                     r = rs[j]; cb = ""; lcb = ""; rowIndex = (j+startRow);
38640                     for(var i = 0; i < colCount; i++){
38641                         c = cs[i];
38642                         p.cellId = "x-grid-cell-" + rowIndex + "-" + i;
38643                         p.id = c.id;
38644                         p.css = p.attr = "";
38645                         p.value = c.renderer(r.data[c.name], p, r, rowIndex, i, ds);
38646                         if(p.value == undefined || p.value === "") {
38647                             p.value = "&#160;";
38648                         }
38649                         if(c.has_editor){
38650                             p.css += ' x-grid-editable-cell';
38651                         }
38652                         if(c.dirty && typeof r.modified[c.name] !== 'undefined'){
38653                             p.css +=  ' x-grid-dirty-cell';
38654                         }
38655                         var markup = ct.apply(p);
38656                         if(!c.locked){
38657                             cb+= markup;
38658                         }else{
38659                             lcb+= markup;
38660                         }
38661                     }
38662                     var alt = [];
38663                     if(stripe && ((rowIndex+1) % 2 == 0)){
38664                         alt.push("x-grid-row-alt")
38665                     }
38666                     if(r.dirty){
38667                         alt.push(  " x-grid-dirty-row");
38668                     }
38669                     rp.cells = lcb;
38670                     if(this.getRowClass){
38671                         alt.push(this.getRowClass(r, rowIndex));
38672                     }
38673                     if (hasListener) {
38674                         rowcfg = {
38675                              
38676                             record: r,
38677                             rowIndex : rowIndex,
38678                             rowClass : ''
38679                         };
38680                         this.grid.fireEvent('rowclass', this, rowcfg);
38681                         alt.push(rowcfg.rowClass);
38682                     }
38683                     rp.alt = alt.join(" ");
38684                     lbuf+= rt.apply(rp);
38685                     rp.cells = cb;
38686                     buf+=  rt.apply(rp);
38687                 }
38688                 return [lbuf, buf];
38689             } :
38690             function(cs, rs, ds, startRow, colCount, stripe){
38691                 var ts = this.templates, ct = ts.cell, rt = ts.row;
38692                 // buffers
38693                 var buf = [], lbuf = [], cb, lcb, c, p = {}, rp = {}, r, rowIndex;
38694                 var hasListener = this.grid.hasListener('rowclass');
38695  
38696                 var rowcfg = {};
38697                 for(var j = 0, len = rs.length; j < len; j++){
38698                     r = rs[j]; cb = []; lcb = []; rowIndex = (j+startRow);
38699                     for(var i = 0; i < colCount; i++){
38700                         c = cs[i];
38701                         p.cellId = "x-grid-cell-" + rowIndex + "-" + i;
38702                         p.id = c.id;
38703                         p.css = p.attr = "";
38704                         p.value = c.renderer(r.data[c.name], p, r, rowIndex, i, ds);
38705                         if(p.value == undefined || p.value === "") {
38706                             p.value = "&#160;";
38707                         }
38708                         //Roo.log(c);
38709                          if(c.has_editor){
38710                             p.css += ' x-grid-editable-cell';
38711                         }
38712                         if(r.dirty && typeof r.modified[c.name] !== 'undefined'){
38713                             p.css += ' x-grid-dirty-cell' 
38714                         }
38715                         
38716                         var markup = ct.apply(p);
38717                         if(!c.locked){
38718                             cb[cb.length] = markup;
38719                         }else{
38720                             lcb[lcb.length] = markup;
38721                         }
38722                     }
38723                     var alt = [];
38724                     if(stripe && ((rowIndex+1) % 2 == 0)){
38725                         alt.push( "x-grid-row-alt");
38726                     }
38727                     if(r.dirty){
38728                         alt.push(" x-grid-dirty-row");
38729                     }
38730                     rp.cells = lcb;
38731                     if(this.getRowClass){
38732                         alt.push( this.getRowClass(r, rowIndex));
38733                     }
38734                     if (hasListener) {
38735                         rowcfg = {
38736                              
38737                             record: r,
38738                             rowIndex : rowIndex,
38739                             rowClass : ''
38740                         };
38741                         this.grid.fireEvent('rowclass', this, rowcfg);
38742                         alt.push(rowcfg.rowClass);
38743                     }
38744                     
38745                     rp.alt = alt.join(" ");
38746                     rp.cells = lcb.join("");
38747                     lbuf[lbuf.length] = rt.apply(rp);
38748                     rp.cells = cb.join("");
38749                     buf[buf.length] =  rt.apply(rp);
38750                 }
38751                 return [lbuf.join(""), buf.join("")];
38752             },
38753
38754     renderBody : function(){
38755         var markup = this.renderRows();
38756         var bt = this.templates.body;
38757         return [bt.apply({rows: markup[0]}), bt.apply({rows: markup[1]})];
38758     },
38759
38760     /**
38761      * Refreshes the grid
38762      * @param {Boolean} headersToo
38763      */
38764     refresh : function(headersToo){
38765         this.fireEvent("beforerefresh", this);
38766         this.grid.stopEditing();
38767         var result = this.renderBody();
38768         this.lockedBody.update(result[0]);
38769         this.mainBody.update(result[1]);
38770         if(headersToo === true){
38771             this.updateHeaders();
38772             this.updateColumns();
38773             this.updateSplitters();
38774             this.updateHeaderSortState();
38775         }
38776         this.syncRowHeights();
38777         this.layout();
38778         this.fireEvent("refresh", this);
38779     },
38780
38781     handleColumnMove : function(cm, oldIndex, newIndex){
38782         this.indexMap = null;
38783         var s = this.getScrollState();
38784         this.refresh(true);
38785         this.restoreScroll(s);
38786         this.afterMove(newIndex);
38787     },
38788
38789     afterMove : function(colIndex){
38790         if(this.enableMoveAnim && Roo.enableFx){
38791             this.fly(this.getHeaderCell(colIndex).firstChild).highlight(this.hlColor);
38792         }
38793         // if multisort - fix sortOrder, and reload..
38794         if (this.grid.dataSource.multiSort) {
38795             // the we can call sort again..
38796             var dm = this.grid.dataSource;
38797             var cm = this.grid.colModel;
38798             var so = [];
38799             for(var i = 0; i < cm.config.length; i++ ) {
38800                 
38801                 if ((typeof(dm.sortToggle[cm.config[i].dataIndex]) == 'undefined')) {
38802                     continue; // dont' bother, it's not in sort list or being set.
38803                 }
38804                 
38805                 so.push(cm.config[i].dataIndex);
38806             };
38807             dm.sortOrder = so;
38808             dm.load(dm.lastOptions);
38809             
38810             
38811         }
38812         
38813     },
38814
38815     updateCell : function(dm, rowIndex, dataIndex){
38816         var colIndex = this.getColumnIndexByDataIndex(dataIndex);
38817         if(typeof colIndex == "undefined"){ // not present in grid
38818             return;
38819         }
38820         var cm = this.grid.colModel;
38821         var cell = this.getCell(rowIndex, colIndex);
38822         var cellText = this.getCellText(rowIndex, colIndex);
38823
38824         var p = {
38825             cellId : "x-grid-cell-" + rowIndex + "-" + colIndex,
38826             id : cm.getColumnId(colIndex),
38827             css: colIndex == cm.getColumnCount()-1 ? "x-grid-col-last" : ""
38828         };
38829         var renderer = cm.getRenderer(colIndex);
38830         var val = renderer(dm.getValueAt(rowIndex, dataIndex), p, rowIndex, colIndex, dm);
38831         if(typeof val == "undefined" || val === "") {
38832             val = "&#160;";
38833         }
38834         cellText.innerHTML = val;
38835         cell.className = this.cellClass + " " + this.idToCssName(p.cellId) + " " + p.css;
38836         this.syncRowHeights(rowIndex, rowIndex);
38837     },
38838
38839     calcColumnWidth : function(colIndex, maxRowsToMeasure){
38840         var maxWidth = 0;
38841         if(this.grid.autoSizeHeaders){
38842             var h = this.getHeaderCellMeasure(colIndex);
38843             maxWidth = Math.max(maxWidth, h.scrollWidth);
38844         }
38845         var tb, index;
38846         if(this.cm.isLocked(colIndex)){
38847             tb = this.getLockedTable();
38848             index = colIndex;
38849         }else{
38850             tb = this.getBodyTable();
38851             index = colIndex - this.cm.getLockedCount();
38852         }
38853         if(tb && tb.rows){
38854             var rows = tb.rows;
38855             var stopIndex = Math.min(maxRowsToMeasure || rows.length, rows.length);
38856             for(var i = 0; i < stopIndex; i++){
38857                 var cell = rows[i].childNodes[index].firstChild;
38858                 maxWidth = Math.max(maxWidth, cell.scrollWidth);
38859             }
38860         }
38861         return maxWidth + /*margin for error in IE*/ 5;
38862     },
38863     /**
38864      * Autofit a column to its content.
38865      * @param {Number} colIndex
38866      * @param {Boolean} forceMinSize true to force the column to go smaller if possible
38867      */
38868      autoSizeColumn : function(colIndex, forceMinSize, suppressEvent){
38869          if(this.cm.isHidden(colIndex)){
38870              return; // can't calc a hidden column
38871          }
38872         if(forceMinSize){
38873             var cid = this.cm.getColumnId(colIndex);
38874             this.css.updateRule(this.colSelector +this.idToCssName( cid), "width", this.grid.minColumnWidth + "px");
38875            if(this.grid.autoSizeHeaders){
38876                this.css.updateRule(this.hdSelector + this.idToCssName(cid), "width", this.grid.minColumnWidth + "px");
38877            }
38878         }
38879         var newWidth = this.calcColumnWidth(colIndex);
38880         this.cm.setColumnWidth(colIndex,
38881             Math.max(this.grid.minColumnWidth, newWidth), suppressEvent);
38882         if(!suppressEvent){
38883             this.grid.fireEvent("columnresize", colIndex, newWidth);
38884         }
38885     },
38886
38887     /**
38888      * Autofits all columns to their content and then expands to fit any extra space in the grid
38889      */
38890      autoSizeColumns : function(){
38891         var cm = this.grid.colModel;
38892         var colCount = cm.getColumnCount();
38893         for(var i = 0; i < colCount; i++){
38894             this.autoSizeColumn(i, true, true);
38895         }
38896         if(cm.getTotalWidth() < this.scroller.dom.clientWidth){
38897             this.fitColumns();
38898         }else{
38899             this.updateColumns();
38900             this.layout();
38901         }
38902     },
38903
38904     /**
38905      * Autofits all columns to the grid's width proportionate with their current size
38906      * @param {Boolean} reserveScrollSpace Reserve space for a scrollbar
38907      */
38908     fitColumns : function(reserveScrollSpace){
38909         var cm = this.grid.colModel;
38910         var colCount = cm.getColumnCount();
38911         var cols = [];
38912         var width = 0;
38913         var i, w;
38914         for (i = 0; i < colCount; i++){
38915             if(!cm.isHidden(i) && !cm.isFixed(i)){
38916                 w = cm.getColumnWidth(i);
38917                 cols.push(i);
38918                 cols.push(w);
38919                 width += w;
38920             }
38921         }
38922         var avail = Math.min(this.scroller.dom.clientWidth, this.el.getWidth());
38923         if(reserveScrollSpace){
38924             avail -= 17;
38925         }
38926         var frac = (avail - cm.getTotalWidth())/width;
38927         while (cols.length){
38928             w = cols.pop();
38929             i = cols.pop();
38930             cm.setColumnWidth(i, Math.floor(w + w*frac), true);
38931         }
38932         this.updateColumns();
38933         this.layout();
38934     },
38935
38936     onRowSelect : function(rowIndex){
38937         var row = this.getRowComposite(rowIndex);
38938         row.addClass("x-grid-row-selected");
38939     },
38940
38941     onRowDeselect : function(rowIndex){
38942         var row = this.getRowComposite(rowIndex);
38943         row.removeClass("x-grid-row-selected");
38944     },
38945
38946     onCellSelect : function(row, col){
38947         var cell = this.getCell(row, col);
38948         if(cell){
38949             Roo.fly(cell).addClass("x-grid-cell-selected");
38950         }
38951     },
38952
38953     onCellDeselect : function(row, col){
38954         var cell = this.getCell(row, col);
38955         if(cell){
38956             Roo.fly(cell).removeClass("x-grid-cell-selected");
38957         }
38958     },
38959
38960     updateHeaderSortState : function(){
38961         
38962         // sort state can be single { field: xxx, direction : yyy}
38963         // or   { xxx=>ASC , yyy : DESC ..... }
38964         
38965         var mstate = {};
38966         if (!this.ds.multiSort) { 
38967             var state = this.ds.getSortState();
38968             if(!state){
38969                 return;
38970             }
38971             mstate[state.field] = state.direction;
38972             // FIXME... - this is not used here.. but might be elsewhere..
38973             this.sortState = state;
38974             
38975         } else {
38976             mstate = this.ds.sortToggle;
38977         }
38978         //remove existing sort classes..
38979         
38980         var sc = this.sortClasses;
38981         var hds = this.el.select(this.headerSelector).removeClass(sc);
38982         
38983         for(var f in mstate) {
38984         
38985             var sortColumn = this.cm.findColumnIndex(f);
38986             
38987             if(sortColumn != -1){
38988                 var sortDir = mstate[f];        
38989                 hds.item(sortColumn).addClass(sc[sortDir == "DESC" ? 1 : 0]);
38990             }
38991         }
38992         
38993          
38994         
38995     },
38996
38997
38998     handleHeaderClick : function(g, index,e){
38999         
39000         Roo.log("header click");
39001         
39002         if (Roo.isTouch) {
39003             // touch events on header are handled by context
39004             this.handleHdCtx(g,index,e);
39005             return;
39006         }
39007         
39008         
39009         if(this.headersDisabled){
39010             return;
39011         }
39012         var dm = g.dataSource, cm = g.colModel;
39013         if(!cm.isSortable(index)){
39014             return;
39015         }
39016         g.stopEditing();
39017         
39018         if (dm.multiSort) {
39019             // update the sortOrder
39020             var so = [];
39021             for(var i = 0; i < cm.config.length; i++ ) {
39022                 
39023                 if ((typeof(dm.sortToggle[cm.config[i].dataIndex]) == 'undefined') && (index != i)) {
39024                     continue; // dont' bother, it's not in sort list or being set.
39025                 }
39026                 
39027                 so.push(cm.config[i].dataIndex);
39028             };
39029             dm.sortOrder = so;
39030         }
39031         
39032         
39033         dm.sort(cm.getDataIndex(index));
39034     },
39035
39036
39037     destroy : function(){
39038         if(this.colMenu){
39039             this.colMenu.removeAll();
39040             Roo.menu.MenuMgr.unregister(this.colMenu);
39041             this.colMenu.getEl().remove();
39042             delete this.colMenu;
39043         }
39044         if(this.hmenu){
39045             this.hmenu.removeAll();
39046             Roo.menu.MenuMgr.unregister(this.hmenu);
39047             this.hmenu.getEl().remove();
39048             delete this.hmenu;
39049         }
39050         if(this.grid.enableColumnMove){
39051             var dds = Roo.dd.DDM.ids['gridHeader' + this.grid.getGridEl().id];
39052             if(dds){
39053                 for(var dd in dds){
39054                     if(!dds[dd].config.isTarget && dds[dd].dragElId){
39055                         var elid = dds[dd].dragElId;
39056                         dds[dd].unreg();
39057                         Roo.get(elid).remove();
39058                     } else if(dds[dd].config.isTarget){
39059                         dds[dd].proxyTop.remove();
39060                         dds[dd].proxyBottom.remove();
39061                         dds[dd].unreg();
39062                     }
39063                     if(Roo.dd.DDM.locationCache[dd]){
39064                         delete Roo.dd.DDM.locationCache[dd];
39065                     }
39066                 }
39067                 delete Roo.dd.DDM.ids['gridHeader' + this.grid.getGridEl().id];
39068             }
39069         }
39070         Roo.util.CSS.removeStyleSheet(this.idToCssName(this.grid.id) + '-cssrules');
39071         this.bind(null, null);
39072         Roo.EventManager.removeResizeListener(this.onWindowResize, this);
39073     },
39074
39075     handleLockChange : function(){
39076         this.refresh(true);
39077     },
39078
39079     onDenyColumnLock : function(){
39080
39081     },
39082
39083     onDenyColumnHide : function(){
39084
39085     },
39086
39087     handleHdMenuClick : function(item){
39088         var index = this.hdCtxIndex;
39089         var cm = this.cm, ds = this.ds;
39090         switch(item.id){
39091             case "asc":
39092                 ds.sort(cm.getDataIndex(index), "ASC");
39093                 break;
39094             case "desc":
39095                 ds.sort(cm.getDataIndex(index), "DESC");
39096                 break;
39097             case "lock":
39098                 var lc = cm.getLockedCount();
39099                 if(cm.getColumnCount(true) <= lc+1){
39100                     this.onDenyColumnLock();
39101                     return;
39102                 }
39103                 if(lc != index){
39104                     cm.setLocked(index, true, true);
39105                     cm.moveColumn(index, lc);
39106                     this.grid.fireEvent("columnmove", index, lc);
39107                 }else{
39108                     cm.setLocked(index, true);
39109                 }
39110             break;
39111             case "unlock":
39112                 var lc = cm.getLockedCount();
39113                 if((lc-1) != index){
39114                     cm.setLocked(index, false, true);
39115                     cm.moveColumn(index, lc-1);
39116                     this.grid.fireEvent("columnmove", index, lc-1);
39117                 }else{
39118                     cm.setLocked(index, false);
39119                 }
39120             break;
39121             case 'wider': // used to expand cols on touch..
39122             case 'narrow':
39123                 var cw = cm.getColumnWidth(index);
39124                 cw += (item.id == 'wider' ? 1 : -1) * 50;
39125                 cw = Math.max(0, cw);
39126                 cw = Math.min(cw,4000);
39127                 cm.setColumnWidth(index, cw);
39128                 break;
39129                 
39130             default:
39131                 index = cm.getIndexById(item.id.substr(4));
39132                 if(index != -1){
39133                     if(item.checked && cm.getColumnCount(true) <= 1){
39134                         this.onDenyColumnHide();
39135                         return false;
39136                     }
39137                     cm.setHidden(index, item.checked);
39138                 }
39139         }
39140         return true;
39141     },
39142
39143     beforeColMenuShow : function(){
39144         var cm = this.cm,  colCount = cm.getColumnCount();
39145         this.colMenu.removeAll();
39146         
39147         var items = [];
39148         for(var i = 0; i < colCount; i++){
39149             items.push({
39150                 id: "col-"+cm.getColumnId(i),
39151                 text: cm.getColumnHeader(i),
39152                 checked: !cm.isHidden(i),
39153                 hideOnClick:false
39154             });
39155         }
39156         
39157         if (this.grid.sortColMenu) {
39158             items.sort(function(a,b) {
39159                 if (a.text == b.text) {
39160                     return 0;
39161                 }
39162                 return a.text.toUpperCase() > b.text.toUpperCase() ? 1 : -1;
39163             });
39164         }
39165         
39166         for(var i = 0; i < colCount; i++){
39167             this.colMenu.add(new Roo.menu.CheckItem(items[i]));
39168         }
39169     },
39170
39171     handleHdCtx : function(g, index, e){
39172         e.stopEvent();
39173         var hd = this.getHeaderCell(index);
39174         this.hdCtxIndex = index;
39175         var ms = this.hmenu.items, cm = this.cm;
39176         ms.get("asc").setDisabled(!cm.isSortable(index));
39177         ms.get("desc").setDisabled(!cm.isSortable(index));
39178         if(this.grid.enableColLock !== false){
39179             ms.get("lock").setDisabled(cm.isLocked(index));
39180             ms.get("unlock").setDisabled(!cm.isLocked(index));
39181         }
39182         this.hmenu.show(hd, "tl-bl");
39183     },
39184
39185     handleHdOver : function(e){
39186         var hd = this.findHeaderCell(e.getTarget());
39187         if(hd && !this.headersDisabled){
39188             if(this.grid.colModel.isSortable(this.getCellIndex(hd))){
39189                this.fly(hd).addClass("x-grid-hd-over");
39190             }
39191         }
39192     },
39193
39194     handleHdOut : function(e){
39195         var hd = this.findHeaderCell(e.getTarget());
39196         if(hd){
39197             this.fly(hd).removeClass("x-grid-hd-over");
39198         }
39199     },
39200
39201     handleSplitDblClick : function(e, t){
39202         var i = this.getCellIndex(t);
39203         if(this.grid.enableColumnResize !== false && this.cm.isResizable(i) && !this.cm.isFixed(i)){
39204             this.autoSizeColumn(i, true);
39205             this.layout();
39206         }
39207     },
39208
39209     render : function(){
39210
39211         var cm = this.cm;
39212         var colCount = cm.getColumnCount();
39213
39214         if(this.grid.monitorWindowResize === true){
39215             Roo.EventManager.onWindowResize(this.onWindowResize, this, true);
39216         }
39217         var header = this.renderHeaders();
39218         var body = this.templates.body.apply({rows:""});
39219         var html = this.templates.master.apply({
39220             lockedBody: body,
39221             body: body,
39222             lockedHeader: header[0],
39223             header: header[1]
39224         });
39225
39226         //this.updateColumns();
39227
39228         this.grid.getGridEl().dom.innerHTML = html;
39229
39230         this.initElements();
39231         
39232         // a kludge to fix the random scolling effect in webkit
39233         this.el.on("scroll", function() {
39234             this.el.dom.scrollTop=0; // hopefully not recursive..
39235         },this);
39236
39237         this.scroller.on("scroll", this.handleScroll, this);
39238         this.lockedBody.on("mousewheel", this.handleWheel, this);
39239         this.mainBody.on("mousewheel", this.handleWheel, this);
39240
39241         this.mainHd.on("mouseover", this.handleHdOver, this);
39242         this.mainHd.on("mouseout", this.handleHdOut, this);
39243         this.mainHd.on("dblclick", this.handleSplitDblClick, this,
39244                 {delegate: "."+this.splitClass});
39245
39246         this.lockedHd.on("mouseover", this.handleHdOver, this);
39247         this.lockedHd.on("mouseout", this.handleHdOut, this);
39248         this.lockedHd.on("dblclick", this.handleSplitDblClick, this,
39249                 {delegate: "."+this.splitClass});
39250
39251         if(this.grid.enableColumnResize !== false && Roo.grid.SplitDragZone){
39252             new Roo.grid.SplitDragZone(this.grid, this.lockedHd.dom, this.mainHd.dom);
39253         }
39254
39255         this.updateSplitters();
39256
39257         if(this.grid.enableColumnMove && Roo.grid.HeaderDragZone){
39258             new Roo.grid.HeaderDragZone(this.grid, this.lockedHd.dom, this.mainHd.dom);
39259             new Roo.grid.HeaderDropZone(this.grid, this.lockedHd.dom, this.mainHd.dom);
39260         }
39261
39262         if(this.grid.enableCtxMenu !== false && Roo.menu.Menu){
39263             this.hmenu = new Roo.menu.Menu({id: this.grid.id + "-hctx"});
39264             this.hmenu.add(
39265                 {id:"asc", text: this.sortAscText, cls: "xg-hmenu-sort-asc"},
39266                 {id:"desc", text: this.sortDescText, cls: "xg-hmenu-sort-desc"}
39267             );
39268             if(this.grid.enableColLock !== false){
39269                 this.hmenu.add('-',
39270                     {id:"lock", text: this.lockText, cls: "xg-hmenu-lock"},
39271                     {id:"unlock", text: this.unlockText, cls: "xg-hmenu-unlock"}
39272                 );
39273             }
39274             if (Roo.isTouch) {
39275                  this.hmenu.add('-',
39276                     {id:"wider", text: this.columnsWiderText},
39277                     {id:"narrow", text: this.columnsNarrowText }
39278                 );
39279                 
39280                  
39281             }
39282             
39283             if(this.grid.enableColumnHide !== false){
39284
39285                 this.colMenu = new Roo.menu.Menu({id:this.grid.id + "-hcols-menu"});
39286                 this.colMenu.on("beforeshow", this.beforeColMenuShow, this);
39287                 this.colMenu.on("itemclick", this.handleHdMenuClick, this);
39288
39289                 this.hmenu.add('-',
39290                     {id:"columns", text: this.columnsText, menu: this.colMenu}
39291                 );
39292             }
39293             this.hmenu.on("itemclick", this.handleHdMenuClick, this);
39294
39295             this.grid.on("headercontextmenu", this.handleHdCtx, this);
39296         }
39297
39298         if((this.grid.enableDragDrop || this.grid.enableDrag) && Roo.grid.GridDragZone){
39299             this.dd = new Roo.grid.GridDragZone(this.grid, {
39300                 ddGroup : this.grid.ddGroup || 'GridDD'
39301             });
39302             
39303         }
39304
39305         /*
39306         for(var i = 0; i < colCount; i++){
39307             if(cm.isHidden(i)){
39308                 this.hideColumn(i);
39309             }
39310             if(cm.config[i].align){
39311                 this.css.updateRule(this.colSelector + i, "textAlign", cm.config[i].align);
39312                 this.css.updateRule(this.hdSelector + i, "textAlign", cm.config[i].align);
39313             }
39314         }*/
39315         
39316         this.updateHeaderSortState();
39317
39318         this.beforeInitialResize();
39319         this.layout(true);
39320
39321         // two part rendering gives faster view to the user
39322         this.renderPhase2.defer(1, this);
39323     },
39324
39325     renderPhase2 : function(){
39326         // render the rows now
39327         this.refresh();
39328         if(this.grid.autoSizeColumns){
39329             this.autoSizeColumns();
39330         }
39331     },
39332
39333     beforeInitialResize : function(){
39334
39335     },
39336
39337     onColumnSplitterMoved : function(i, w){
39338         this.userResized = true;
39339         var cm = this.grid.colModel;
39340         cm.setColumnWidth(i, w, true);
39341         var cid = cm.getColumnId(i);
39342         this.css.updateRule(this.colSelector + this.idToCssName(cid), "width", (w-this.borderWidth) + "px");
39343         this.css.updateRule(this.hdSelector + this.idToCssName(cid), "width", (w-this.borderWidth) + "px");
39344         this.updateSplitters();
39345         this.layout();
39346         this.grid.fireEvent("columnresize", i, w);
39347     },
39348
39349     syncRowHeights : function(startIndex, endIndex){
39350         if(this.grid.enableRowHeightSync === true && this.cm.getLockedCount() > 0){
39351             startIndex = startIndex || 0;
39352             var mrows = this.getBodyTable().rows;
39353             var lrows = this.getLockedTable().rows;
39354             var len = mrows.length-1;
39355             endIndex = Math.min(endIndex || len, len);
39356             for(var i = startIndex; i <= endIndex; i++){
39357                 var m = mrows[i], l = lrows[i];
39358                 var h = Math.max(m.offsetHeight, l.offsetHeight);
39359                 m.style.height = l.style.height = h + "px";
39360             }
39361         }
39362     },
39363
39364     layout : function(initialRender, is2ndPass)
39365     {
39366         var g = this.grid;
39367         var auto = g.autoHeight;
39368         var scrollOffset = 16;
39369         var c = g.getGridEl(), cm = this.cm,
39370                 expandCol = g.autoExpandColumn,
39371                 gv = this;
39372         //c.beginMeasure();
39373
39374         if(!c.dom.offsetWidth){ // display:none?
39375             if(initialRender){
39376                 this.lockedWrap.show();
39377                 this.mainWrap.show();
39378             }
39379             return;
39380         }
39381
39382         var hasLock = this.cm.isLocked(0);
39383
39384         var tbh = this.headerPanel.getHeight();
39385         var bbh = this.footerPanel.getHeight();
39386
39387         if(auto){
39388             var ch = this.getBodyTable().offsetHeight + tbh + bbh + this.mainHd.getHeight();
39389             var newHeight = ch + c.getBorderWidth("tb");
39390             if(g.maxHeight){
39391                 newHeight = Math.min(g.maxHeight, newHeight);
39392             }
39393             c.setHeight(newHeight);
39394         }
39395
39396         if(g.autoWidth){
39397             c.setWidth(cm.getTotalWidth()+c.getBorderWidth('lr'));
39398         }
39399
39400         var s = this.scroller;
39401
39402         var csize = c.getSize(true);
39403
39404         this.el.setSize(csize.width, csize.height);
39405
39406         this.headerPanel.setWidth(csize.width);
39407         this.footerPanel.setWidth(csize.width);
39408
39409         var hdHeight = this.mainHd.getHeight();
39410         var vw = csize.width;
39411         var vh = csize.height - (tbh + bbh);
39412
39413         s.setSize(vw, vh);
39414
39415         var bt = this.getBodyTable();
39416         
39417         if(cm.getLockedCount() == cm.config.length){
39418             bt = this.getLockedTable();
39419         }
39420         
39421         var ltWidth = hasLock ?
39422                       Math.max(this.getLockedTable().offsetWidth, this.lockedHd.dom.firstChild.offsetWidth) : 0;
39423
39424         var scrollHeight = bt.offsetHeight;
39425         var scrollWidth = ltWidth + bt.offsetWidth;
39426         var vscroll = false, hscroll = false;
39427
39428         this.scrollSizer.setSize(scrollWidth, scrollHeight+hdHeight);
39429
39430         var lw = this.lockedWrap, mw = this.mainWrap;
39431         var lb = this.lockedBody, mb = this.mainBody;
39432
39433         setTimeout(function(){
39434             var t = s.dom.offsetTop;
39435             var w = s.dom.clientWidth,
39436                 h = s.dom.clientHeight;
39437
39438             lw.setTop(t);
39439             lw.setSize(ltWidth, h);
39440
39441             mw.setLeftTop(ltWidth, t);
39442             mw.setSize(w-ltWidth, h);
39443
39444             lb.setHeight(h-hdHeight);
39445             mb.setHeight(h-hdHeight);
39446
39447             if(is2ndPass !== true && !gv.userResized && expandCol){
39448                 // high speed resize without full column calculation
39449                 
39450                 var ci = cm.getIndexById(expandCol);
39451                 if (ci < 0) {
39452                     ci = cm.findColumnIndex(expandCol);
39453                 }
39454                 ci = Math.max(0, ci); // make sure it's got at least the first col.
39455                 var expandId = cm.getColumnId(ci);
39456                 var  tw = cm.getTotalWidth(false);
39457                 var currentWidth = cm.getColumnWidth(ci);
39458                 var cw = Math.min(Math.max(((w-tw)+currentWidth-2)-/*scrollbar*/(w <= s.dom.offsetWidth ? 0 : 18), g.autoExpandMin), g.autoExpandMax);
39459                 if(currentWidth != cw){
39460                     cm.setColumnWidth(ci, cw, true);
39461                     gv.css.updateRule(gv.colSelector+gv.idToCssName(expandId), "width", (cw - gv.borderWidth) + "px");
39462                     gv.css.updateRule(gv.hdSelector+gv.idToCssName(expandId), "width", (cw - gv.borderWidth) + "px");
39463                     gv.updateSplitters();
39464                     gv.layout(false, true);
39465                 }
39466             }
39467
39468             if(initialRender){
39469                 lw.show();
39470                 mw.show();
39471             }
39472             //c.endMeasure();
39473         }, 10);
39474     },
39475
39476     onWindowResize : function(){
39477         if(!this.grid.monitorWindowResize || this.grid.autoHeight){
39478             return;
39479         }
39480         this.layout();
39481     },
39482
39483     appendFooter : function(parentEl){
39484         return null;
39485     },
39486
39487     sortAscText : "Sort Ascending",
39488     sortDescText : "Sort Descending",
39489     lockText : "Lock Column",
39490     unlockText : "Unlock Column",
39491     columnsText : "Columns",
39492  
39493     columnsWiderText : "Wider",
39494     columnsNarrowText : "Thinner"
39495 });
39496
39497
39498 Roo.grid.GridView.ColumnDragZone = function(grid, hd){
39499     Roo.grid.GridView.ColumnDragZone.superclass.constructor.call(this, grid, hd, null);
39500     this.proxy.el.addClass('x-grid3-col-dd');
39501 };
39502
39503 Roo.extend(Roo.grid.GridView.ColumnDragZone, Roo.grid.HeaderDragZone, {
39504     handleMouseDown : function(e){
39505
39506     },
39507
39508     callHandleMouseDown : function(e){
39509         Roo.grid.GridView.ColumnDragZone.superclass.handleMouseDown.call(this, e);
39510     }
39511 });
39512 /*
39513  * Based on:
39514  * Ext JS Library 1.1.1
39515  * Copyright(c) 2006-2007, Ext JS, LLC.
39516  *
39517  * Originally Released Under LGPL - original licence link has changed is not relivant.
39518  *
39519  * Fork - LGPL
39520  * <script type="text/javascript">
39521  */
39522  /**
39523  * @extends Roo.dd.DDProxy
39524  * @class Roo.grid.SplitDragZone
39525  * Support for Column Header resizing
39526  * @constructor
39527  * @param {Object} config
39528  */
39529 // private
39530 // This is a support class used internally by the Grid components
39531 Roo.grid.SplitDragZone = function(grid, hd, hd2){
39532     this.grid = grid;
39533     this.view = grid.getView();
39534     this.proxy = this.view.resizeProxy;
39535     Roo.grid.SplitDragZone.superclass.constructor.call(
39536         this,
39537         hd, // ID
39538         "gridSplitters" + this.grid.getGridEl().id, // SGROUP
39539         {  // CONFIG
39540             dragElId : Roo.id(this.proxy.dom),
39541             resizeFrame:false
39542         }
39543     );
39544     
39545     this.setHandleElId(Roo.id(hd));
39546     if (hd2 !== false) {
39547         this.setOuterHandleElId(Roo.id(hd2));
39548     }
39549     
39550     this.scroll = false;
39551 };
39552 Roo.extend(Roo.grid.SplitDragZone, Roo.dd.DDProxy, {
39553     fly: Roo.Element.fly,
39554
39555     b4StartDrag : function(x, y){
39556         this.view.headersDisabled = true;
39557         var h = this.view.mainWrap ? this.view.mainWrap.getHeight() : (
39558                     this.view.headEl.getHeight() + this.view.bodyEl.getHeight()
39559         );
39560         this.proxy.setHeight(h);
39561         
39562         // for old system colWidth really stored the actual width?
39563         // in bootstrap we tried using xs/ms/etc.. to do % sizing?
39564         // which in reality did not work.. - it worked only for fixed sizes
39565         // for resizable we need to use actual sizes.
39566         var w = this.cm.getColumnWidth(this.cellIndex);
39567         if (!this.view.mainWrap) {
39568             // bootstrap.
39569             w = this.view.getHeaderIndex(this.cellIndex).getWidth();
39570         }
39571         
39572         
39573         
39574         // this was w-this.grid.minColumnWidth;
39575         // doesnt really make sense? - w = thie curren width or the rendered one?
39576         var minw = Math.max(w-this.grid.minColumnWidth, 0);
39577         this.resetConstraints();
39578         this.setXConstraint(minw, 1000);
39579         this.setYConstraint(0, 0);
39580         this.minX = x - minw;
39581         this.maxX = x + 1000;
39582         this.startPos = x;
39583         if (!this.view.mainWrap) { // this is Bootstrap code..
39584             this.getDragEl().style.display='block';
39585         }
39586         
39587         Roo.dd.DDProxy.prototype.b4StartDrag.call(this, x, y);
39588     },
39589
39590
39591     handleMouseDown : function(e){
39592         ev = Roo.EventObject.setEvent(e);
39593         var t = this.fly(ev.getTarget());
39594         if(t.hasClass("x-grid-split")){
39595             this.cellIndex = this.view.getCellIndex(t.dom);
39596             this.split = t.dom;
39597             this.cm = this.grid.colModel;
39598             if(this.cm.isResizable(this.cellIndex) && !this.cm.isFixed(this.cellIndex)){
39599                 Roo.grid.SplitDragZone.superclass.handleMouseDown.apply(this, arguments);
39600             }
39601         }
39602     },
39603
39604     endDrag : function(e){
39605         this.view.headersDisabled = false;
39606         var endX = Math.max(this.minX, Roo.lib.Event.getPageX(e));
39607         var diff = endX - this.startPos;
39608         // 
39609         var w = this.cm.getColumnWidth(this.cellIndex);
39610         if (!this.view.mainWrap) {
39611             w = 0;
39612         }
39613         this.view.onColumnSplitterMoved(this.cellIndex, w+diff);
39614     },
39615
39616     autoOffset : function(){
39617         this.setDelta(0,0);
39618     }
39619 });/*
39620  * Based on:
39621  * Ext JS Library 1.1.1
39622  * Copyright(c) 2006-2007, Ext JS, LLC.
39623  *
39624  * Originally Released Under LGPL - original licence link has changed is not relivant.
39625  *
39626  * Fork - LGPL
39627  * <script type="text/javascript">
39628  */
39629  
39630 // private
39631 // This is a support class used internally by the Grid components
39632 Roo.grid.GridDragZone = function(grid, config){
39633     this.view = grid.getView();
39634     Roo.grid.GridDragZone.superclass.constructor.call(this, this.view.mainBody.dom, config);
39635     if(this.view.lockedBody){
39636         this.setHandleElId(Roo.id(this.view.mainBody.dom));
39637         this.setOuterHandleElId(Roo.id(this.view.lockedBody.dom));
39638     }
39639     this.scroll = false;
39640     this.grid = grid;
39641     this.ddel = document.createElement('div');
39642     this.ddel.className = 'x-grid-dd-wrap';
39643 };
39644
39645 Roo.extend(Roo.grid.GridDragZone, Roo.dd.DragZone, {
39646     ddGroup : "GridDD",
39647
39648     getDragData : function(e){
39649         var t = Roo.lib.Event.getTarget(e);
39650         var rowIndex = this.view.findRowIndex(t);
39651         var sm = this.grid.selModel;
39652             
39653         //Roo.log(rowIndex);
39654         
39655         if (sm.getSelectedCell) {
39656             // cell selection..
39657             if (!sm.getSelectedCell()) {
39658                 return false;
39659             }
39660             if (rowIndex != sm.getSelectedCell()[0]) {
39661                 return false;
39662             }
39663         
39664         }
39665         if (sm.getSelections && sm.getSelections().length < 1) {
39666             return false;
39667         }
39668         
39669         
39670         // before it used to all dragging of unseleted... - now we dont do that.
39671         if(rowIndex !== false){
39672             
39673             // if editorgrid.. 
39674             
39675             
39676             //Roo.log([ sm.getSelectedCell() ? sm.getSelectedCell()[0] : 'NO' , rowIndex ]);
39677                
39678             //if(!sm.isSelected(rowIndex) || e.hasModifier()){
39679               //  
39680             //}
39681             if (e.hasModifier()){
39682                 sm.handleMouseDown(e, t); // non modifier buttons are handled by row select.
39683             }
39684             
39685             Roo.log("getDragData");
39686             
39687             return {
39688                 grid: this.grid,
39689                 ddel: this.ddel,
39690                 rowIndex: rowIndex,
39691                 selections: sm.getSelections ? sm.getSelections() : (
39692                     sm.getSelectedCell() ? [ this.grid.ds.getAt(sm.getSelectedCell()[0]) ] : [])
39693             };
39694         }
39695         return false;
39696     },
39697     
39698     
39699     onInitDrag : function(e){
39700         var data = this.dragData;
39701         this.ddel.innerHTML = this.grid.getDragDropText();
39702         this.proxy.update(this.ddel);
39703         // fire start drag?
39704     },
39705
39706     afterRepair : function(){
39707         this.dragging = false;
39708     },
39709
39710     getRepairXY : function(e, data){
39711         return false;
39712     },
39713
39714     onEndDrag : function(data, e){
39715         // fire end drag?
39716     },
39717
39718     onValidDrop : function(dd, e, id){
39719         // fire drag drop?
39720         this.hideProxy();
39721     },
39722
39723     beforeInvalidDrop : function(e, id){
39724
39725     }
39726 });/*
39727  * Based on:
39728  * Ext JS Library 1.1.1
39729  * Copyright(c) 2006-2007, Ext JS, LLC.
39730  *
39731  * Originally Released Under LGPL - original licence link has changed is not relivant.
39732  *
39733  * Fork - LGPL
39734  * <script type="text/javascript">
39735  */
39736  
39737
39738 /**
39739  * @class Roo.grid.ColumnModel
39740  * @extends Roo.util.Observable
39741  * This is the default implementation of a ColumnModel used by the Grid. It defines
39742  * the columns in the grid.
39743  * <br>Usage:<br>
39744  <pre><code>
39745  var colModel = new Roo.grid.ColumnModel([
39746         {header: "Ticker", width: 60, sortable: true, locked: true},
39747         {header: "Company Name", width: 150, sortable: true},
39748         {header: "Market Cap.", width: 100, sortable: true},
39749         {header: "$ Sales", width: 100, sortable: true, renderer: money},
39750         {header: "Employees", width: 100, sortable: true, resizable: false}
39751  ]);
39752  </code></pre>
39753  * <p>
39754  
39755  * The config options listed for this class are options which may appear in each
39756  * individual column definition.
39757  * <br/>RooJS Fix - column id's are not sequential but use Roo.id() - fixes bugs with layouts.
39758  * @constructor
39759  * @param {Object} config An Array of column config objects. See this class's
39760  * config objects for details.
39761 */
39762 Roo.grid.ColumnModel = function(config){
39763         /**
39764      * The config passed into the constructor
39765      */
39766     this.config = []; //config;
39767     this.lookup = {};
39768
39769     // if no id, create one
39770     // if the column does not have a dataIndex mapping,
39771     // map it to the order it is in the config
39772     for(var i = 0, len = config.length; i < len; i++){
39773         this.addColumn(config[i]);
39774         
39775     }
39776
39777     /**
39778      * The width of columns which have no width specified (defaults to 100)
39779      * @type Number
39780      */
39781     this.defaultWidth = 100;
39782
39783     /**
39784      * Default sortable of columns which have no sortable specified (defaults to false)
39785      * @type Boolean
39786      */
39787     this.defaultSortable = false;
39788
39789     this.addEvents({
39790         /**
39791              * @event widthchange
39792              * Fires when the width of a column changes.
39793              * @param {ColumnModel} this
39794              * @param {Number} columnIndex The column index
39795              * @param {Number} newWidth The new width
39796              */
39797             "widthchange": true,
39798         /**
39799              * @event headerchange
39800              * Fires when the text of a header changes.
39801              * @param {ColumnModel} this
39802              * @param {Number} columnIndex The column index
39803              * @param {Number} newText The new header text
39804              */
39805             "headerchange": true,
39806         /**
39807              * @event hiddenchange
39808              * Fires when a column is hidden or "unhidden".
39809              * @param {ColumnModel} this
39810              * @param {Number} columnIndex The column index
39811              * @param {Boolean} hidden true if hidden, false otherwise
39812              */
39813             "hiddenchange": true,
39814             /**
39815          * @event columnmoved
39816          * Fires when a column is moved.
39817          * @param {ColumnModel} this
39818          * @param {Number} oldIndex
39819          * @param {Number} newIndex
39820          */
39821         "columnmoved" : true,
39822         /**
39823          * @event columlockchange
39824          * Fires when a column's locked state is changed
39825          * @param {ColumnModel} this
39826          * @param {Number} colIndex
39827          * @param {Boolean} locked true if locked
39828          */
39829         "columnlockchange" : true
39830     });
39831     Roo.grid.ColumnModel.superclass.constructor.call(this);
39832 };
39833 Roo.extend(Roo.grid.ColumnModel, Roo.util.Observable, {
39834     /**
39835      * @cfg {String} header [required] The header text to display in the Grid view.
39836      */
39837         /**
39838      * @cfg {String} xsHeader Header at Bootsrap Extra Small width (default for all)
39839      */
39840         /**
39841      * @cfg {String} smHeader Header at Bootsrap Small width
39842      */
39843         /**
39844      * @cfg {String} mdHeader Header at Bootsrap Medium width
39845      */
39846         /**
39847      * @cfg {String} lgHeader Header at Bootsrap Large width
39848      */
39849         /**
39850      * @cfg {String} xlHeader Header at Bootsrap extra Large width
39851      */
39852     /**
39853      * @cfg {String} dataIndex  The name of the field in the grid's {@link Roo.data.Store}'s
39854      * {@link Roo.data.Record} definition from which to draw the column's value. If not
39855      * specified, the column's index is used as an index into the Record's data Array.
39856      */
39857     /**
39858      * @cfg {Number} width  The initial width in pixels of the column. Using this
39859      * instead of {@link Roo.grid.Grid#autoSizeColumns} is more efficient.
39860      */
39861     /**
39862      * @cfg {Boolean} sortable True if sorting is to be allowed on this column.
39863      * Defaults to the value of the {@link #defaultSortable} property.
39864      * Whether local/remote sorting is used is specified in {@link Roo.data.Store#remoteSort}.
39865      */
39866     /**
39867      * @cfg {Boolean} locked  True to lock the column in place while scrolling the Grid.  Defaults to false.
39868      */
39869     /**
39870      * @cfg {Boolean} fixed  True if the column width cannot be changed.  Defaults to false.
39871      */
39872     /**
39873      * @cfg {Boolean} resizable  False to disable column resizing. Defaults to true.
39874      */
39875     /**
39876      * @cfg {Boolean} hidden  True to hide the column. Defaults to false.
39877      */
39878     /**
39879      * @cfg {Function} renderer A function used to generate HTML markup for a cell
39880      * given the cell's data value. See {@link #setRenderer}. If not specified, the
39881      * default renderer returns the escaped data value. If an object is returned (bootstrap only)
39882      * then it is treated as a Roo Component object instance, and it is rendered after the initial row is rendered
39883      */
39884        /**
39885      * @cfg {Roo.grid.GridEditor} editor  For grid editors - returns the grid editor 
39886      */
39887     /**
39888      * @cfg {String} align (left|right) Set the CSS text-align property of the column.  Defaults to undefined (left).
39889      */
39890     /**
39891      * @cfg {String} valign (top|bottom|middle) Set the CSS vertical-align property of the column (eg. middle, top, bottom etc).  Defaults to undefined (middle)
39892      */
39893     /**
39894      * @cfg {String} cursor ( auto|default|none|context-menu|help|pointer|progress|wait|cell|crosshair|text|vertical-text|alias|copy|move|no-drop|not-allowed|e-resize|n-resize|ne-resize|nw-resize|s-resize|se-resize|sw-resize|w-resize|ew-resize|ns-resize|nesw-resize|nwse-resize|col-resize|row-resize|all-scroll|zoom-in|zoom-out|grab|grabbing)
39895      */
39896     /**
39897      * @cfg {String} tooltip mouse over tooltip text
39898      */
39899     /**
39900      * @cfg {Number} xs  can be '0' for hidden at this size (number less than 12)
39901      */
39902     /**
39903      * @cfg {Number} sm can be '0' for hidden at this size (number less than 12)
39904      */
39905     /**
39906      * @cfg {Number} md can be '0' for hidden at this size (number less than 12)
39907      */
39908     /**
39909      * @cfg {Number} lg   can be '0' for hidden at this size (number less than 12)
39910      */
39911         /**
39912      * @cfg {Number} xl   can be '0' for hidden at this size (number less than 12)
39913      */
39914     /**
39915      * Returns the id of the column at the specified index.
39916      * @param {Number} index The column index
39917      * @return {String} the id
39918      */
39919     getColumnId : function(index){
39920         return this.config[index].id;
39921     },
39922
39923     /**
39924      * Returns the column for a specified id.
39925      * @param {String} id The column id
39926      * @return {Object} the column
39927      */
39928     getColumnById : function(id){
39929         return this.lookup[id];
39930     },
39931
39932     
39933     /**
39934      * Returns the column Object for a specified dataIndex.
39935      * @param {String} dataIndex The column dataIndex
39936      * @return {Object|Boolean} the column or false if not found
39937      */
39938     getColumnByDataIndex: function(dataIndex){
39939         var index = this.findColumnIndex(dataIndex);
39940         return index > -1 ? this.config[index] : false;
39941     },
39942     
39943     /**
39944      * Returns the index for a specified column id.
39945      * @param {String} id The column id
39946      * @return {Number} the index, or -1 if not found
39947      */
39948     getIndexById : function(id){
39949         for(var i = 0, len = this.config.length; i < len; i++){
39950             if(this.config[i].id == id){
39951                 return i;
39952             }
39953         }
39954         return -1;
39955     },
39956     
39957     /**
39958      * Returns the index for a specified column dataIndex.
39959      * @param {String} dataIndex The column dataIndex
39960      * @return {Number} the index, or -1 if not found
39961      */
39962     
39963     findColumnIndex : function(dataIndex){
39964         for(var i = 0, len = this.config.length; i < len; i++){
39965             if(this.config[i].dataIndex == dataIndex){
39966                 return i;
39967             }
39968         }
39969         return -1;
39970     },
39971     
39972     
39973     moveColumn : function(oldIndex, newIndex){
39974         var c = this.config[oldIndex];
39975         this.config.splice(oldIndex, 1);
39976         this.config.splice(newIndex, 0, c);
39977         this.dataMap = null;
39978         this.fireEvent("columnmoved", this, oldIndex, newIndex);
39979     },
39980
39981     isLocked : function(colIndex){
39982         return this.config[colIndex].locked === true;
39983     },
39984
39985     setLocked : function(colIndex, value, suppressEvent){
39986         if(this.isLocked(colIndex) == value){
39987             return;
39988         }
39989         this.config[colIndex].locked = value;
39990         if(!suppressEvent){
39991             this.fireEvent("columnlockchange", this, colIndex, value);
39992         }
39993     },
39994
39995     getTotalLockedWidth : function(){
39996         var totalWidth = 0;
39997         for(var i = 0; i < this.config.length; i++){
39998             if(this.isLocked(i) && !this.isHidden(i)){
39999                 this.totalWidth += this.getColumnWidth(i);
40000             }
40001         }
40002         return totalWidth;
40003     },
40004
40005     getLockedCount : function(){
40006         for(var i = 0, len = this.config.length; i < len; i++){
40007             if(!this.isLocked(i)){
40008                 return i;
40009             }
40010         }
40011         
40012         return this.config.length;
40013     },
40014
40015     /**
40016      * Returns the number of columns.
40017      * @return {Number}
40018      */
40019     getColumnCount : function(visibleOnly){
40020         if(visibleOnly === true){
40021             var c = 0;
40022             for(var i = 0, len = this.config.length; i < len; i++){
40023                 if(!this.isHidden(i)){
40024                     c++;
40025                 }
40026             }
40027             return c;
40028         }
40029         return this.config.length;
40030     },
40031
40032     /**
40033      * Returns the column configs that return true by the passed function that is called with (columnConfig, index)
40034      * @param {Function} fn
40035      * @param {Object} scope (optional)
40036      * @return {Array} result
40037      */
40038     getColumnsBy : function(fn, scope){
40039         var r = [];
40040         for(var i = 0, len = this.config.length; i < len; i++){
40041             var c = this.config[i];
40042             if(fn.call(scope||this, c, i) === true){
40043                 r[r.length] = c;
40044             }
40045         }
40046         return r;
40047     },
40048
40049     /**
40050      * Returns true if the specified column is sortable.
40051      * @param {Number} col The column index
40052      * @return {Boolean}
40053      */
40054     isSortable : function(col){
40055         if(typeof this.config[col].sortable == "undefined"){
40056             return this.defaultSortable;
40057         }
40058         return this.config[col].sortable;
40059     },
40060
40061     /**
40062      * Returns the rendering (formatting) function defined for the column.
40063      * @param {Number} col The column index.
40064      * @return {Function} The function used to render the cell. See {@link #setRenderer}.
40065      */
40066     getRenderer : function(col){
40067         if(!this.config[col].renderer){
40068             return Roo.grid.ColumnModel.defaultRenderer;
40069         }
40070         return this.config[col].renderer;
40071     },
40072
40073     /**
40074      * Sets the rendering (formatting) function for a column.
40075      * @param {Number} col The column index
40076      * @param {Function} fn The function to use to process the cell's raw data
40077      * to return HTML markup for the grid view. The render function is called with
40078      * the following parameters:<ul>
40079      * <li>Data value.</li>
40080      * <li>Cell metadata. An object in which you may set the following attributes:<ul>
40081      * <li>css A CSS style string to apply to the table cell.</li>
40082      * <li>attr An HTML attribute definition string to apply to the data container element <i>within</i> the table cell.</li></ul>
40083      * <li>The {@link Roo.data.Record} from which the data was extracted.</li>
40084      * <li>Row index</li>
40085      * <li>Column index</li>
40086      * <li>The {@link Roo.data.Store} object from which the Record was extracted</li></ul>
40087      */
40088     setRenderer : function(col, fn){
40089         this.config[col].renderer = fn;
40090     },
40091
40092     /**
40093      * Returns the width for the specified column.
40094      * @param {Number} col The column index
40095      * @param (optional) {String} gridSize bootstrap width size.
40096      * @return {Number}
40097      */
40098     getColumnWidth : function(col, gridSize)
40099         {
40100                 var cfg = this.config[col];
40101                 
40102                 if (typeof(gridSize) == 'undefined') {
40103                         return cfg.width * 1 || this.defaultWidth;
40104                 }
40105                 if (gridSize === false) { // if we set it..
40106                         return cfg.width || false;
40107                 }
40108                 var sizes = ['xl', 'lg', 'md', 'sm', 'xs'];
40109                 
40110                 for(var i = sizes.indexOf(gridSize); i < sizes.length; i++) {
40111                         if (typeof(cfg[ sizes[i] ] ) == 'undefined') {
40112                                 continue;
40113                         }
40114                         return cfg[ sizes[i] ];
40115                 }
40116                 return 1;
40117                 
40118     },
40119
40120     /**
40121      * Sets the width for a column.
40122      * @param {Number} col The column index
40123      * @param {Number} width The new width
40124      */
40125     setColumnWidth : function(col, width, suppressEvent){
40126         this.config[col].width = width;
40127         this.totalWidth = null;
40128         if(!suppressEvent){
40129              this.fireEvent("widthchange", this, col, width);
40130         }
40131     },
40132
40133     /**
40134      * Returns the total width of all columns.
40135      * @param {Boolean} includeHidden True to include hidden column widths
40136      * @return {Number}
40137      */
40138     getTotalWidth : function(includeHidden){
40139         if(!this.totalWidth){
40140             this.totalWidth = 0;
40141             for(var i = 0, len = this.config.length; i < len; i++){
40142                 if(includeHidden || !this.isHidden(i)){
40143                     this.totalWidth += this.getColumnWidth(i);
40144                 }
40145             }
40146         }
40147         return this.totalWidth;
40148     },
40149
40150     /**
40151      * Returns the header for the specified column.
40152      * @param {Number} col The column index
40153      * @return {String}
40154      */
40155     getColumnHeader : function(col){
40156         return this.config[col].header;
40157     },
40158
40159     /**
40160      * Sets the header for a column.
40161      * @param {Number} col The column index
40162      * @param {String} header The new header
40163      */
40164     setColumnHeader : function(col, header){
40165         this.config[col].header = header;
40166         this.fireEvent("headerchange", this, col, header);
40167     },
40168
40169     /**
40170      * Returns the tooltip for the specified column.
40171      * @param {Number} col The column index
40172      * @return {String}
40173      */
40174     getColumnTooltip : function(col){
40175             return this.config[col].tooltip;
40176     },
40177     /**
40178      * Sets the tooltip for a column.
40179      * @param {Number} col The column index
40180      * @param {String} tooltip The new tooltip
40181      */
40182     setColumnTooltip : function(col, tooltip){
40183             this.config[col].tooltip = tooltip;
40184     },
40185
40186     /**
40187      * Returns the dataIndex for the specified column.
40188      * @param {Number} col The column index
40189      * @return {Number}
40190      */
40191     getDataIndex : function(col){
40192         return this.config[col].dataIndex;
40193     },
40194
40195     /**
40196      * Sets the dataIndex for a column.
40197      * @param {Number} col The column index
40198      * @param {Number} dataIndex The new dataIndex
40199      */
40200     setDataIndex : function(col, dataIndex){
40201         this.config[col].dataIndex = dataIndex;
40202     },
40203
40204     
40205     
40206     /**
40207      * Returns true if the cell is editable.
40208      * @param {Number} colIndex The column index
40209      * @param {Number} rowIndex The row index - this is nto actually used..?
40210      * @return {Boolean}
40211      */
40212     isCellEditable : function(colIndex, rowIndex){
40213         return (this.config[colIndex].editable || (typeof this.config[colIndex].editable == "undefined" && this.config[colIndex].editor)) ? true : false;
40214     },
40215
40216     /**
40217      * Returns the editor defined for the cell/column.
40218      * return false or null to disable editing.
40219      * @param {Number} colIndex The column index
40220      * @param {Number} rowIndex The row index
40221      * @return {Object}
40222      */
40223     getCellEditor : function(colIndex, rowIndex){
40224         return this.config[colIndex].editor;
40225     },
40226
40227     /**
40228      * Sets if a column is editable.
40229      * @param {Number} col The column index
40230      * @param {Boolean} editable True if the column is editable
40231      */
40232     setEditable : function(col, editable){
40233         this.config[col].editable = editable;
40234     },
40235
40236
40237     /**
40238      * Returns true if the column is hidden.
40239      * @param {Number} colIndex The column index
40240      * @return {Boolean}
40241      */
40242     isHidden : function(colIndex){
40243         return this.config[colIndex].hidden;
40244     },
40245
40246
40247     /**
40248      * Returns true if the column width cannot be changed
40249      */
40250     isFixed : function(colIndex){
40251         return this.config[colIndex].fixed;
40252     },
40253
40254     /**
40255      * Returns true if the column can be resized
40256      * @return {Boolean}
40257      */
40258     isResizable : function(colIndex){
40259         return colIndex >= 0 && this.config[colIndex].resizable !== false && this.config[colIndex].fixed !== true;
40260     },
40261     /**
40262      * Sets if a column is hidden.
40263      * @param {Number} colIndex The column index
40264      * @param {Boolean} hidden True if the column is hidden
40265      */
40266     setHidden : function(colIndex, hidden){
40267         this.config[colIndex].hidden = hidden;
40268         this.totalWidth = null;
40269         this.fireEvent("hiddenchange", this, colIndex, hidden);
40270     },
40271
40272     /**
40273      * Sets the editor for a column.
40274      * @param {Number} col The column index
40275      * @param {Object} editor The editor object
40276      */
40277     setEditor : function(col, editor){
40278         this.config[col].editor = editor;
40279     },
40280     /**
40281      * Add a column (experimental...) - defaults to adding to the end..
40282      * @param {Object} config 
40283     */
40284     addColumn : function(c)
40285     {
40286     
40287         var i = this.config.length;
40288         this.config[i] = c;
40289         
40290         if(typeof c.dataIndex == "undefined"){
40291             c.dataIndex = i;
40292         }
40293         if(typeof c.renderer == "string"){
40294             c.renderer = Roo.util.Format[c.renderer];
40295         }
40296         if(typeof c.id == "undefined"){
40297             c.id = Roo.id();
40298         }
40299         if(c.editor && c.editor.xtype){
40300             c.editor  = Roo.factory(c.editor, Roo.grid);
40301         }
40302         if(c.editor && c.editor.isFormField){
40303             c.editor = new Roo.grid.GridEditor(c.editor);
40304         }
40305         this.lookup[c.id] = c;
40306     }
40307     
40308 });
40309
40310 Roo.grid.ColumnModel.defaultRenderer = function(value)
40311 {
40312     if(typeof value == "object") {
40313         return value;
40314     }
40315         if(typeof value == "string" && value.length < 1){
40316             return "&#160;";
40317         }
40318     
40319         return String.format("{0}", value);
40320 };
40321
40322 // Alias for backwards compatibility
40323 Roo.grid.DefaultColumnModel = Roo.grid.ColumnModel;
40324 /*
40325  * Based on:
40326  * Ext JS Library 1.1.1
40327  * Copyright(c) 2006-2007, Ext JS, LLC.
40328  *
40329  * Originally Released Under LGPL - original licence link has changed is not relivant.
40330  *
40331  * Fork - LGPL
40332  * <script type="text/javascript">
40333  */
40334
40335 /**
40336  * @class Roo.grid.AbstractSelectionModel
40337  * @extends Roo.util.Observable
40338  * @abstract
40339  * Abstract base class for grid SelectionModels.  It provides the interface that should be
40340  * implemented by descendant classes.  This class should not be directly instantiated.
40341  * @constructor
40342  */
40343 Roo.grid.AbstractSelectionModel = function(){
40344     this.locked = false;
40345     Roo.grid.AbstractSelectionModel.superclass.constructor.call(this);
40346 };
40347
40348 Roo.extend(Roo.grid.AbstractSelectionModel, Roo.util.Observable,  {
40349     /** @ignore Called by the grid automatically. Do not call directly. */
40350     init : function(grid){
40351         this.grid = grid;
40352         this.initEvents();
40353     },
40354
40355     /**
40356      * Locks the selections.
40357      */
40358     lock : function(){
40359         this.locked = true;
40360     },
40361
40362     /**
40363      * Unlocks the selections.
40364      */
40365     unlock : function(){
40366         this.locked = false;
40367     },
40368
40369     /**
40370      * Returns true if the selections are locked.
40371      * @return {Boolean}
40372      */
40373     isLocked : function(){
40374         return this.locked;
40375     }
40376 });/*
40377  * Based on:
40378  * Ext JS Library 1.1.1
40379  * Copyright(c) 2006-2007, Ext JS, LLC.
40380  *
40381  * Originally Released Under LGPL - original licence link has changed is not relivant.
40382  *
40383  * Fork - LGPL
40384  * <script type="text/javascript">
40385  */
40386 /**
40387  * @extends Roo.grid.AbstractSelectionModel
40388  * @class Roo.grid.RowSelectionModel
40389  * The default SelectionModel used by {@link Roo.grid.Grid}.
40390  * It supports multiple selections and keyboard selection/navigation. 
40391  * @constructor
40392  * @param {Object} config
40393  */
40394 Roo.grid.RowSelectionModel = function(config){
40395     Roo.apply(this, config);
40396     this.selections = new Roo.util.MixedCollection(false, function(o){
40397         return o.id;
40398     });
40399
40400     this.last = false;
40401     this.lastActive = false;
40402
40403     this.addEvents({
40404         /**
40405         * @event selectionchange
40406         * Fires when the selection changes
40407         * @param {SelectionModel} this
40408         */
40409        "selectionchange" : true,
40410        /**
40411         * @event afterselectionchange
40412         * Fires after the selection changes (eg. by key press or clicking)
40413         * @param {SelectionModel} this
40414         */
40415        "afterselectionchange" : true,
40416        /**
40417         * @event beforerowselect
40418         * Fires when a row is selected being selected, return false to cancel.
40419         * @param {SelectionModel} this
40420         * @param {Number} rowIndex The selected index
40421         * @param {Boolean} keepExisting False if other selections will be cleared
40422         */
40423        "beforerowselect" : true,
40424        /**
40425         * @event rowselect
40426         * Fires when a row is selected.
40427         * @param {SelectionModel} this
40428         * @param {Number} rowIndex The selected index
40429         * @param {Roo.data.Record} r The record
40430         */
40431        "rowselect" : true,
40432        /**
40433         * @event rowdeselect
40434         * Fires when a row is deselected.
40435         * @param {SelectionModel} this
40436         * @param {Number} rowIndex The selected index
40437         */
40438         "rowdeselect" : true
40439     });
40440     Roo.grid.RowSelectionModel.superclass.constructor.call(this);
40441     this.locked = false;
40442 };
40443
40444 Roo.extend(Roo.grid.RowSelectionModel, Roo.grid.AbstractSelectionModel,  {
40445     /**
40446      * @cfg {Boolean} singleSelect
40447      * True to allow selection of only one row at a time (defaults to false)
40448      */
40449     singleSelect : false,
40450
40451     // private
40452     initEvents : function(){
40453
40454         if(!this.grid.enableDragDrop && !this.grid.enableDrag){
40455             this.grid.on("mousedown", this.handleMouseDown, this);
40456         }else{ // allow click to work like normal
40457             this.grid.on("rowclick", this.handleDragableRowClick, this);
40458         }
40459         // bootstrap does not have a view..
40460         var view = this.grid.view ? this.grid.view : this.grid;
40461         this.rowNav = new Roo.KeyNav(this.grid.getGridEl(), {
40462             "up" : function(e){
40463                 if(!e.shiftKey){
40464                     this.selectPrevious(e.shiftKey);
40465                 }else if(this.last !== false && this.lastActive !== false){
40466                     var last = this.last;
40467                     this.selectRange(this.last,  this.lastActive-1);
40468                     view.focusRow(this.lastActive);
40469                     if(last !== false){
40470                         this.last = last;
40471                     }
40472                 }else{
40473                     this.selectFirstRow();
40474                 }
40475                 this.fireEvent("afterselectionchange", this);
40476             },
40477             "down" : function(e){
40478                 if(!e.shiftKey){
40479                     this.selectNext(e.shiftKey);
40480                 }else if(this.last !== false && this.lastActive !== false){
40481                     var last = this.last;
40482                     this.selectRange(this.last,  this.lastActive+1);
40483                     view.focusRow(this.lastActive);
40484                     if(last !== false){
40485                         this.last = last;
40486                     }
40487                 }else{
40488                     this.selectFirstRow();
40489                 }
40490                 this.fireEvent("afterselectionchange", this);
40491             },
40492             scope: this
40493         });
40494
40495          
40496         view.on("refresh", this.onRefresh, this);
40497         view.on("rowupdated", this.onRowUpdated, this);
40498         view.on("rowremoved", this.onRemove, this);
40499     },
40500
40501     // private
40502     onRefresh : function(){
40503         var ds = this.grid.ds, i, v = this.grid.view;
40504         var s = this.selections;
40505         s.each(function(r){
40506             if((i = ds.indexOfId(r.id)) != -1){
40507                 v.onRowSelect(i);
40508                 s.add(ds.getAt(i)); // updating the selection relate data
40509             }else{
40510                 s.remove(r);
40511             }
40512         });
40513     },
40514
40515     // private
40516     onRemove : function(v, index, r){
40517         this.selections.remove(r);
40518     },
40519
40520     // private
40521     onRowUpdated : function(v, index, r){
40522         if(this.isSelected(r)){
40523             v.onRowSelect(index);
40524         }
40525     },
40526
40527     /**
40528      * Select records.
40529      * @param {Array} records The records to select
40530      * @param {Boolean} keepExisting (optional) True to keep existing selections
40531      */
40532     selectRecords : function(records, keepExisting){
40533         if(!keepExisting){
40534             this.clearSelections();
40535         }
40536         var ds = this.grid.ds;
40537         for(var i = 0, len = records.length; i < len; i++){
40538             this.selectRow(ds.indexOf(records[i]), true);
40539         }
40540     },
40541
40542     /**
40543      * Gets the number of selected rows.
40544      * @return {Number}
40545      */
40546     getCount : function(){
40547         return this.selections.length;
40548     },
40549
40550     /**
40551      * Selects the first row in the grid.
40552      */
40553     selectFirstRow : function(){
40554         this.selectRow(0);
40555     },
40556
40557     /**
40558      * Select the last row.
40559      * @param {Boolean} keepExisting (optional) True to keep existing selections
40560      */
40561     selectLastRow : function(keepExisting){
40562         this.selectRow(this.grid.ds.getCount() - 1, keepExisting);
40563     },
40564
40565     /**
40566      * Selects the row immediately following the last selected row.
40567      * @param {Boolean} keepExisting (optional) True to keep existing selections
40568      */
40569     selectNext : function(keepExisting){
40570         if(this.last !== false && (this.last+1) < this.grid.ds.getCount()){
40571             this.selectRow(this.last+1, keepExisting);
40572             var view = this.grid.view ? this.grid.view : this.grid;
40573             view.focusRow(this.last);
40574         }
40575     },
40576
40577     /**
40578      * Selects the row that precedes the last selected row.
40579      * @param {Boolean} keepExisting (optional) True to keep existing selections
40580      */
40581     selectPrevious : function(keepExisting){
40582         if(this.last){
40583             this.selectRow(this.last-1, keepExisting);
40584             var view = this.grid.view ? this.grid.view : this.grid;
40585             view.focusRow(this.last);
40586         }
40587     },
40588
40589     /**
40590      * Returns the selected records
40591      * @return {Array} Array of selected records
40592      */
40593     getSelections : function(){
40594         return [].concat(this.selections.items);
40595     },
40596
40597     /**
40598      * Returns the first selected record.
40599      * @return {Record}
40600      */
40601     getSelected : function(){
40602         return this.selections.itemAt(0);
40603     },
40604
40605
40606     /**
40607      * Clears all selections.
40608      */
40609     clearSelections : function(fast){
40610         if(this.locked) {
40611             return;
40612         }
40613         if(fast !== true){
40614             var ds = this.grid.ds;
40615             var s = this.selections;
40616             s.each(function(r){
40617                 this.deselectRow(ds.indexOfId(r.id));
40618             }, this);
40619             s.clear();
40620         }else{
40621             this.selections.clear();
40622         }
40623         this.last = false;
40624     },
40625
40626
40627     /**
40628      * Selects all rows.
40629      */
40630     selectAll : function(){
40631         if(this.locked) {
40632             return;
40633         }
40634         this.selections.clear();
40635         for(var i = 0, len = this.grid.ds.getCount(); i < len; i++){
40636             this.selectRow(i, true);
40637         }
40638     },
40639
40640     /**
40641      * Returns True if there is a selection.
40642      * @return {Boolean}
40643      */
40644     hasSelection : function(){
40645         return this.selections.length > 0;
40646     },
40647
40648     /**
40649      * Returns True if the specified row is selected.
40650      * @param {Number/Record} record The record or index of the record to check
40651      * @return {Boolean}
40652      */
40653     isSelected : function(index){
40654         var r = typeof index == "number" ? this.grid.ds.getAt(index) : index;
40655         return (r && this.selections.key(r.id) ? true : false);
40656     },
40657
40658     /**
40659      * Returns True if the specified record id is selected.
40660      * @param {String} id The id of record to check
40661      * @return {Boolean}
40662      */
40663     isIdSelected : function(id){
40664         return (this.selections.key(id) ? true : false);
40665     },
40666
40667     // private
40668     handleMouseDown : function(e, t)
40669     {
40670         var view = this.grid.view ? this.grid.view : this.grid;
40671         var rowIndex;
40672         if(this.isLocked() || (rowIndex = view.findRowIndex(t)) === false){
40673             return;
40674         };
40675         if(e.shiftKey && this.last !== false){
40676             var last = this.last;
40677             this.selectRange(last, rowIndex, e.ctrlKey);
40678             this.last = last; // reset the last
40679             view.focusRow(rowIndex);
40680         }else{
40681             var isSelected = this.isSelected(rowIndex);
40682             if(e.button !== 0 && isSelected){
40683                 view.focusRow(rowIndex);
40684             }else if(e.ctrlKey && isSelected){
40685                 this.deselectRow(rowIndex);
40686             }else if(!isSelected){
40687                 this.selectRow(rowIndex, e.button === 0 && (e.ctrlKey || e.shiftKey));
40688                 view.focusRow(rowIndex);
40689             }
40690         }
40691         this.fireEvent("afterselectionchange", this);
40692     },
40693     // private
40694     handleDragableRowClick :  function(grid, rowIndex, e) 
40695     {
40696         if(e.button === 0 && !e.shiftKey && !e.ctrlKey) {
40697             this.selectRow(rowIndex, false);
40698             var view = this.grid.view ? this.grid.view : this.grid;
40699             view.focusRow(rowIndex);
40700              this.fireEvent("afterselectionchange", this);
40701         }
40702     },
40703     
40704     /**
40705      * Selects multiple rows.
40706      * @param {Array} rows Array of the indexes of the row to select
40707      * @param {Boolean} keepExisting (optional) True to keep existing selections
40708      */
40709     selectRows : function(rows, keepExisting){
40710         if(!keepExisting){
40711             this.clearSelections();
40712         }
40713         for(var i = 0, len = rows.length; i < len; i++){
40714             this.selectRow(rows[i], true);
40715         }
40716     },
40717
40718     /**
40719      * Selects a range of rows. All rows in between startRow and endRow are also selected.
40720      * @param {Number} startRow The index of the first row in the range
40721      * @param {Number} endRow The index of the last row in the range
40722      * @param {Boolean} keepExisting (optional) True to retain existing selections
40723      */
40724     selectRange : function(startRow, endRow, keepExisting){
40725         if(this.locked) {
40726             return;
40727         }
40728         if(!keepExisting){
40729             this.clearSelections();
40730         }
40731         if(startRow <= endRow){
40732             for(var i = startRow; i <= endRow; i++){
40733                 this.selectRow(i, true);
40734             }
40735         }else{
40736             for(var i = startRow; i >= endRow; i--){
40737                 this.selectRow(i, true);
40738             }
40739         }
40740     },
40741
40742     /**
40743      * Deselects a range of rows. All rows in between startRow and endRow are also deselected.
40744      * @param {Number} startRow The index of the first row in the range
40745      * @param {Number} endRow The index of the last row in the range
40746      */
40747     deselectRange : function(startRow, endRow, preventViewNotify){
40748         if(this.locked) {
40749             return;
40750         }
40751         for(var i = startRow; i <= endRow; i++){
40752             this.deselectRow(i, preventViewNotify);
40753         }
40754     },
40755
40756     /**
40757      * Selects a row.
40758      * @param {Number} row The index of the row to select
40759      * @param {Boolean} keepExisting (optional) True to keep existing selections
40760      */
40761     selectRow : function(index, keepExisting, preventViewNotify){
40762         if(this.locked || (index < 0 || index >= this.grid.ds.getCount())) {
40763             return;
40764         }
40765         if(this.fireEvent("beforerowselect", this, index, keepExisting) !== false){
40766             if(!keepExisting || this.singleSelect){
40767                 this.clearSelections();
40768             }
40769             var r = this.grid.ds.getAt(index);
40770             this.selections.add(r);
40771             this.last = this.lastActive = index;
40772             if(!preventViewNotify){
40773                 var view = this.grid.view ? this.grid.view : this.grid;
40774                 view.onRowSelect(index);
40775             }
40776             this.fireEvent("rowselect", this, index, r);
40777             this.fireEvent("selectionchange", this);
40778         }
40779     },
40780
40781     /**
40782      * Deselects a row.
40783      * @param {Number} row The index of the row to deselect
40784      */
40785     deselectRow : function(index, preventViewNotify){
40786         if(this.locked) {
40787             return;
40788         }
40789         if(this.last == index){
40790             this.last = false;
40791         }
40792         if(this.lastActive == index){
40793             this.lastActive = false;
40794         }
40795         var r = this.grid.ds.getAt(index);
40796         this.selections.remove(r);
40797         if(!preventViewNotify){
40798             var view = this.grid.view ? this.grid.view : this.grid;
40799             view.onRowDeselect(index);
40800         }
40801         this.fireEvent("rowdeselect", this, index);
40802         this.fireEvent("selectionchange", this);
40803     },
40804
40805     // private
40806     restoreLast : function(){
40807         if(this._last){
40808             this.last = this._last;
40809         }
40810     },
40811
40812     // private
40813     acceptsNav : function(row, col, cm){
40814         return !cm.isHidden(col) && cm.isCellEditable(col, row);
40815     },
40816
40817     // private
40818     onEditorKey : function(field, e){
40819         var k = e.getKey(), newCell, g = this.grid, ed = g.activeEditor;
40820         if(k == e.TAB){
40821             e.stopEvent();
40822             ed.completeEdit();
40823             if(e.shiftKey){
40824                 newCell = g.walkCells(ed.row, ed.col-1, -1, this.acceptsNav, this);
40825             }else{
40826                 newCell = g.walkCells(ed.row, ed.col+1, 1, this.acceptsNav, this);
40827             }
40828         }else if(k == e.ENTER && !e.ctrlKey){
40829             e.stopEvent();
40830             ed.completeEdit();
40831             if(e.shiftKey){
40832                 newCell = g.walkCells(ed.row-1, ed.col, -1, this.acceptsNav, this);
40833             }else{
40834                 newCell = g.walkCells(ed.row+1, ed.col, 1, this.acceptsNav, this);
40835             }
40836         }else if(k == e.ESC){
40837             ed.cancelEdit();
40838         }
40839         if(newCell){
40840             g.startEditing(newCell[0], newCell[1]);
40841         }
40842     }
40843 });/*
40844  * Based on:
40845  * Ext JS Library 1.1.1
40846  * Copyright(c) 2006-2007, Ext JS, LLC.
40847  *
40848  * Originally Released Under LGPL - original licence link has changed is not relivant.
40849  *
40850  * Fork - LGPL
40851  * <script type="text/javascript">
40852  */
40853 /**
40854  * @class Roo.grid.CellSelectionModel
40855  * @extends Roo.grid.AbstractSelectionModel
40856  * This class provides the basic implementation for cell selection in a grid.
40857  * @constructor
40858  * @param {Object} config The object containing the configuration of this model.
40859  * @cfg {Boolean} enter_is_tab Enter behaves the same as tab. (eg. goes to next cell) default: false
40860  */
40861 Roo.grid.CellSelectionModel = function(config){
40862     Roo.apply(this, config);
40863
40864     this.selection = null;
40865
40866     this.addEvents({
40867         /**
40868              * @event beforerowselect
40869              * Fires before a cell is selected.
40870              * @param {SelectionModel} this
40871              * @param {Number} rowIndex The selected row index
40872              * @param {Number} colIndex The selected cell index
40873              */
40874             "beforecellselect" : true,
40875         /**
40876              * @event cellselect
40877              * Fires when a cell is selected.
40878              * @param {SelectionModel} this
40879              * @param {Number} rowIndex The selected row index
40880              * @param {Number} colIndex The selected cell index
40881              */
40882             "cellselect" : true,
40883         /**
40884              * @event selectionchange
40885              * Fires when the active selection changes.
40886              * @param {SelectionModel} this
40887              * @param {Object} selection null for no selection or an object (o) with two properties
40888                 <ul>
40889                 <li>o.record: the record object for the row the selection is in</li>
40890                 <li>o.cell: An array of [rowIndex, columnIndex]</li>
40891                 </ul>
40892              */
40893             "selectionchange" : true,
40894         /**
40895              * @event tabend
40896              * Fires when the tab (or enter) was pressed on the last editable cell
40897              * You can use this to trigger add new row.
40898              * @param {SelectionModel} this
40899              */
40900             "tabend" : true,
40901          /**
40902              * @event beforeeditnext
40903              * Fires before the next editable sell is made active
40904              * You can use this to skip to another cell or fire the tabend
40905              *    if you set cell to false
40906              * @param {Object} eventdata object : { cell : [ row, col ] } 
40907              */
40908             "beforeeditnext" : true
40909     });
40910     Roo.grid.CellSelectionModel.superclass.constructor.call(this);
40911 };
40912
40913 Roo.extend(Roo.grid.CellSelectionModel, Roo.grid.AbstractSelectionModel,  {
40914     
40915     enter_is_tab: false,
40916
40917     /** @ignore */
40918     initEvents : function(){
40919         this.grid.on("mousedown", this.handleMouseDown, this);
40920         this.grid.getGridEl().on(Roo.isIE ? "keydown" : "keypress", this.handleKeyDown, this);
40921         var view = this.grid.view;
40922         view.on("refresh", this.onViewChange, this);
40923         view.on("rowupdated", this.onRowUpdated, this);
40924         view.on("beforerowremoved", this.clearSelections, this);
40925         view.on("beforerowsinserted", this.clearSelections, this);
40926         if(this.grid.isEditor){
40927             this.grid.on("beforeedit", this.beforeEdit,  this);
40928         }
40929     },
40930
40931         //private
40932     beforeEdit : function(e){
40933         this.select(e.row, e.column, false, true, e.record);
40934     },
40935
40936         //private
40937     onRowUpdated : function(v, index, r){
40938         if(this.selection && this.selection.record == r){
40939             v.onCellSelect(index, this.selection.cell[1]);
40940         }
40941     },
40942
40943         //private
40944     onViewChange : function(){
40945         this.clearSelections(true);
40946     },
40947
40948         /**
40949          * Returns the currently selected cell,.
40950          * @return {Array} The selected cell (row, column) or null if none selected.
40951          */
40952     getSelectedCell : function(){
40953         return this.selection ? this.selection.cell : null;
40954     },
40955
40956     /**
40957      * Clears all selections.
40958      * @param {Boolean} true to prevent the gridview from being notified about the change.
40959      */
40960     clearSelections : function(preventNotify){
40961         var s = this.selection;
40962         if(s){
40963             if(preventNotify !== true){
40964                 this.grid.view.onCellDeselect(s.cell[0], s.cell[1]);
40965             }
40966             this.selection = null;
40967             this.fireEvent("selectionchange", this, null);
40968         }
40969     },
40970
40971     /**
40972      * Returns true if there is a selection.
40973      * @return {Boolean}
40974      */
40975     hasSelection : function(){
40976         return this.selection ? true : false;
40977     },
40978
40979     /** @ignore */
40980     handleMouseDown : function(e, t){
40981         var v = this.grid.getView();
40982         if(this.isLocked()){
40983             return;
40984         };
40985         var row = v.findRowIndex(t);
40986         var cell = v.findCellIndex(t);
40987         if(row !== false && cell !== false){
40988             this.select(row, cell);
40989         }
40990     },
40991
40992     /**
40993      * Selects a cell.
40994      * @param {Number} rowIndex
40995      * @param {Number} collIndex
40996      */
40997     select : function(rowIndex, colIndex, preventViewNotify, preventFocus, /*internal*/ r){
40998         if(this.fireEvent("beforecellselect", this, rowIndex, colIndex) !== false){
40999             this.clearSelections();
41000             r = r || this.grid.dataSource.getAt(rowIndex);
41001             this.selection = {
41002                 record : r,
41003                 cell : [rowIndex, colIndex]
41004             };
41005             if(!preventViewNotify){
41006                 var v = this.grid.getView();
41007                 v.onCellSelect(rowIndex, colIndex);
41008                 if(preventFocus !== true){
41009                     v.focusCell(rowIndex, colIndex);
41010                 }
41011             }
41012             this.fireEvent("cellselect", this, rowIndex, colIndex);
41013             this.fireEvent("selectionchange", this, this.selection);
41014         }
41015     },
41016
41017         //private
41018     isSelectable : function(rowIndex, colIndex, cm){
41019         return !cm.isHidden(colIndex);
41020     },
41021
41022     /** @ignore */
41023     handleKeyDown : function(e){
41024         //Roo.log('Cell Sel Model handleKeyDown');
41025         if(!e.isNavKeyPress()){
41026             return;
41027         }
41028         var g = this.grid, s = this.selection;
41029         if(!s){
41030             e.stopEvent();
41031             var cell = g.walkCells(0, 0, 1, this.isSelectable,  this);
41032             if(cell){
41033                 this.select(cell[0], cell[1]);
41034             }
41035             return;
41036         }
41037         var sm = this;
41038         var walk = function(row, col, step){
41039             return g.walkCells(row, col, step, sm.isSelectable,  sm);
41040         };
41041         var k = e.getKey(), r = s.cell[0], c = s.cell[1];
41042         var newCell;
41043
41044       
41045
41046         switch(k){
41047             case e.TAB:
41048                 // handled by onEditorKey
41049                 if (g.isEditor && g.editing) {
41050                     return;
41051                 }
41052                 if(e.shiftKey) {
41053                     newCell = walk(r, c-1, -1);
41054                 } else {
41055                     newCell = walk(r, c+1, 1);
41056                 }
41057                 break;
41058             
41059             case e.DOWN:
41060                newCell = walk(r+1, c, 1);
41061                 break;
41062             
41063             case e.UP:
41064                 newCell = walk(r-1, c, -1);
41065                 break;
41066             
41067             case e.RIGHT:
41068                 newCell = walk(r, c+1, 1);
41069                 break;
41070             
41071             case e.LEFT:
41072                 newCell = walk(r, c-1, -1);
41073                 break;
41074             
41075             case e.ENTER:
41076                 
41077                 if(g.isEditor && !g.editing){
41078                    g.startEditing(r, c);
41079                    e.stopEvent();
41080                    return;
41081                 }
41082                 
41083                 
41084              break;
41085         };
41086         if(newCell){
41087             this.select(newCell[0], newCell[1]);
41088             e.stopEvent();
41089             
41090         }
41091     },
41092
41093     acceptsNav : function(row, col, cm){
41094         return !cm.isHidden(col) && cm.isCellEditable(col, row);
41095     },
41096     /**
41097      * Selects a cell.
41098      * @param {Number} field (not used) - as it's normally used as a listener
41099      * @param {Number} e - event - fake it by using
41100      *
41101      * var e = Roo.EventObjectImpl.prototype;
41102      * e.keyCode = e.TAB
41103      *
41104      * 
41105      */
41106     onEditorKey : function(field, e){
41107         
41108         var k = e.getKey(),
41109             newCell,
41110             g = this.grid,
41111             ed = g.activeEditor,
41112             forward = false;
41113         ///Roo.log('onEditorKey' + k);
41114         
41115         
41116         if (this.enter_is_tab && k == e.ENTER) {
41117             k = e.TAB;
41118         }
41119         
41120         if(k == e.TAB){
41121             if(e.shiftKey){
41122                 newCell = g.walkCells(ed.row, ed.col-1, -1, this.acceptsNav, this);
41123             }else{
41124                 newCell = g.walkCells(ed.row, ed.col+1, 1, this.acceptsNav, this);
41125                 forward = true;
41126             }
41127             
41128             e.stopEvent();
41129             
41130         } else if(k == e.ENTER &&  !e.ctrlKey){
41131             ed.completeEdit();
41132             e.stopEvent();
41133             newCell = g.walkCells(ed.row, ed.col+1, 1, this.acceptsNav, this);
41134         
41135                 } else if(k == e.ESC){
41136             ed.cancelEdit();
41137         }
41138                 
41139         if (newCell) {
41140             var ecall = { cell : newCell, forward : forward };
41141             this.fireEvent('beforeeditnext', ecall );
41142             newCell = ecall.cell;
41143                         forward = ecall.forward;
41144         }
41145                 
41146         if(newCell){
41147             //Roo.log('next cell after edit');
41148             g.startEditing.defer(100, g, [newCell[0], newCell[1]]);
41149         } else if (forward) {
41150             // tabbed past last
41151             this.fireEvent.defer(100, this, ['tabend',this]);
41152         }
41153     }
41154 });/*
41155  * Based on:
41156  * Ext JS Library 1.1.1
41157  * Copyright(c) 2006-2007, Ext JS, LLC.
41158  *
41159  * Originally Released Under LGPL - original licence link has changed is not relivant.
41160  *
41161  * Fork - LGPL
41162  * <script type="text/javascript">
41163  */
41164  
41165 /**
41166  * @class Roo.grid.EditorGrid
41167  * @extends Roo.grid.Grid
41168  * Class for creating and editable grid.
41169  * @param {String/HTMLElement/Roo.Element} container The element into which this grid will be rendered - 
41170  * The container MUST have some type of size defined for the grid to fill. The container will be 
41171  * automatically set to position relative if it isn't already.
41172  * @param {Object} dataSource The data model to bind to
41173  * @param {Object} colModel The column model with info about this grid's columns
41174  */
41175 Roo.grid.EditorGrid = function(container, config){
41176     Roo.grid.EditorGrid.superclass.constructor.call(this, container, config);
41177     this.getGridEl().addClass("xedit-grid");
41178
41179     if(!this.selModel){
41180         this.selModel = new Roo.grid.CellSelectionModel();
41181     }
41182
41183     this.activeEditor = null;
41184
41185         this.addEvents({
41186             /**
41187              * @event beforeedit
41188              * Fires before cell editing is triggered. The edit event object has the following properties <br />
41189              * <ul style="padding:5px;padding-left:16px;">
41190              * <li>grid - This grid</li>
41191              * <li>record - The record being edited</li>
41192              * <li>field - The field name being edited</li>
41193              * <li>value - The value for the field being edited.</li>
41194              * <li>row - The grid row index</li>
41195              * <li>column - The grid column index</li>
41196              * <li>cancel - Set this to true to cancel the edit or return false from your handler.</li>
41197              * </ul>
41198              * @param {Object} e An edit event (see above for description)
41199              */
41200             "beforeedit" : true,
41201             /**
41202              * @event afteredit
41203              * Fires after a cell is edited. <br />
41204              * <ul style="padding:5px;padding-left:16px;">
41205              * <li>grid - This grid</li>
41206              * <li>record - The record being edited</li>
41207              * <li>field - The field name being edited</li>
41208              * <li>value - The value being set</li>
41209              * <li>originalValue - The original value for the field, before the edit.</li>
41210              * <li>row - The grid row index</li>
41211              * <li>column - The grid column index</li>
41212              * </ul>
41213              * @param {Object} e An edit event (see above for description)
41214              */
41215             "afteredit" : true,
41216             /**
41217              * @event validateedit
41218              * Fires after a cell is edited, but before the value is set in the record. 
41219          * You can use this to modify the value being set in the field, Return false
41220              * to cancel the change. The edit event object has the following properties <br />
41221              * <ul style="padding:5px;padding-left:16px;">
41222          * <li>editor - This editor</li>
41223              * <li>grid - This grid</li>
41224              * <li>record - The record being edited</li>
41225              * <li>field - The field name being edited</li>
41226              * <li>value - The value being set</li>
41227              * <li>originalValue - The original value for the field, before the edit.</li>
41228              * <li>row - The grid row index</li>
41229              * <li>column - The grid column index</li>
41230              * <li>cancel - Set this to true to cancel the edit or return false from your handler.</li>
41231              * </ul>
41232              * @param {Object} e An edit event (see above for description)
41233              */
41234             "validateedit" : true
41235         });
41236     this.on("bodyscroll", this.stopEditing,  this);
41237     this.on(this.clicksToEdit == 1 ? "cellclick" : "celldblclick", this.onCellDblClick,  this);
41238 };
41239
41240 Roo.extend(Roo.grid.EditorGrid, Roo.grid.Grid, {
41241     /**
41242      * @cfg {Number} clicksToEdit
41243      * The number of clicks on a cell required to display the cell's editor (defaults to 2)
41244      */
41245     clicksToEdit: 2,
41246
41247     // private
41248     isEditor : true,
41249     // private
41250     trackMouseOver: false, // causes very odd FF errors
41251
41252     onCellDblClick : function(g, row, col){
41253         this.startEditing(row, col);
41254     },
41255
41256     onEditComplete : function(ed, value, startValue){
41257         this.editing = false;
41258         this.activeEditor = null;
41259         ed.un("specialkey", this.selModel.onEditorKey, this.selModel);
41260         var r = ed.record;
41261         var field = this.colModel.getDataIndex(ed.col);
41262         var e = {
41263             grid: this,
41264             record: r,
41265             field: field,
41266             originalValue: startValue,
41267             value: value,
41268             row: ed.row,
41269             column: ed.col,
41270             cancel:false,
41271             editor: ed
41272         };
41273         var cell = Roo.get(this.view.getCell(ed.row,ed.col));
41274         cell.show();
41275           
41276         if(String(value) !== String(startValue)){
41277             
41278             if(this.fireEvent("validateedit", e) !== false && !e.cancel){
41279                 r.set(field, e.value);
41280                 // if we are dealing with a combo box..
41281                 // then we also set the 'name' colum to be the displayField
41282                 if (ed.field.displayField && ed.field.name) {
41283                     r.set(ed.field.name, ed.field.el.dom.value);
41284                 }
41285                 
41286                 delete e.cancel; //?? why!!!
41287                 this.fireEvent("afteredit", e);
41288             }
41289         } else {
41290             this.fireEvent("afteredit", e); // always fire it!
41291         }
41292         this.view.focusCell(ed.row, ed.col);
41293     },
41294
41295     /**
41296      * Starts editing the specified for the specified row/column
41297      * @param {Number} rowIndex
41298      * @param {Number} colIndex
41299      */
41300     startEditing : function(row, col){
41301         this.stopEditing();
41302         if(this.colModel.isCellEditable(col, row)){
41303             this.view.ensureVisible(row, col, true);
41304           
41305             var r = this.dataSource.getAt(row);
41306             var field = this.colModel.getDataIndex(col);
41307             var cell = Roo.get(this.view.getCell(row,col));
41308             var e = {
41309                 grid: this,
41310                 record: r,
41311                 field: field,
41312                 value: r.data[field],
41313                 row: row,
41314                 column: col,
41315                 cancel:false 
41316             };
41317             if(this.fireEvent("beforeedit", e) !== false && !e.cancel){
41318                 this.editing = true;
41319                 var ed = this.colModel.getCellEditor(col, row);
41320                 
41321                 if (!ed) {
41322                     return;
41323                 }
41324                 if(!ed.rendered){
41325                     ed.render(ed.parentEl || document.body);
41326                 }
41327                 ed.field.reset();
41328                
41329                 cell.hide();
41330                 
41331                 (function(){ // complex but required for focus issues in safari, ie and opera
41332                     ed.row = row;
41333                     ed.col = col;
41334                     ed.record = r;
41335                     ed.on("complete",   this.onEditComplete,        this,       {single: true});
41336                     ed.on("specialkey", this.selModel.onEditorKey,  this.selModel);
41337                     this.activeEditor = ed;
41338                     var v = r.data[field];
41339                     ed.startEdit(this.view.getCell(row, col), v);
41340                     // combo's with 'displayField and name set
41341                     if (ed.field.displayField && ed.field.name) {
41342                         ed.field.el.dom.value = r.data[ed.field.name];
41343                     }
41344                     
41345                     
41346                 }).defer(50, this);
41347             }
41348         }
41349     },
41350         
41351     /**
41352      * Stops any active editing
41353      */
41354     stopEditing : function(){
41355         if(this.activeEditor){
41356             this.activeEditor.completeEdit();
41357         }
41358         this.activeEditor = null;
41359     },
41360         
41361          /**
41362      * Called to get grid's drag proxy text, by default returns this.ddText.
41363      * @return {String}
41364      */
41365     getDragDropText : function(){
41366         var count = this.selModel.getSelectedCell() ? 1 : 0;
41367         return String.format(this.ddText, count, count == 1 ? '' : 's');
41368     }
41369         
41370 });/*
41371  * Based on:
41372  * Ext JS Library 1.1.1
41373  * Copyright(c) 2006-2007, Ext JS, LLC.
41374  *
41375  * Originally Released Under LGPL - original licence link has changed is not relivant.
41376  *
41377  * Fork - LGPL
41378  * <script type="text/javascript">
41379  */
41380
41381 // private - not really -- you end up using it !
41382 // This is a support class used internally by the Grid components
41383
41384 /**
41385  * @class Roo.grid.GridEditor
41386  * @extends Roo.Editor
41387  * Class for creating and editable grid elements.
41388  * @param {Object} config any settings (must include field)
41389  */
41390 Roo.grid.GridEditor = function(field, config){
41391     if (!config && field.field) {
41392         config = field;
41393         field = Roo.factory(config.field, Roo.form);
41394     }
41395     Roo.grid.GridEditor.superclass.constructor.call(this, field, config);
41396     field.monitorTab = false;
41397 };
41398
41399 Roo.extend(Roo.grid.GridEditor, Roo.Editor, {
41400     
41401     /**
41402      * @cfg {Roo.form.Field} field Field to wrap (or xtyped)
41403      */
41404     
41405     alignment: "tl-tl",
41406     autoSize: "width",
41407     hideEl : false,
41408     cls: "x-small-editor x-grid-editor",
41409     shim:false,
41410     shadow:"frame"
41411 });/*
41412  * Based on:
41413  * Ext JS Library 1.1.1
41414  * Copyright(c) 2006-2007, Ext JS, LLC.
41415  *
41416  * Originally Released Under LGPL - original licence link has changed is not relivant.
41417  *
41418  * Fork - LGPL
41419  * <script type="text/javascript">
41420  */
41421   
41422
41423   
41424 Roo.grid.PropertyRecord = Roo.data.Record.create([
41425     {name:'name',type:'string'},  'value'
41426 ]);
41427
41428
41429 Roo.grid.PropertyStore = function(grid, source){
41430     this.grid = grid;
41431     this.store = new Roo.data.Store({
41432         recordType : Roo.grid.PropertyRecord
41433     });
41434     this.store.on('update', this.onUpdate,  this);
41435     if(source){
41436         this.setSource(source);
41437     }
41438     Roo.grid.PropertyStore.superclass.constructor.call(this);
41439 };
41440
41441
41442
41443 Roo.extend(Roo.grid.PropertyStore, Roo.util.Observable, {
41444     setSource : function(o){
41445         this.source = o;
41446         this.store.removeAll();
41447         var data = [];
41448         for(var k in o){
41449             if(this.isEditableValue(o[k])){
41450                 data.push(new Roo.grid.PropertyRecord({name: k, value: o[k]}, k));
41451             }
41452         }
41453         this.store.loadRecords({records: data}, {}, true);
41454     },
41455
41456     onUpdate : function(ds, record, type){
41457         if(type == Roo.data.Record.EDIT){
41458             var v = record.data['value'];
41459             var oldValue = record.modified['value'];
41460             if(this.grid.fireEvent('beforepropertychange', this.source, record.id, v, oldValue) !== false){
41461                 this.source[record.id] = v;
41462                 record.commit();
41463                 this.grid.fireEvent('propertychange', this.source, record.id, v, oldValue);
41464             }else{
41465                 record.reject();
41466             }
41467         }
41468     },
41469
41470     getProperty : function(row){
41471        return this.store.getAt(row);
41472     },
41473
41474     isEditableValue: function(val){
41475         if(val && val instanceof Date){
41476             return true;
41477         }else if(typeof val == 'object' || typeof val == 'function'){
41478             return false;
41479         }
41480         return true;
41481     },
41482
41483     setValue : function(prop, value){
41484         this.source[prop] = value;
41485         this.store.getById(prop).set('value', value);
41486     },
41487
41488     getSource : function(){
41489         return this.source;
41490     }
41491 });
41492
41493 Roo.grid.PropertyColumnModel = function(grid, store){
41494     this.grid = grid;
41495     var g = Roo.grid;
41496     g.PropertyColumnModel.superclass.constructor.call(this, [
41497         {header: this.nameText, sortable: true, dataIndex:'name', id: 'name'},
41498         {header: this.valueText, resizable:false, dataIndex: 'value', id: 'value'}
41499     ]);
41500     this.store = store;
41501     this.bselect = Roo.DomHelper.append(document.body, {
41502         tag: 'select', style:'display:none', cls: 'x-grid-editor', children: [
41503             {tag: 'option', value: 'true', html: 'true'},
41504             {tag: 'option', value: 'false', html: 'false'}
41505         ]
41506     });
41507     Roo.id(this.bselect);
41508     var f = Roo.form;
41509     this.editors = {
41510         'date' : new g.GridEditor(new f.DateField({selectOnFocus:true})),
41511         'string' : new g.GridEditor(new f.TextField({selectOnFocus:true})),
41512         'number' : new g.GridEditor(new f.NumberField({selectOnFocus:true, style:'text-align:left;'})),
41513         'int' : new g.GridEditor(new f.NumberField({selectOnFocus:true, allowDecimals:false, style:'text-align:left;'})),
41514         'boolean' : new g.GridEditor(new f.Field({el:this.bselect,selectOnFocus:true}))
41515     };
41516     this.renderCellDelegate = this.renderCell.createDelegate(this);
41517     this.renderPropDelegate = this.renderProp.createDelegate(this);
41518 };
41519
41520 Roo.extend(Roo.grid.PropertyColumnModel, Roo.grid.ColumnModel, {
41521     
41522     
41523     nameText : 'Name',
41524     valueText : 'Value',
41525     
41526     dateFormat : 'm/j/Y',
41527     
41528     
41529     renderDate : function(dateVal){
41530         return dateVal.dateFormat(this.dateFormat);
41531     },
41532
41533     renderBool : function(bVal){
41534         return bVal ? 'true' : 'false';
41535     },
41536
41537     isCellEditable : function(colIndex, rowIndex){
41538         return colIndex == 1;
41539     },
41540
41541     getRenderer : function(col){
41542         return col == 1 ?
41543             this.renderCellDelegate : this.renderPropDelegate;
41544     },
41545
41546     renderProp : function(v){
41547         return this.getPropertyName(v);
41548     },
41549
41550     renderCell : function(val){
41551         var rv = val;
41552         if(val instanceof Date){
41553             rv = this.renderDate(val);
41554         }else if(typeof val == 'boolean'){
41555             rv = this.renderBool(val);
41556         }
41557         return Roo.util.Format.htmlEncode(rv);
41558     },
41559
41560     getPropertyName : function(name){
41561         var pn = this.grid.propertyNames;
41562         return pn && pn[name] ? pn[name] : name;
41563     },
41564
41565     getCellEditor : function(colIndex, rowIndex){
41566         var p = this.store.getProperty(rowIndex);
41567         var n = p.data['name'], val = p.data['value'];
41568         
41569         if(typeof(this.grid.customEditors[n]) == 'string'){
41570             return this.editors[this.grid.customEditors[n]];
41571         }
41572         if(typeof(this.grid.customEditors[n]) != 'undefined'){
41573             return this.grid.customEditors[n];
41574         }
41575         if(val instanceof Date){
41576             return this.editors['date'];
41577         }else if(typeof val == 'number'){
41578             return this.editors['number'];
41579         }else if(typeof val == 'boolean'){
41580             return this.editors['boolean'];
41581         }else{
41582             return this.editors['string'];
41583         }
41584     }
41585 });
41586
41587 /**
41588  * @class Roo.grid.PropertyGrid
41589  * @extends Roo.grid.EditorGrid
41590  * This class represents the  interface of a component based property grid control.
41591  * <br><br>Usage:<pre><code>
41592  var grid = new Roo.grid.PropertyGrid("my-container-id", {
41593       
41594  });
41595  // set any options
41596  grid.render();
41597  * </code></pre>
41598   
41599  * @constructor
41600  * @param {String/HTMLElement/Roo.Element} container The element into which this grid will be rendered -
41601  * The container MUST have some type of size defined for the grid to fill. The container will be
41602  * automatically set to position relative if it isn't already.
41603  * @param {Object} config A config object that sets properties on this grid.
41604  */
41605 Roo.grid.PropertyGrid = function(container, config){
41606     config = config || {};
41607     var store = new Roo.grid.PropertyStore(this);
41608     this.store = store;
41609     var cm = new Roo.grid.PropertyColumnModel(this, store);
41610     store.store.sort('name', 'ASC');
41611     Roo.grid.PropertyGrid.superclass.constructor.call(this, container, Roo.apply({
41612         ds: store.store,
41613         cm: cm,
41614         enableColLock:false,
41615         enableColumnMove:false,
41616         stripeRows:false,
41617         trackMouseOver: false,
41618         clicksToEdit:1
41619     }, config));
41620     this.getGridEl().addClass('x-props-grid');
41621     this.lastEditRow = null;
41622     this.on('columnresize', this.onColumnResize, this);
41623     this.addEvents({
41624          /**
41625              * @event beforepropertychange
41626              * Fires before a property changes (return false to stop?)
41627              * @param {Roo.grid.PropertyGrid} grid property grid? (check could be store)
41628              * @param {String} id Record Id
41629              * @param {String} newval New Value
41630          * @param {String} oldval Old Value
41631              */
41632         "beforepropertychange": true,
41633         /**
41634              * @event propertychange
41635              * Fires after a property changes
41636              * @param {Roo.grid.PropertyGrid} grid property grid? (check could be store)
41637              * @param {String} id Record Id
41638              * @param {String} newval New Value
41639          * @param {String} oldval Old Value
41640              */
41641         "propertychange": true
41642     });
41643     this.customEditors = this.customEditors || {};
41644 };
41645 Roo.extend(Roo.grid.PropertyGrid, Roo.grid.EditorGrid, {
41646     
41647      /**
41648      * @cfg {Object} customEditors map of colnames=> custom editors.
41649      * the custom editor can be one of the standard ones (date|string|number|int|boolean), or a
41650      * grid editor eg. Roo.grid.GridEditor(new Roo.form.TextArea({selectOnFocus:true})),
41651      * false disables editing of the field.
41652          */
41653     
41654       /**
41655      * @cfg {Object} propertyNames map of property Names to their displayed value
41656          */
41657     
41658     render : function(){
41659         Roo.grid.PropertyGrid.superclass.render.call(this);
41660         this.autoSize.defer(100, this);
41661     },
41662
41663     autoSize : function(){
41664         Roo.grid.PropertyGrid.superclass.autoSize.call(this);
41665         if(this.view){
41666             this.view.fitColumns();
41667         }
41668     },
41669
41670     onColumnResize : function(){
41671         this.colModel.setColumnWidth(1, this.container.getWidth(true)-this.colModel.getColumnWidth(0));
41672         this.autoSize();
41673     },
41674     /**
41675      * Sets the data for the Grid
41676      * accepts a Key => Value object of all the elements avaiable.
41677      * @param {Object} data  to appear in grid.
41678      */
41679     setSource : function(source){
41680         this.store.setSource(source);
41681         //this.autoSize();
41682     },
41683     /**
41684      * Gets all the data from the grid.
41685      * @return {Object} data  data stored in grid
41686      */
41687     getSource : function(){
41688         return this.store.getSource();
41689     }
41690 });/*
41691   
41692  * Licence LGPL
41693  
41694  */
41695  
41696 /**
41697  * @class Roo.grid.Calendar
41698  * @extends Roo.grid.Grid
41699  * This class extends the Grid to provide a calendar widget
41700  * <br><br>Usage:<pre><code>
41701  var grid = new Roo.grid.Calendar("my-container-id", {
41702      ds: myDataStore,
41703      cm: myColModel,
41704      selModel: mySelectionModel,
41705      autoSizeColumns: true,
41706      monitorWindowResize: false,
41707      trackMouseOver: true
41708      eventstore : real data store..
41709  });
41710  // set any options
41711  grid.render();
41712   
41713   * @constructor
41714  * @param {String/HTMLElement/Roo.Element} container The element into which this grid will be rendered -
41715  * The container MUST have some type of size defined for the grid to fill. The container will be
41716  * automatically set to position relative if it isn't already.
41717  * @param {Object} config A config object that sets properties on this grid.
41718  */
41719 Roo.grid.Calendar = function(container, config){
41720         // initialize the container
41721         this.container = Roo.get(container);
41722         this.container.update("");
41723         this.container.setStyle("overflow", "hidden");
41724     this.container.addClass('x-grid-container');
41725
41726     this.id = this.container.id;
41727
41728     Roo.apply(this, config);
41729     // check and correct shorthanded configs
41730     
41731     var rows = [];
41732     var d =1;
41733     for (var r = 0;r < 6;r++) {
41734         
41735         rows[r]=[];
41736         for (var c =0;c < 7;c++) {
41737             rows[r][c]= '';
41738         }
41739     }
41740     if (this.eventStore) {
41741         this.eventStore= Roo.factory(this.eventStore, Roo.data);
41742         this.eventStore.on('load',this.onLoad, this);
41743         this.eventStore.on('beforeload',this.clearEvents, this);
41744          
41745     }
41746     
41747     this.dataSource = new Roo.data.Store({
41748             proxy: new Roo.data.MemoryProxy(rows),
41749             reader: new Roo.data.ArrayReader({}, [
41750                    'weekday0', 'weekday1', 'weekday2', 'weekday3', 'weekday4', 'weekday5', 'weekday6' ])
41751     });
41752
41753     this.dataSource.load();
41754     this.ds = this.dataSource;
41755     this.ds.xmodule = this.xmodule || false;
41756     
41757     
41758     var cellRender = function(v,x,r)
41759     {
41760         return String.format(
41761             '<div class="fc-day  fc-widget-content"><div>' +
41762                 '<div class="fc-event-container"></div>' +
41763                 '<div class="fc-day-number">{0}</div>'+
41764                 
41765                 '<div class="fc-day-content"><div style="position:relative"></div></div>' +
41766             '</div></div>', v);
41767     
41768     }
41769     
41770     
41771     this.colModel = new Roo.grid.ColumnModel( [
41772         {
41773             xtype: 'ColumnModel',
41774             xns: Roo.grid,
41775             dataIndex : 'weekday0',
41776             header : 'Sunday',
41777             renderer : cellRender
41778         },
41779         {
41780             xtype: 'ColumnModel',
41781             xns: Roo.grid,
41782             dataIndex : 'weekday1',
41783             header : 'Monday',
41784             renderer : cellRender
41785         },
41786         {
41787             xtype: 'ColumnModel',
41788             xns: Roo.grid,
41789             dataIndex : 'weekday2',
41790             header : 'Tuesday',
41791             renderer : cellRender
41792         },
41793         {
41794             xtype: 'ColumnModel',
41795             xns: Roo.grid,
41796             dataIndex : 'weekday3',
41797             header : 'Wednesday',
41798             renderer : cellRender
41799         },
41800         {
41801             xtype: 'ColumnModel',
41802             xns: Roo.grid,
41803             dataIndex : 'weekday4',
41804             header : 'Thursday',
41805             renderer : cellRender
41806         },
41807         {
41808             xtype: 'ColumnModel',
41809             xns: Roo.grid,
41810             dataIndex : 'weekday5',
41811             header : 'Friday',
41812             renderer : cellRender
41813         },
41814         {
41815             xtype: 'ColumnModel',
41816             xns: Roo.grid,
41817             dataIndex : 'weekday6',
41818             header : 'Saturday',
41819             renderer : cellRender
41820         }
41821     ]);
41822     this.cm = this.colModel;
41823     this.cm.xmodule = this.xmodule || false;
41824  
41825         
41826           
41827     //this.selModel = new Roo.grid.CellSelectionModel();
41828     //this.sm = this.selModel;
41829     //this.selModel.init(this);
41830     
41831     
41832     if(this.width){
41833         this.container.setWidth(this.width);
41834     }
41835
41836     if(this.height){
41837         this.container.setHeight(this.height);
41838     }
41839     /** @private */
41840         this.addEvents({
41841         // raw events
41842         /**
41843          * @event click
41844          * The raw click event for the entire grid.
41845          * @param {Roo.EventObject} e
41846          */
41847         "click" : true,
41848         /**
41849          * @event dblclick
41850          * The raw dblclick event for the entire grid.
41851          * @param {Roo.EventObject} e
41852          */
41853         "dblclick" : true,
41854         /**
41855          * @event contextmenu
41856          * The raw contextmenu event for the entire grid.
41857          * @param {Roo.EventObject} e
41858          */
41859         "contextmenu" : true,
41860         /**
41861          * @event mousedown
41862          * The raw mousedown event for the entire grid.
41863          * @param {Roo.EventObject} e
41864          */
41865         "mousedown" : true,
41866         /**
41867          * @event mouseup
41868          * The raw mouseup event for the entire grid.
41869          * @param {Roo.EventObject} e
41870          */
41871         "mouseup" : true,
41872         /**
41873          * @event mouseover
41874          * The raw mouseover event for the entire grid.
41875          * @param {Roo.EventObject} e
41876          */
41877         "mouseover" : true,
41878         /**
41879          * @event mouseout
41880          * The raw mouseout event for the entire grid.
41881          * @param {Roo.EventObject} e
41882          */
41883         "mouseout" : true,
41884         /**
41885          * @event keypress
41886          * The raw keypress event for the entire grid.
41887          * @param {Roo.EventObject} e
41888          */
41889         "keypress" : true,
41890         /**
41891          * @event keydown
41892          * The raw keydown event for the entire grid.
41893          * @param {Roo.EventObject} e
41894          */
41895         "keydown" : true,
41896
41897         // custom events
41898
41899         /**
41900          * @event cellclick
41901          * Fires when a cell is clicked
41902          * @param {Grid} this
41903          * @param {Number} rowIndex
41904          * @param {Number} columnIndex
41905          * @param {Roo.EventObject} e
41906          */
41907         "cellclick" : true,
41908         /**
41909          * @event celldblclick
41910          * Fires when a cell is double clicked
41911          * @param {Grid} this
41912          * @param {Number} rowIndex
41913          * @param {Number} columnIndex
41914          * @param {Roo.EventObject} e
41915          */
41916         "celldblclick" : true,
41917         /**
41918          * @event rowclick
41919          * Fires when a row is clicked
41920          * @param {Grid} this
41921          * @param {Number} rowIndex
41922          * @param {Roo.EventObject} e
41923          */
41924         "rowclick" : true,
41925         /**
41926          * @event rowdblclick
41927          * Fires when a row is double clicked
41928          * @param {Grid} this
41929          * @param {Number} rowIndex
41930          * @param {Roo.EventObject} e
41931          */
41932         "rowdblclick" : true,
41933         /**
41934          * @event headerclick
41935          * Fires when a header is clicked
41936          * @param {Grid} this
41937          * @param {Number} columnIndex
41938          * @param {Roo.EventObject} e
41939          */
41940         "headerclick" : true,
41941         /**
41942          * @event headerdblclick
41943          * Fires when a header cell is double clicked
41944          * @param {Grid} this
41945          * @param {Number} columnIndex
41946          * @param {Roo.EventObject} e
41947          */
41948         "headerdblclick" : true,
41949         /**
41950          * @event rowcontextmenu
41951          * Fires when a row is right clicked
41952          * @param {Grid} this
41953          * @param {Number} rowIndex
41954          * @param {Roo.EventObject} e
41955          */
41956         "rowcontextmenu" : true,
41957         /**
41958          * @event cellcontextmenu
41959          * Fires when a cell is right clicked
41960          * @param {Grid} this
41961          * @param {Number} rowIndex
41962          * @param {Number} cellIndex
41963          * @param {Roo.EventObject} e
41964          */
41965          "cellcontextmenu" : true,
41966         /**
41967          * @event headercontextmenu
41968          * Fires when a header is right clicked
41969          * @param {Grid} this
41970          * @param {Number} columnIndex
41971          * @param {Roo.EventObject} e
41972          */
41973         "headercontextmenu" : true,
41974         /**
41975          * @event bodyscroll
41976          * Fires when the body element is scrolled
41977          * @param {Number} scrollLeft
41978          * @param {Number} scrollTop
41979          */
41980         "bodyscroll" : true,
41981         /**
41982          * @event columnresize
41983          * Fires when the user resizes a column
41984          * @param {Number} columnIndex
41985          * @param {Number} newSize
41986          */
41987         "columnresize" : true,
41988         /**
41989          * @event columnmove
41990          * Fires when the user moves a column
41991          * @param {Number} oldIndex
41992          * @param {Number} newIndex
41993          */
41994         "columnmove" : true,
41995         /**
41996          * @event startdrag
41997          * Fires when row(s) start being dragged
41998          * @param {Grid} this
41999          * @param {Roo.GridDD} dd The drag drop object
42000          * @param {event} e The raw browser event
42001          */
42002         "startdrag" : true,
42003         /**
42004          * @event enddrag
42005          * Fires when a drag operation is complete
42006          * @param {Grid} this
42007          * @param {Roo.GridDD} dd The drag drop object
42008          * @param {event} e The raw browser event
42009          */
42010         "enddrag" : true,
42011         /**
42012          * @event dragdrop
42013          * Fires when dragged row(s) are dropped on a valid DD target
42014          * @param {Grid} this
42015          * @param {Roo.GridDD} dd The drag drop object
42016          * @param {String} targetId The target drag drop object
42017          * @param {event} e The raw browser event
42018          */
42019         "dragdrop" : true,
42020         /**
42021          * @event dragover
42022          * Fires while row(s) are being dragged. "targetId" is the id of the Yahoo.util.DD object the selected rows are being dragged over.
42023          * @param {Grid} this
42024          * @param {Roo.GridDD} dd The drag drop object
42025          * @param {String} targetId The target drag drop object
42026          * @param {event} e The raw browser event
42027          */
42028         "dragover" : true,
42029         /**
42030          * @event dragenter
42031          *  Fires when the dragged row(s) first cross another DD target while being dragged
42032          * @param {Grid} this
42033          * @param {Roo.GridDD} dd The drag drop object
42034          * @param {String} targetId The target drag drop object
42035          * @param {event} e The raw browser event
42036          */
42037         "dragenter" : true,
42038         /**
42039          * @event dragout
42040          * Fires when the dragged row(s) leave another DD target while being dragged
42041          * @param {Grid} this
42042          * @param {Roo.GridDD} dd The drag drop object
42043          * @param {String} targetId The target drag drop object
42044          * @param {event} e The raw browser event
42045          */
42046         "dragout" : true,
42047         /**
42048          * @event rowclass
42049          * Fires when a row is rendered, so you can change add a style to it.
42050          * @param {GridView} gridview   The grid view
42051          * @param {Object} rowcfg   contains record  rowIndex and rowClass - set rowClass to add a style.
42052          */
42053         'rowclass' : true,
42054
42055         /**
42056          * @event render
42057          * Fires when the grid is rendered
42058          * @param {Grid} grid
42059          */
42060         'render' : true,
42061             /**
42062              * @event select
42063              * Fires when a date is selected
42064              * @param {DatePicker} this
42065              * @param {Date} date The selected date
42066              */
42067         'select': true,
42068         /**
42069              * @event monthchange
42070              * Fires when the displayed month changes 
42071              * @param {DatePicker} this
42072              * @param {Date} date The selected month
42073              */
42074         'monthchange': true,
42075         /**
42076              * @event evententer
42077              * Fires when mouse over an event
42078              * @param {Calendar} this
42079              * @param {event} Event
42080              */
42081         'evententer': true,
42082         /**
42083              * @event eventleave
42084              * Fires when the mouse leaves an
42085              * @param {Calendar} this
42086              * @param {event}
42087              */
42088         'eventleave': true,
42089         /**
42090              * @event eventclick
42091              * Fires when the mouse click an
42092              * @param {Calendar} this
42093              * @param {event}
42094              */
42095         'eventclick': true,
42096         /**
42097              * @event eventrender
42098              * Fires before each cell is rendered, so you can modify the contents, like cls / title / qtip
42099              * @param {Calendar} this
42100              * @param {data} data to be modified
42101              */
42102         'eventrender': true
42103         
42104     });
42105
42106     Roo.grid.Grid.superclass.constructor.call(this);
42107     this.on('render', function() {
42108         this.view.el.addClass('x-grid-cal'); 
42109         
42110         (function() { this.setDate(new Date()); }).defer(100,this); //default today..
42111
42112     },this);
42113     
42114     if (!Roo.grid.Calendar.style) {
42115         Roo.grid.Calendar.style = Roo.util.CSS.createStyleSheet({
42116             
42117             
42118             '.x-grid-cal .x-grid-col' :  {
42119                 height: 'auto !important',
42120                 'vertical-align': 'top'
42121             },
42122             '.x-grid-cal  .fc-event-hori' : {
42123                 height: '14px'
42124             }
42125              
42126             
42127         }, Roo.id());
42128     }
42129
42130     
42131     
42132 };
42133 Roo.extend(Roo.grid.Calendar, Roo.grid.Grid, {
42134     /**
42135      * @cfg {Store} eventStore The store that loads events.
42136      */
42137     eventStore : 25,
42138
42139      
42140     activeDate : false,
42141     startDay : 0,
42142     autoWidth : true,
42143     monitorWindowResize : false,
42144
42145     
42146     resizeColumns : function() {
42147         var col = (this.view.el.getWidth() / 7) - 3;
42148         // loop through cols, and setWidth
42149         for(var i =0 ; i < 7 ; i++){
42150             this.cm.setColumnWidth(i, col);
42151         }
42152     },
42153      setDate :function(date) {
42154         
42155         Roo.log('setDate?');
42156         
42157         this.resizeColumns();
42158         var vd = this.activeDate;
42159         this.activeDate = date;
42160 //        if(vd && this.el){
42161 //            var t = date.getTime();
42162 //            if(vd.getMonth() == date.getMonth() && vd.getFullYear() == date.getFullYear()){
42163 //                Roo.log('using add remove');
42164 //                
42165 //                this.fireEvent('monthchange', this, date);
42166 //                
42167 //                this.cells.removeClass("fc-state-highlight");
42168 //                this.cells.each(function(c){
42169 //                   if(c.dateValue == t){
42170 //                       c.addClass("fc-state-highlight");
42171 //                       setTimeout(function(){
42172 //                            try{c.dom.firstChild.focus();}catch(e){}
42173 //                       }, 50);
42174 //                       return false;
42175 //                   }
42176 //                   return true;
42177 //                });
42178 //                return;
42179 //            }
42180 //        }
42181         
42182         var days = date.getDaysInMonth();
42183         
42184         var firstOfMonth = date.getFirstDateOfMonth();
42185         var startingPos = firstOfMonth.getDay()-this.startDay;
42186         
42187         if(startingPos < this.startDay){
42188             startingPos += 7;
42189         }
42190         
42191         var pm = date.add(Date.MONTH, -1);
42192         var prevStart = pm.getDaysInMonth()-startingPos;
42193 //        
42194         
42195         
42196         this.cells = this.view.el.select('.x-grid-row .x-grid-col',true);
42197         
42198         this.textNodes = this.view.el.query('.x-grid-row .x-grid-col .x-grid-cell-text');
42199         //this.cells.addClassOnOver('fc-state-hover');
42200         
42201         var cells = this.cells.elements;
42202         var textEls = this.textNodes;
42203         
42204         //Roo.each(cells, function(cell){
42205         //    cell.removeClass([ 'fc-past', 'fc-other-month', 'fc-future', 'fc-state-highlight', 'fc-state-disabled']);
42206         //});
42207         
42208         days += startingPos;
42209
42210         // convert everything to numbers so it's fast
42211         var day = 86400000;
42212         var d = (new Date(pm.getFullYear(), pm.getMonth(), prevStart)).clearTime();
42213         //Roo.log(d);
42214         //Roo.log(pm);
42215         //Roo.log(prevStart);
42216         
42217         var today = new Date().clearTime().getTime();
42218         var sel = date.clearTime().getTime();
42219         var min = this.minDate ? this.minDate.clearTime() : Number.NEGATIVE_INFINITY;
42220         var max = this.maxDate ? this.maxDate.clearTime() : Number.POSITIVE_INFINITY;
42221         var ddMatch = this.disabledDatesRE;
42222         var ddText = this.disabledDatesText;
42223         var ddays = this.disabledDays ? this.disabledDays.join("") : false;
42224         var ddaysText = this.disabledDaysText;
42225         var format = this.format;
42226         
42227         var setCellClass = function(cal, cell){
42228             
42229             //Roo.log('set Cell Class');
42230             cell.title = "";
42231             var t = d.getTime();
42232             
42233             //Roo.log(d);
42234             
42235             
42236             cell.dateValue = t;
42237             if(t == today){
42238                 cell.className += " fc-today";
42239                 cell.className += " fc-state-highlight";
42240                 cell.title = cal.todayText;
42241             }
42242             if(t == sel){
42243                 // disable highlight in other month..
42244                 cell.className += " fc-state-highlight";
42245                 
42246             }
42247             // disabling
42248             if(t < min) {
42249                 //cell.className = " fc-state-disabled";
42250                 cell.title = cal.minText;
42251                 return;
42252             }
42253             if(t > max) {
42254                 //cell.className = " fc-state-disabled";
42255                 cell.title = cal.maxText;
42256                 return;
42257             }
42258             if(ddays){
42259                 if(ddays.indexOf(d.getDay()) != -1){
42260                     // cell.title = ddaysText;
42261                    // cell.className = " fc-state-disabled";
42262                 }
42263             }
42264             if(ddMatch && format){
42265                 var fvalue = d.dateFormat(format);
42266                 if(ddMatch.test(fvalue)){
42267                     cell.title = ddText.replace("%0", fvalue);
42268                    cell.className = " fc-state-disabled";
42269                 }
42270             }
42271             
42272             if (!cell.initialClassName) {
42273                 cell.initialClassName = cell.dom.className;
42274             }
42275             
42276             cell.dom.className = cell.initialClassName  + ' ' +  cell.className;
42277         };
42278
42279         var i = 0;
42280         
42281         for(; i < startingPos; i++) {
42282             cells[i].dayName =  (++prevStart);
42283             Roo.log(textEls[i]);
42284             d.setDate(d.getDate()+1);
42285             
42286             //cells[i].className = "fc-past fc-other-month";
42287             setCellClass(this, cells[i]);
42288         }
42289         
42290         var intDay = 0;
42291         
42292         for(; i < days; i++){
42293             intDay = i - startingPos + 1;
42294             cells[i].dayName =  (intDay);
42295             d.setDate(d.getDate()+1);
42296             
42297             cells[i].className = ''; // "x-date-active";
42298             setCellClass(this, cells[i]);
42299         }
42300         var extraDays = 0;
42301         
42302         for(; i < 42; i++) {
42303             //textEls[i].innerHTML = (++extraDays);
42304             
42305             d.setDate(d.getDate()+1);
42306             cells[i].dayName = (++extraDays);
42307             cells[i].className = "fc-future fc-other-month";
42308             setCellClass(this, cells[i]);
42309         }
42310         
42311         //this.el.select('.fc-header-title h2',true).update(Date.monthNames[date.getMonth()] + " " + date.getFullYear());
42312         
42313         var totalRows = Math.ceil((date.getDaysInMonth() + date.getFirstDateOfMonth().getDay()) / 7);
42314         
42315         // this will cause all the cells to mis
42316         var rows= [];
42317         var i =0;
42318         for (var r = 0;r < 6;r++) {
42319             for (var c =0;c < 7;c++) {
42320                 this.ds.getAt(r).set('weekday' + c ,cells[i++].dayName );
42321             }    
42322         }
42323         
42324         this.cells = this.view.el.select('.x-grid-row .x-grid-col',true);
42325         for(i=0;i<cells.length;i++) {
42326             
42327             this.cells.elements[i].dayName = cells[i].dayName ;
42328             this.cells.elements[i].className = cells[i].className;
42329             this.cells.elements[i].initialClassName = cells[i].initialClassName ;
42330             this.cells.elements[i].title = cells[i].title ;
42331             this.cells.elements[i].dateValue = cells[i].dateValue ;
42332         }
42333         
42334         
42335         
42336         
42337         //this.el.select('tr.fc-week.fc-prev-last',true).removeClass('fc-last');
42338         //this.el.select('tr.fc-week.fc-next-last',true).addClass('fc-last').show();
42339         
42340         ////if(totalRows != 6){
42341             //this.el.select('tr.fc-week.fc-last',true).removeClass('fc-last').addClass('fc-next-last').hide();
42342            // this.el.select('tr.fc-week.fc-prev-last',true).addClass('fc-last');
42343        // }
42344         
42345         this.fireEvent('monthchange', this, date);
42346         
42347         
42348     },
42349  /**
42350      * Returns the grid's SelectionModel.
42351      * @return {SelectionModel}
42352      */
42353     getSelectionModel : function(){
42354         if(!this.selModel){
42355             this.selModel = new Roo.grid.CellSelectionModel();
42356         }
42357         return this.selModel;
42358     },
42359
42360     load: function() {
42361         this.eventStore.load()
42362         
42363         
42364         
42365     },
42366     
42367     findCell : function(dt) {
42368         dt = dt.clearTime().getTime();
42369         var ret = false;
42370         this.cells.each(function(c){
42371             //Roo.log("check " +c.dateValue + '?=' + dt);
42372             if(c.dateValue == dt){
42373                 ret = c;
42374                 return false;
42375             }
42376             return true;
42377         });
42378         
42379         return ret;
42380     },
42381     
42382     findCells : function(rec) {
42383         var s = rec.data.start_dt.clone().clearTime().getTime();
42384        // Roo.log(s);
42385         var e= rec.data.end_dt.clone().clearTime().getTime();
42386        // Roo.log(e);
42387         var ret = [];
42388         this.cells.each(function(c){
42389              ////Roo.log("check " +c.dateValue + '<' + e + ' > ' + s);
42390             
42391             if(c.dateValue > e){
42392                 return ;
42393             }
42394             if(c.dateValue < s){
42395                 return ;
42396             }
42397             ret.push(c);
42398         });
42399         
42400         return ret;    
42401     },
42402     
42403     findBestRow: function(cells)
42404     {
42405         var ret = 0;
42406         
42407         for (var i =0 ; i < cells.length;i++) {
42408             ret  = Math.max(cells[i].rows || 0,ret);
42409         }
42410         return ret;
42411         
42412     },
42413     
42414     
42415     addItem : function(rec)
42416     {
42417         // look for vertical location slot in
42418         var cells = this.findCells(rec);
42419         
42420         rec.row = this.findBestRow(cells);
42421         
42422         // work out the location.
42423         
42424         var crow = false;
42425         var rows = [];
42426         for(var i =0; i < cells.length; i++) {
42427             if (!crow) {
42428                 crow = {
42429                     start : cells[i],
42430                     end :  cells[i]
42431                 };
42432                 continue;
42433             }
42434             if (crow.start.getY() == cells[i].getY()) {
42435                 // on same row.
42436                 crow.end = cells[i];
42437                 continue;
42438             }
42439             // different row.
42440             rows.push(crow);
42441             crow = {
42442                 start: cells[i],
42443                 end : cells[i]
42444             };
42445             
42446         }
42447         
42448         rows.push(crow);
42449         rec.els = [];
42450         rec.rows = rows;
42451         rec.cells = cells;
42452         for (var i = 0; i < cells.length;i++) {
42453             cells[i].rows = Math.max(cells[i].rows || 0 , rec.row + 1 );
42454             
42455         }
42456         
42457         
42458     },
42459     
42460     clearEvents: function() {
42461         
42462         if (!this.eventStore.getCount()) {
42463             return;
42464         }
42465         // reset number of rows in cells.
42466         Roo.each(this.cells.elements, function(c){
42467             c.rows = 0;
42468         });
42469         
42470         this.eventStore.each(function(e) {
42471             this.clearEvent(e);
42472         },this);
42473         
42474     },
42475     
42476     clearEvent : function(ev)
42477     {
42478         if (ev.els) {
42479             Roo.each(ev.els, function(el) {
42480                 el.un('mouseenter' ,this.onEventEnter, this);
42481                 el.un('mouseleave' ,this.onEventLeave, this);
42482                 el.remove();
42483             },this);
42484             ev.els = [];
42485         }
42486     },
42487     
42488     
42489     renderEvent : function(ev,ctr) {
42490         if (!ctr) {
42491              ctr = this.view.el.select('.fc-event-container',true).first();
42492         }
42493         
42494          
42495         this.clearEvent(ev);
42496             //code
42497        
42498         
42499         
42500         ev.els = [];
42501         var cells = ev.cells;
42502         var rows = ev.rows;
42503         this.fireEvent('eventrender', this, ev);
42504         
42505         for(var i =0; i < rows.length; i++) {
42506             
42507             cls = '';
42508             if (i == 0) {
42509                 cls += ' fc-event-start';
42510             }
42511             if ((i+1) == rows.length) {
42512                 cls += ' fc-event-end';
42513             }
42514             
42515             //Roo.log(ev.data);
42516             // how many rows should it span..
42517             var cg = this.eventTmpl.append(ctr,Roo.apply({
42518                 fccls : cls
42519                 
42520             }, ev.data) , true);
42521             
42522             
42523             cg.on('mouseenter' ,this.onEventEnter, this, ev);
42524             cg.on('mouseleave' ,this.onEventLeave, this, ev);
42525             cg.on('click', this.onEventClick, this, ev);
42526             
42527             ev.els.push(cg);
42528             
42529             var sbox = rows[i].start.select('.fc-day-content',true).first().getBox();
42530             var ebox = rows[i].end.select('.fc-day-content',true).first().getBox();
42531             //Roo.log(cg);
42532              
42533             cg.setXY([sbox.x +2, sbox.y +(ev.row * 20)]);    
42534             cg.setWidth(ebox.right - sbox.x -2);
42535         }
42536     },
42537     
42538     renderEvents: function()
42539     {   
42540         // first make sure there is enough space..
42541         
42542         if (!this.eventTmpl) {
42543             this.eventTmpl = new Roo.Template(
42544                 '<div class="roo-dynamic fc-event fc-event-hori fc-event-draggable ui-draggable {fccls} {cls}"  style="position: absolute" unselectable="on">' +
42545                     '<div class="fc-event-inner">' +
42546                         '<span class="fc-event-time">{time}</span>' +
42547                         '<span class="fc-event-title" qtip="{qtip}">{title}</span>' +
42548                     '</div>' +
42549                     '<div class="ui-resizable-heandle ui-resizable-e">&nbsp;&nbsp;&nbsp;</div>' +
42550                 '</div>'
42551             );
42552                 
42553         }
42554                
42555         
42556         
42557         this.cells.each(function(c) {
42558             //Roo.log(c.select('.fc-day-content div',true).first());
42559             c.select('.fc-day-content div',true).first().setHeight(Math.max(34, (c.rows || 1) * 20));
42560         });
42561         
42562         var ctr = this.view.el.select('.fc-event-container',true).first();
42563         
42564         var cls;
42565         this.eventStore.each(function(ev){
42566             
42567             this.renderEvent(ev);
42568              
42569              
42570         }, this);
42571         this.view.layout();
42572         
42573     },
42574     
42575     onEventEnter: function (e, el,event,d) {
42576         this.fireEvent('evententer', this, el, event);
42577     },
42578     
42579     onEventLeave: function (e, el,event,d) {
42580         this.fireEvent('eventleave', this, el, event);
42581     },
42582     
42583     onEventClick: function (e, el,event,d) {
42584         this.fireEvent('eventclick', this, el, event);
42585     },
42586     
42587     onMonthChange: function () {
42588         this.store.load();
42589     },
42590     
42591     onLoad: function () {
42592         
42593         //Roo.log('calendar onload');
42594 //         
42595         if(this.eventStore.getCount() > 0){
42596             
42597            
42598             
42599             this.eventStore.each(function(d){
42600                 
42601                 
42602                 // FIXME..
42603                 var add =   d.data;
42604                 if (typeof(add.end_dt) == 'undefined')  {
42605                     Roo.log("Missing End time in calendar data: ");
42606                     Roo.log(d);
42607                     return;
42608                 }
42609                 if (typeof(add.start_dt) == 'undefined')  {
42610                     Roo.log("Missing Start time in calendar data: ");
42611                     Roo.log(d);
42612                     return;
42613                 }
42614                 add.start_dt = typeof(add.start_dt) == 'string' ? Date.parseDate(add.start_dt,'Y-m-d H:i:s') : add.start_dt,
42615                 add.end_dt = typeof(add.end_dt) == 'string' ? Date.parseDate(add.end_dt,'Y-m-d H:i:s') : add.end_dt,
42616                 add.id = add.id || d.id;
42617                 add.title = add.title || '??';
42618                 
42619                 this.addItem(d);
42620                 
42621              
42622             },this);
42623         }
42624         
42625         this.renderEvents();
42626     }
42627     
42628
42629 });
42630 /*
42631  grid : {
42632                 xtype: 'Grid',
42633                 xns: Roo.grid,
42634                 listeners : {
42635                     render : function ()
42636                     {
42637                         _this.grid = this;
42638                         
42639                         if (!this.view.el.hasClass('course-timesheet')) {
42640                             this.view.el.addClass('course-timesheet');
42641                         }
42642                         if (this.tsStyle) {
42643                             this.ds.load({});
42644                             return; 
42645                         }
42646                         Roo.log('width');
42647                         Roo.log(_this.grid.view.el.getWidth());
42648                         
42649                         
42650                         this.tsStyle =  Roo.util.CSS.createStyleSheet({
42651                             '.course-timesheet .x-grid-row' : {
42652                                 height: '80px'
42653                             },
42654                             '.x-grid-row td' : {
42655                                 'vertical-align' : 0
42656                             },
42657                             '.course-edit-link' : {
42658                                 'color' : 'blue',
42659                                 'text-overflow' : 'ellipsis',
42660                                 'overflow' : 'hidden',
42661                                 'white-space' : 'nowrap',
42662                                 'cursor' : 'pointer'
42663                             },
42664                             '.sub-link' : {
42665                                 'color' : 'green'
42666                             },
42667                             '.de-act-sup-link' : {
42668                                 'color' : 'purple',
42669                                 'text-decoration' : 'line-through'
42670                             },
42671                             '.de-act-link' : {
42672                                 'color' : 'red',
42673                                 'text-decoration' : 'line-through'
42674                             },
42675                             '.course-timesheet .course-highlight' : {
42676                                 'border-top-style': 'dashed !important',
42677                                 'border-bottom-bottom': 'dashed !important'
42678                             },
42679                             '.course-timesheet .course-item' : {
42680                                 'font-family'   : 'tahoma, arial, helvetica',
42681                                 'font-size'     : '11px',
42682                                 'overflow'      : 'hidden',
42683                                 'padding-left'  : '10px',
42684                                 'padding-right' : '10px',
42685                                 'padding-top' : '10px' 
42686                             }
42687                             
42688                         }, Roo.id());
42689                                 this.ds.load({});
42690                     }
42691                 },
42692                 autoWidth : true,
42693                 monitorWindowResize : false,
42694                 cellrenderer : function(v,x,r)
42695                 {
42696                     return v;
42697                 },
42698                 sm : {
42699                     xtype: 'CellSelectionModel',
42700                     xns: Roo.grid
42701                 },
42702                 dataSource : {
42703                     xtype: 'Store',
42704                     xns: Roo.data,
42705                     listeners : {
42706                         beforeload : function (_self, options)
42707                         {
42708                             options.params = options.params || {};
42709                             options.params._month = _this.monthField.getValue();
42710                             options.params.limit = 9999;
42711                             options.params['sort'] = 'when_dt';    
42712                             options.params['dir'] = 'ASC';    
42713                             this.proxy.loadResponse = this.loadResponse;
42714                             Roo.log("load?");
42715                             //this.addColumns();
42716                         },
42717                         load : function (_self, records, options)
42718                         {
42719                             _this.grid.view.el.select('.course-edit-link', true).on('click', function() {
42720                                 // if you click on the translation.. you can edit it...
42721                                 var el = Roo.get(this);
42722                                 var id = el.dom.getAttribute('data-id');
42723                                 var d = el.dom.getAttribute('data-date');
42724                                 var t = el.dom.getAttribute('data-time');
42725                                 //var id = this.child('span').dom.textContent;
42726                                 
42727                                 //Roo.log(this);
42728                                 Pman.Dialog.CourseCalendar.show({
42729                                     id : id,
42730                                     when_d : d,
42731                                     when_t : t,
42732                                     productitem_active : id ? 1 : 0
42733                                 }, function() {
42734                                     _this.grid.ds.load({});
42735                                 });
42736                            
42737                            });
42738                            
42739                            _this.panel.fireEvent('resize', [ '', '' ]);
42740                         }
42741                     },
42742                     loadResponse : function(o, success, response){
42743                             // this is overridden on before load..
42744                             
42745                             Roo.log("our code?");       
42746                             //Roo.log(success);
42747                             //Roo.log(response)
42748                             delete this.activeRequest;
42749                             if(!success){
42750                                 this.fireEvent("loadexception", this, o, response);
42751                                 o.request.callback.call(o.request.scope, null, o.request.arg, false);
42752                                 return;
42753                             }
42754                             var result;
42755                             try {
42756                                 result = o.reader.read(response);
42757                             }catch(e){
42758                                 Roo.log("load exception?");
42759                                 this.fireEvent("loadexception", this, o, response, e);
42760                                 o.request.callback.call(o.request.scope, null, o.request.arg, false);
42761                                 return;
42762                             }
42763                             Roo.log("ready...");        
42764                             // loop through result.records;
42765                             // and set this.tdate[date] = [] << array of records..
42766                             _this.tdata  = {};
42767                             Roo.each(result.records, function(r){
42768                                 //Roo.log(r.data);
42769                                 if(typeof(_this.tdata[r.data.when_dt.format('j')]) == 'undefined'){
42770                                     _this.tdata[r.data.when_dt.format('j')] = [];
42771                                 }
42772                                 _this.tdata[r.data.when_dt.format('j')].push(r.data);
42773                             });
42774                             
42775                             //Roo.log(_this.tdata);
42776                             
42777                             result.records = [];
42778                             result.totalRecords = 6;
42779                     
42780                             // let's generate some duumy records for the rows.
42781                             //var st = _this.dateField.getValue();
42782                             
42783                             // work out monday..
42784                             //st = st.add(Date.DAY, -1 * st.format('w'));
42785                             
42786                             var date = Date.parseDate(_this.monthField.getValue(), "Y-m-d");
42787                             
42788                             var firstOfMonth = date.getFirstDayOfMonth();
42789                             var days = date.getDaysInMonth();
42790                             var d = 1;
42791                             var firstAdded = false;
42792                             for (var i = 0; i < result.totalRecords ; i++) {
42793                                 //var d= st.add(Date.DAY, i);
42794                                 var row = {};
42795                                 var added = 0;
42796                                 for(var w = 0 ; w < 7 ; w++){
42797                                     if(!firstAdded && firstOfMonth != w){
42798                                         continue;
42799                                     }
42800                                     if(d > days){
42801                                         continue;
42802                                     }
42803                                     firstAdded = true;
42804                                     var dd = (d > 0 && d < 10) ? "0"+d : d;
42805                                     row['weekday'+w] = String.format(
42806                                                     '<span style="font-size: 16px;"><b>{0}</b></span>'+
42807                                                     '<span class="course-edit-link" style="color:blue;" data-id="0" data-date="{1}"> Add New</span>',
42808                                                     d,
42809                                                     date.format('Y-m-')+dd
42810                                                 );
42811                                     added++;
42812                                     if(typeof(_this.tdata[d]) != 'undefined'){
42813                                         Roo.each(_this.tdata[d], function(r){
42814                                             var is_sub = '';
42815                                             var deactive = '';
42816                                             var id = r.id;
42817                                             var desc = (r.productitem_id_descrip) ? r.productitem_id_descrip : '';
42818                                             if(r.parent_id*1>0){
42819                                                 is_sub = (r.productitem_id_visible*1 < 1) ? 'de-act-sup-link' :'sub-link';
42820                                                 id = r.parent_id;
42821                                             }
42822                                             if(r.productitem_id_visible*1 < 1 && r.parent_id*1 < 1){
42823                                                 deactive = 'de-act-link';
42824                                             }
42825                                             
42826                                             row['weekday'+w] += String.format(
42827                                                     '<br /><span class="course-edit-link {3} {4}" qtip="{5}" data-id="{0}">{2} - {1}</span>',
42828                                                     id, //0
42829                                                     r.product_id_name, //1
42830                                                     r.when_dt.format('h:ia'), //2
42831                                                     is_sub, //3
42832                                                     deactive, //4
42833                                                     desc // 5
42834                                             );
42835                                         });
42836                                     }
42837                                     d++;
42838                                 }
42839                                 
42840                                 // only do this if something added..
42841                                 if(added > 0){ 
42842                                     result.records.push(_this.grid.dataSource.reader.newRow(row));
42843                                 }
42844                                 
42845                                 
42846                                 // push it twice. (second one with an hour..
42847                                 
42848                             }
42849                             //Roo.log(result);
42850                             this.fireEvent("load", this, o, o.request.arg);
42851                             o.request.callback.call(o.request.scope, result, o.request.arg, true);
42852                         },
42853                     sortInfo : {field: 'when_dt', direction : 'ASC' },
42854                     proxy : {
42855                         xtype: 'HttpProxy',
42856                         xns: Roo.data,
42857                         method : 'GET',
42858                         url : baseURL + '/Roo/Shop_course.php'
42859                     },
42860                     reader : {
42861                         xtype: 'JsonReader',
42862                         xns: Roo.data,
42863                         id : 'id',
42864                         fields : [
42865                             {
42866                                 'name': 'id',
42867                                 'type': 'int'
42868                             },
42869                             {
42870                                 'name': 'when_dt',
42871                                 'type': 'string'
42872                             },
42873                             {
42874                                 'name': 'end_dt',
42875                                 'type': 'string'
42876                             },
42877                             {
42878                                 'name': 'parent_id',
42879                                 'type': 'int'
42880                             },
42881                             {
42882                                 'name': 'product_id',
42883                                 'type': 'int'
42884                             },
42885                             {
42886                                 'name': 'productitem_id',
42887                                 'type': 'int'
42888                             },
42889                             {
42890                                 'name': 'guid',
42891                                 'type': 'int'
42892                             }
42893                         ]
42894                     }
42895                 },
42896                 toolbar : {
42897                     xtype: 'Toolbar',
42898                     xns: Roo,
42899                     items : [
42900                         {
42901                             xtype: 'Button',
42902                             xns: Roo.Toolbar,
42903                             listeners : {
42904                                 click : function (_self, e)
42905                                 {
42906                                     var sd = Date.parseDate(_this.monthField.getValue(), "Y-m-d");
42907                                     sd.setMonth(sd.getMonth()-1);
42908                                     _this.monthField.setValue(sd.format('Y-m-d'));
42909                                     _this.grid.ds.load({});
42910                                 }
42911                             },
42912                             text : "Back"
42913                         },
42914                         {
42915                             xtype: 'Separator',
42916                             xns: Roo.Toolbar
42917                         },
42918                         {
42919                             xtype: 'MonthField',
42920                             xns: Roo.form,
42921                             listeners : {
42922                                 render : function (_self)
42923                                 {
42924                                     _this.monthField = _self;
42925                                    // _this.monthField.set  today
42926                                 },
42927                                 select : function (combo, date)
42928                                 {
42929                                     _this.grid.ds.load({});
42930                                 }
42931                             },
42932                             value : (function() { return new Date(); })()
42933                         },
42934                         {
42935                             xtype: 'Separator',
42936                             xns: Roo.Toolbar
42937                         },
42938                         {
42939                             xtype: 'TextItem',
42940                             xns: Roo.Toolbar,
42941                             text : "Blue: in-active, green: in-active sup-event, red: de-active, purple: de-active sup-event"
42942                         },
42943                         {
42944                             xtype: 'Fill',
42945                             xns: Roo.Toolbar
42946                         },
42947                         {
42948                             xtype: 'Button',
42949                             xns: Roo.Toolbar,
42950                             listeners : {
42951                                 click : function (_self, e)
42952                                 {
42953                                     var sd = Date.parseDate(_this.monthField.getValue(), "Y-m-d");
42954                                     sd.setMonth(sd.getMonth()+1);
42955                                     _this.monthField.setValue(sd.format('Y-m-d'));
42956                                     _this.grid.ds.load({});
42957                                 }
42958                             },
42959                             text : "Next"
42960                         }
42961                     ]
42962                 },
42963                  
42964             }
42965         };
42966         
42967         *//*
42968  * Based on:
42969  * Ext JS Library 1.1.1
42970  * Copyright(c) 2006-2007, Ext JS, LLC.
42971  *
42972  * Originally Released Under LGPL - original licence link has changed is not relivant.
42973  *
42974  * Fork - LGPL
42975  * <script type="text/javascript">
42976  */
42977  
42978 /**
42979  * @class Roo.LoadMask
42980  * A simple utility class for generically masking elements while loading data.  If the element being masked has
42981  * an underlying {@link Roo.data.Store}, the masking will be automatically synchronized with the store's loading
42982  * process and the mask element will be cached for reuse.  For all other elements, this mask will replace the
42983  * element's UpdateManager load indicator and will be destroyed after the initial load.
42984  * @constructor
42985  * Create a new LoadMask
42986  * @param {String/HTMLElement/Roo.Element} el The element or DOM node, or its id
42987  * @param {Object} config The config object
42988  */
42989 Roo.LoadMask = function(el, config){
42990     this.el = Roo.get(el);
42991     Roo.apply(this, config);
42992     if(this.store){
42993         this.store.on('beforeload', this.onBeforeLoad, this);
42994         this.store.on('load', this.onLoad, this);
42995         this.store.on('loadexception', this.onLoadException, this);
42996         this.removeMask = false;
42997     }else{
42998         var um = this.el.getUpdateManager();
42999         um.showLoadIndicator = false; // disable the default indicator
43000         um.on('beforeupdate', this.onBeforeLoad, this);
43001         um.on('update', this.onLoad, this);
43002         um.on('failure', this.onLoad, this);
43003         this.removeMask = true;
43004     }
43005 };
43006
43007 Roo.LoadMask.prototype = {
43008     /**
43009      * @cfg {Boolean} removeMask
43010      * True to create a single-use mask that is automatically destroyed after loading (useful for page loads),
43011      * False to persist the mask element reference for multiple uses (e.g., for paged data widgets).  Defaults to false.
43012      */
43013     removeMask : false,
43014     /**
43015      * @cfg {String} msg
43016      * The text to display in a centered loading message box (defaults to 'Loading...')
43017      */
43018     msg : 'Loading...',
43019     /**
43020      * @cfg {String} msgCls
43021      * The CSS class to apply to the loading message element (defaults to "x-mask-loading")
43022      */
43023     msgCls : 'x-mask-loading',
43024
43025     /**
43026      * Read-only. True if the mask is currently disabled so that it will not be displayed (defaults to false)
43027      * @type Boolean
43028      */
43029     disabled: false,
43030
43031     /**
43032      * Disables the mask to prevent it from being displayed
43033      */
43034     disable : function(){
43035        this.disabled = true;
43036     },
43037
43038     /**
43039      * Enables the mask so that it can be displayed
43040      */
43041     enable : function(){
43042         this.disabled = false;
43043     },
43044     
43045     onLoadException : function()
43046     {
43047         Roo.log(arguments);
43048         
43049         if (typeof(arguments[3]) != 'undefined') {
43050             Roo.MessageBox.alert("Error loading",arguments[3]);
43051         } 
43052         /*
43053         try {
43054             if (this.store && typeof(this.store.reader.jsonData.errorMsg) != 'undefined') {
43055                 Roo.MessageBox.alert("Error loading",this.store.reader.jsonData.errorMsg);
43056             }   
43057         } catch(e) {
43058             
43059         }
43060         */
43061     
43062         (function() { this.el.unmask(this.removeMask); }).defer(50, this);
43063     },
43064     // private
43065     onLoad : function()
43066     {
43067         (function() { this.el.unmask(this.removeMask); }).defer(50, this);
43068     },
43069
43070     // private
43071     onBeforeLoad : function(){
43072         if(!this.disabled){
43073             (function() { this.el.mask(this.msg, this.msgCls); }).defer(50, this);
43074         }
43075     },
43076
43077     // private
43078     destroy : function(){
43079         if(this.store){
43080             this.store.un('beforeload', this.onBeforeLoad, this);
43081             this.store.un('load', this.onLoad, this);
43082             this.store.un('loadexception', this.onLoadException, this);
43083         }else{
43084             var um = this.el.getUpdateManager();
43085             um.un('beforeupdate', this.onBeforeLoad, this);
43086             um.un('update', this.onLoad, this);
43087             um.un('failure', this.onLoad, this);
43088         }
43089     }
43090 };/*
43091  * Based on:
43092  * Ext JS Library 1.1.1
43093  * Copyright(c) 2006-2007, Ext JS, LLC.
43094  *
43095  * Originally Released Under LGPL - original licence link has changed is not relivant.
43096  *
43097  * Fork - LGPL
43098  * <script type="text/javascript">
43099  */
43100
43101
43102 /**
43103  * @class Roo.XTemplate
43104  * @extends Roo.Template
43105  * Provides a template that can have nested templates for loops or conditionals. The syntax is:
43106 <pre><code>
43107 var t = new Roo.XTemplate(
43108         '&lt;select name="{name}"&gt;',
43109                 '&lt;tpl for="options"&gt;&lt;option value="{value:trim}"&gt;{text:ellipsis(10)}&lt;/option&gt;&lt;/tpl&gt;',
43110         '&lt;/select&gt;'
43111 );
43112  
43113 // then append, applying the master template values
43114  </code></pre>
43115  *
43116  * Supported features:
43117  *
43118  *  Tags:
43119
43120 <pre><code>
43121       {a_variable} - output encoded.
43122       {a_variable.format:("Y-m-d")} - call a method on the variable
43123       {a_variable:raw} - unencoded output
43124       {a_variable:toFixed(1,2)} - Roo.util.Format."toFixed"
43125       {a_variable:this.method_on_template(...)} - call a method on the template object.
43126  
43127 </code></pre>
43128  *  The tpl tag:
43129 <pre><code>
43130         &lt;tpl for="a_variable or condition.."&gt;&lt;/tpl&gt;
43131         &lt;tpl if="a_variable or condition"&gt;&lt;/tpl&gt;
43132         &lt;tpl exec="some javascript"&gt;&lt;/tpl&gt;
43133         &lt;tpl name="named_template"&gt;&lt;/tpl&gt; (experimental)
43134   
43135         &lt;tpl for="."&gt;&lt;/tpl&gt; - just iterate the property..
43136         &lt;tpl for=".."&gt;&lt;/tpl&gt; - iterates with the parent (probably the template) 
43137 </code></pre>
43138  *      
43139  */
43140 Roo.XTemplate = function()
43141 {
43142     Roo.XTemplate.superclass.constructor.apply(this, arguments);
43143     if (this.html) {
43144         this.compile();
43145     }
43146 };
43147
43148
43149 Roo.extend(Roo.XTemplate, Roo.Template, {
43150
43151     /**
43152      * The various sub templates
43153      */
43154     tpls : false,
43155     /**
43156      *
43157      * basic tag replacing syntax
43158      * WORD:WORD()
43159      *
43160      * // you can fake an object call by doing this
43161      *  x.t:(test,tesT) 
43162      * 
43163      */
43164     re : /\{([\w-\.]+)(?:\:([\w\.]*)(?:\((.*?)?\))?)?\}/g,
43165
43166     /**
43167      * compile the template
43168      *
43169      * This is not recursive, so I'm not sure how nested templates are really going to be handled..
43170      *
43171      */
43172     compile: function()
43173     {
43174         var s = this.html;
43175      
43176         s = ['<tpl>', s, '</tpl>'].join('');
43177     
43178         var re     = /<tpl\b[^>]*>((?:(?=([^<]+))\2|<(?!tpl\b[^>]*>))*?)<\/tpl>/,
43179             nameRe = /^<tpl\b[^>]*?for="(.*?)"/,
43180             ifRe   = /^<tpl\b[^>]*?if="(.*?)"/,
43181             execRe = /^<tpl\b[^>]*?exec="(.*?)"/,
43182             namedRe = /^<tpl\b[^>]*?name="(\w+)"/,  // named templates..
43183             m,
43184             id     = 0,
43185             tpls   = [];
43186     
43187         while(true == !!(m = s.match(re))){
43188             var forMatch   = m[0].match(nameRe),
43189                 ifMatch   = m[0].match(ifRe),
43190                 execMatch   = m[0].match(execRe),
43191                 namedMatch   = m[0].match(namedRe),
43192                 
43193                 exp  = null, 
43194                 fn   = null,
43195                 exec = null,
43196                 name = forMatch && forMatch[1] ? forMatch[1] : '';
43197                 
43198             if (ifMatch) {
43199                 // if - puts fn into test..
43200                 exp = ifMatch && ifMatch[1] ? ifMatch[1] : null;
43201                 if(exp){
43202                    fn = new Function('values', 'parent', 'with(values){ return '+(Roo.util.Format.htmlDecode(exp))+'; }');
43203                 }
43204             }
43205             
43206             if (execMatch) {
43207                 // exec - calls a function... returns empty if true is  returned.
43208                 exp = execMatch && execMatch[1] ? execMatch[1] : null;
43209                 if(exp){
43210                    exec = new Function('values', 'parent', 'with(values){ '+(Roo.util.Format.htmlDecode(exp))+'; }');
43211                 }
43212             }
43213             
43214             
43215             if (name) {
43216                 // for = 
43217                 switch(name){
43218                     case '.':  name = new Function('values', 'parent', 'with(values){ return values; }'); break;
43219                     case '..': name = new Function('values', 'parent', 'with(values){ return parent; }'); break;
43220                     default:   name = new Function('values', 'parent', 'with(values){ return '+name+'; }');
43221                 }
43222             }
43223             var uid = namedMatch ? namedMatch[1] : id;
43224             
43225             
43226             tpls.push({
43227                 id:     namedMatch ? namedMatch[1] : id,
43228                 target: name,
43229                 exec:   exec,
43230                 test:   fn,
43231                 body:   m[1] || ''
43232             });
43233             if (namedMatch) {
43234                 s = s.replace(m[0], '');
43235             } else { 
43236                 s = s.replace(m[0], '{xtpl'+ id + '}');
43237             }
43238             ++id;
43239         }
43240         this.tpls = [];
43241         for(var i = tpls.length-1; i >= 0; --i){
43242             this.compileTpl(tpls[i]);
43243             this.tpls[tpls[i].id] = tpls[i];
43244         }
43245         this.master = tpls[tpls.length-1];
43246         return this;
43247     },
43248     /**
43249      * same as applyTemplate, except it's done to one of the subTemplates
43250      * when using named templates, you can do:
43251      *
43252      * var str = pl.applySubTemplate('your-name', values);
43253      *
43254      * 
43255      * @param {Number} id of the template
43256      * @param {Object} values to apply to template
43257      * @param {Object} parent (normaly the instance of this object)
43258      */
43259     applySubTemplate : function(id, values, parent)
43260     {
43261         
43262         
43263         var t = this.tpls[id];
43264         
43265         
43266         try { 
43267             if(t.test && !t.test.call(this, values, parent)){
43268                 return '';
43269             }
43270         } catch(e) {
43271             Roo.log("Xtemplate.applySubTemplate 'test': Exception thrown");
43272             Roo.log(e.toString());
43273             Roo.log(t.test);
43274             return ''
43275         }
43276         try { 
43277             
43278             if(t.exec && t.exec.call(this, values, parent)){
43279                 return '';
43280             }
43281         } catch(e) {
43282             Roo.log("Xtemplate.applySubTemplate 'exec': Exception thrown");
43283             Roo.log(e.toString());
43284             Roo.log(t.exec);
43285             return ''
43286         }
43287         try {
43288             var vs = t.target ? t.target.call(this, values, parent) : values;
43289             parent = t.target ? values : parent;
43290             if(t.target && vs instanceof Array){
43291                 var buf = [];
43292                 for(var i = 0, len = vs.length; i < len; i++){
43293                     buf[buf.length] = t.compiled.call(this, vs[i], parent);
43294                 }
43295                 return buf.join('');
43296             }
43297             return t.compiled.call(this, vs, parent);
43298         } catch (e) {
43299             Roo.log("Xtemplate.applySubTemplate : Exception thrown");
43300             Roo.log(e.toString());
43301             Roo.log(t.compiled);
43302             return '';
43303         }
43304     },
43305
43306     compileTpl : function(tpl)
43307     {
43308         var fm = Roo.util.Format;
43309         var useF = this.disableFormats !== true;
43310         var sep = Roo.isGecko ? "+" : ",";
43311         var undef = function(str) {
43312             Roo.log("Property not found :"  + str);
43313             return '';
43314         };
43315         
43316         var fn = function(m, name, format, args)
43317         {
43318             //Roo.log(arguments);
43319             args = args ? args.replace(/\\'/g,"'") : args;
43320             //["{TEST:(a,b,c)}", "TEST", "", "a,b,c", 0, "{TEST:(a,b,c)}"]
43321             if (typeof(format) == 'undefined') {
43322                 format= 'htmlEncode';
43323             }
43324             if (format == 'raw' ) {
43325                 format = false;
43326             }
43327             
43328             if(name.substr(0, 4) == 'xtpl'){
43329                 return "'"+ sep +'this.applySubTemplate('+name.substr(4)+', values, parent)'+sep+"'";
43330             }
43331             
43332             // build an array of options to determine if value is undefined..
43333             
43334             // basically get 'xxxx.yyyy' then do
43335             // (typeof(xxxx) == 'undefined' || typeof(xxx.yyyy) == 'undefined') ?
43336             //    (function () { Roo.log("Property not found"); return ''; })() :
43337             //    ......
43338             
43339             var udef_ar = [];
43340             var lookfor = '';
43341             Roo.each(name.split('.'), function(st) {
43342                 lookfor += (lookfor.length ? '.': '') + st;
43343                 udef_ar.push(  "(typeof(" + lookfor + ") == 'undefined')"  );
43344             });
43345             
43346             var udef_st = '((' + udef_ar.join(" || ") +") ? undef('" + name + "') : "; // .. needs )
43347             
43348             
43349             if(format && useF){
43350                 
43351                 args = args ? ',' + args : "";
43352                  
43353                 if(format.substr(0, 5) != "this."){
43354                     format = "fm." + format + '(';
43355                 }else{
43356                     format = 'this.call("'+ format.substr(5) + '", ';
43357                     args = ", values";
43358                 }
43359                 
43360                 return "'"+ sep +   udef_st   +    format + name + args + "))"+sep+"'";
43361             }
43362              
43363             if (args.length) {
43364                 // called with xxyx.yuu:(test,test)
43365                 // change to ()
43366                 return "'"+ sep + udef_st  + name + '(' +  args + "))"+sep+"'";
43367             }
43368             // raw.. - :raw modifier..
43369             return "'"+ sep + udef_st  + name + ")"+sep+"'";
43370             
43371         };
43372         var body;
43373         // branched to use + in gecko and [].join() in others
43374         if(Roo.isGecko){
43375             body = "tpl.compiled = function(values, parent){  with(values) { return '" +
43376                    tpl.body.replace(/(\r\n|\n)/g, '\\n').replace(/'/g, "\\'").replace(this.re, fn) +
43377                     "';};};";
43378         }else{
43379             body = ["tpl.compiled = function(values, parent){  with (values) { return ['"];
43380             body.push(tpl.body.replace(/(\r\n|\n)/g,
43381                             '\\n').replace(/'/g, "\\'").replace(this.re, fn));
43382             body.push("'].join('');};};");
43383             body = body.join('');
43384         }
43385         
43386         Roo.debug && Roo.log(body.replace(/\\n/,'\n'));
43387        
43388         /** eval:var:tpl eval:var:fm eval:var:useF eval:var:undef  */
43389         eval(body);
43390         
43391         return this;
43392     },
43393
43394     applyTemplate : function(values){
43395         return this.master.compiled.call(this, values, {});
43396         //var s = this.subs;
43397     },
43398
43399     apply : function(){
43400         return this.applyTemplate.apply(this, arguments);
43401     }
43402
43403  });
43404
43405 Roo.XTemplate.from = function(el){
43406     el = Roo.getDom(el);
43407     return new Roo.XTemplate(el.value || el.innerHTML);
43408 };