Merge branch 'master' of http://git.roojs.com/roojs1
[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} ret return data from JsonData.reader() - success, totalRecords, records
485          * @param {Object} opts - 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  * @extends Roo.data.DataProxy
1398  * An implementation of Roo.data.DataProxy that simply passes the data specified in its constructor
1399  * to the Reader when its load method is called.
1400  * @constructor
1401  * @param {Object} config  A config object containing the objects needed for the Store to access data,
1402  */
1403 Roo.data.MemoryProxy = function(config){
1404     var data = config;
1405     if (typeof(config) != 'undefined' && typeof(config.data) != 'undefined') {
1406         data = config.data;
1407     }
1408     Roo.data.MemoryProxy.superclass.constructor.call(this);
1409     this.data = data;
1410 };
1411
1412 Roo.extend(Roo.data.MemoryProxy, Roo.data.DataProxy, {
1413     
1414     /**
1415      *  @cfg {Object} data The data object which the Reader uses to construct a block of Roo.data.Records.
1416      */
1417     /**
1418      * Load data from the requested source (in this case an in-memory
1419      * data object passed to the constructor), read the data object into
1420      * a block of Roo.data.Records using the passed Roo.data.DataReader implementation, and
1421      * process that block using the passed callback.
1422      * @param {Object} params This parameter is not used by the MemoryProxy class.
1423      * @param {Roo.data.DataReader} reader The Reader object which converts the data
1424      * object into a block of Roo.data.Records.
1425      * @param {Function} callback The function into which to pass the block of Roo.data.records.
1426      * The function must be passed <ul>
1427      * <li>The Record block object</li>
1428      * <li>The "arg" argument from the load function</li>
1429      * <li>A boolean success indicator</li>
1430      * </ul>
1431      * @param {Object} scope The scope in which to call the callback
1432      * @param {Object} arg An optional argument which is passed to the callback as its second parameter.
1433      */
1434     load : function(params, reader, callback, scope, arg){
1435         params = params || {};
1436         var result;
1437         try {
1438             result = reader.readRecords(params.data ? params.data :this.data);
1439         }catch(e){
1440             this.fireEvent("loadexception", this, arg, null, e);
1441             callback.call(scope, null, arg, false);
1442             return;
1443         }
1444         callback.call(scope, result, arg, true);
1445     },
1446     
1447     // private
1448     update : function(params, records){
1449         
1450     }
1451 });/*
1452  * Based on:
1453  * Ext JS Library 1.1.1
1454  * Copyright(c) 2006-2007, Ext JS, LLC.
1455  *
1456  * Originally Released Under LGPL - original licence link has changed is not relivant.
1457  *
1458  * Fork - LGPL
1459  * <script type="text/javascript">
1460  */
1461 /**
1462  * @class Roo.data.HttpProxy
1463  * @extends Roo.data.DataProxy
1464  * An implementation of {@link Roo.data.DataProxy} that reads a data object from an {@link Roo.data.Connection} object
1465  * configured to reference a certain URL.<br><br>
1466  * <p>
1467  * <em>Note that this class cannot be used to retrieve data from a domain other than the domain
1468  * from which the running page was served.<br><br>
1469  * <p>
1470  * For cross-domain access to remote data, use an {@link Roo.data.ScriptTagProxy}.</em><br><br>
1471  * <p>
1472  * Be aware that to enable the browser to parse an XML document, the server must set
1473  * the Content-Type header in the HTTP response to "text/xml".
1474  * @constructor
1475  * @param {Object} conn Connection config options to add to each request (e.g. {url: 'foo.php'} or
1476  * an {@link Roo.data.Connection} object.  If a Connection config is passed, the singleton {@link Roo.Ajax} object
1477  * will be used to make the request.
1478  */
1479 Roo.data.HttpProxy = function(conn){
1480     Roo.data.HttpProxy.superclass.constructor.call(this);
1481     // is conn a conn config or a real conn?
1482     this.conn = conn;
1483     this.useAjax = !conn || !conn.events;
1484   
1485 };
1486
1487 Roo.extend(Roo.data.HttpProxy, Roo.data.DataProxy, {
1488     // thse are take from connection...
1489     
1490     /**
1491      * @cfg {String} url  The default URL to be used for requests to the server. (defaults to undefined)
1492      */
1493     /**
1494      * @cfg {Object} extraParams  An object containing properties which are used as
1495      * extra parameters to each request made by this object. (defaults to undefined)
1496      */
1497     /**
1498      * @cfg {Object} defaultHeaders   An object containing request headers which are added
1499      *  to each request made by this object. (defaults to undefined)
1500      */
1501     /**
1502      * @cfg {String} method (GET|POST)  The default HTTP method to be used for requests. (defaults to undefined; if not set but parms are present will use POST, otherwise GET)
1503      */
1504     /**
1505      * @cfg {Number} timeout The timeout in milliseconds to be used for requests. (defaults to 30000)
1506      */
1507      /**
1508      * @cfg {Boolean} autoAbort Whether this request should abort any pending requests. (defaults to false)
1509      * @type Boolean
1510      */
1511   
1512
1513     /**
1514      * @cfg {Boolean} disableCaching (Optional) True to add a unique cache-buster param to GET requests. (defaults to true)
1515      * @type Boolean
1516      */
1517     /**
1518      * Return the {@link Roo.data.Connection} object being used by this Proxy.
1519      * @return {Connection} The Connection object. This object may be used to subscribe to events on
1520      * a finer-grained basis than the DataProxy events.
1521      */
1522     getConnection : function(){
1523         return this.useAjax ? Roo.Ajax : this.conn;
1524     },
1525
1526     /**
1527      * Load data from the configured {@link Roo.data.Connection}, read the data object into
1528      * a block of Roo.data.Records using the passed {@link Roo.data.DataReader} implementation, and
1529      * process that block using the passed callback.
1530      * @param {Object} params An object containing properties which are to be used as HTTP parameters
1531      * for the request to the remote server.
1532      * @param {Roo.data.DataReader} reader The Reader object which converts the data
1533      * object into a block of Roo.data.Records.
1534      * @param {Function} callback The function into which to pass the block of Roo.data.Records.
1535      * The function must be passed <ul>
1536      * <li>The Record block object</li>
1537      * <li>The "arg" argument from the load function</li>
1538      * <li>A boolean success indicator</li>
1539      * </ul>
1540      * @param {Object} scope The scope in which to call the callback
1541      * @param {Object} arg An optional argument which is passed to the callback as its second parameter.
1542      */
1543     load : function(params, reader, callback, scope, arg){
1544         if(this.fireEvent("beforeload", this, params) !== false){
1545             var  o = {
1546                 params : params || {},
1547                 request: {
1548                     callback : callback,
1549                     scope : scope,
1550                     arg : arg
1551                 },
1552                 reader: reader,
1553                 callback : this.loadResponse,
1554                 scope: this
1555             };
1556             if(this.useAjax){
1557                 Roo.applyIf(o, this.conn);
1558                 if(this.activeRequest){
1559                     Roo.Ajax.abort(this.activeRequest);
1560                 }
1561                 this.activeRequest = Roo.Ajax.request(o);
1562             }else{
1563                 this.conn.request(o);
1564             }
1565         }else{
1566             callback.call(scope||this, null, arg, false);
1567         }
1568     },
1569
1570     // private
1571     loadResponse : function(o, success, response){
1572         delete this.activeRequest;
1573         if(!success){
1574             this.fireEvent("loadexception", this, o, response);
1575             o.request.callback.call(o.request.scope, null, o.request.arg, false);
1576             return;
1577         }
1578         var result;
1579         try {
1580             result = o.reader.read(response);
1581         }catch(e){
1582             o.success = false;
1583             o.raw = { errorMsg : response.responseText };
1584             this.fireEvent("loadexception", this, o, response, e);
1585             o.request.callback.call(o.request.scope, o, o.request.arg, false);
1586             return;
1587         }
1588         
1589         this.fireEvent("load", this, o, o.request.arg);
1590         o.request.callback.call(o.request.scope, result, o.request.arg, true);
1591     },
1592
1593     // private
1594     update : function(dataSet){
1595
1596     },
1597
1598     // private
1599     updateResponse : function(dataSet){
1600
1601     }
1602 });/*
1603  * Based on:
1604  * Ext JS Library 1.1.1
1605  * Copyright(c) 2006-2007, Ext JS, LLC.
1606  *
1607  * Originally Released Under LGPL - original licence link has changed is not relivant.
1608  *
1609  * Fork - LGPL
1610  * <script type="text/javascript">
1611  */
1612
1613 /**
1614  * @class Roo.data.ScriptTagProxy
1615  * An implementation of Roo.data.DataProxy that reads a data object from a URL which may be in a domain
1616  * other than the originating domain of the running page.<br><br>
1617  * <p>
1618  * <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
1619  * of the running page, you must use this class, rather than DataProxy.</em><br><br>
1620  * <p>
1621  * The content passed back from a server resource requested by a ScriptTagProxy is executable JavaScript
1622  * source code that is used as the source inside a &lt;script> tag.<br><br>
1623  * <p>
1624  * In order for the browser to process the returned data, the server must wrap the data object
1625  * with a call to a callback function, the name of which is passed as a parameter by the ScriptTagProxy.
1626  * Below is a Java example for a servlet which returns data for either a ScriptTagProxy, or an HttpProxy
1627  * depending on whether the callback name was passed:
1628  * <p>
1629  * <pre><code>
1630 boolean scriptTag = false;
1631 String cb = request.getParameter("callback");
1632 if (cb != null) {
1633     scriptTag = true;
1634     response.setContentType("text/javascript");
1635 } else {
1636     response.setContentType("application/x-json");
1637 }
1638 Writer out = response.getWriter();
1639 if (scriptTag) {
1640     out.write(cb + "(");
1641 }
1642 out.print(dataBlock.toJsonString());
1643 if (scriptTag) {
1644     out.write(");");
1645 }
1646 </pre></code>
1647  *
1648  * @constructor
1649  * @param {Object} config A configuration object.
1650  */
1651 Roo.data.ScriptTagProxy = function(config){
1652     Roo.data.ScriptTagProxy.superclass.constructor.call(this);
1653     Roo.apply(this, config);
1654     this.head = document.getElementsByTagName("head")[0];
1655 };
1656
1657 Roo.data.ScriptTagProxy.TRANS_ID = 1000;
1658
1659 Roo.extend(Roo.data.ScriptTagProxy, Roo.data.DataProxy, {
1660     /**
1661      * @cfg {String} url The URL from which to request the data object.
1662      */
1663     /**
1664      * @cfg {Number} timeout (Optional) The number of milliseconds to wait for a response. Defaults to 30 seconds.
1665      */
1666     timeout : 30000,
1667     /**
1668      * @cfg {String} callbackParam (Optional) The name of the parameter to pass to the server which tells
1669      * the server the name of the callback function set up by the load call to process the returned data object.
1670      * Defaults to "callback".<p>The server-side processing must read this parameter value, and generate
1671      * javascript output which calls this named function passing the data object as its only parameter.
1672      */
1673     callbackParam : "callback",
1674     /**
1675      *  @cfg {Boolean} nocache (Optional) Defaults to true. Disable cacheing by adding a unique parameter
1676      * name to the request.
1677      */
1678     nocache : true,
1679
1680     /**
1681      * Load data from the configured URL, read the data object into
1682      * a block of Roo.data.Records using the passed Roo.data.DataReader implementation, and
1683      * process that block using the passed callback.
1684      * @param {Object} params An object containing properties which are to be used as HTTP parameters
1685      * for the request to the remote server.
1686      * @param {Roo.data.DataReader} reader The Reader object which converts the data
1687      * object into a block of Roo.data.Records.
1688      * @param {Function} callback The function into which to pass the block of Roo.data.Records.
1689      * The function must be passed <ul>
1690      * <li>The Record block object</li>
1691      * <li>The "arg" argument from the load function</li>
1692      * <li>A boolean success indicator</li>
1693      * </ul>
1694      * @param {Object} scope The scope in which to call the callback
1695      * @param {Object} arg An optional argument which is passed to the callback as its second parameter.
1696      */
1697     load : function(params, reader, callback, scope, arg){
1698         if(this.fireEvent("beforeload", this, params) !== false){
1699
1700             var p = Roo.urlEncode(Roo.apply(params, this.extraParams));
1701
1702             var url = this.url;
1703             url += (url.indexOf("?") != -1 ? "&" : "?") + p;
1704             if(this.nocache){
1705                 url += "&_dc=" + (new Date().getTime());
1706             }
1707             var transId = ++Roo.data.ScriptTagProxy.TRANS_ID;
1708             var trans = {
1709                 id : transId,
1710                 cb : "stcCallback"+transId,
1711                 scriptId : "stcScript"+transId,
1712                 params : params,
1713                 arg : arg,
1714                 url : url,
1715                 callback : callback,
1716                 scope : scope,
1717                 reader : reader
1718             };
1719             var conn = this;
1720
1721             window[trans.cb] = function(o){
1722                 conn.handleResponse(o, trans);
1723             };
1724
1725             url += String.format("&{0}={1}", this.callbackParam, trans.cb);
1726
1727             if(this.autoAbort !== false){
1728                 this.abort();
1729             }
1730
1731             trans.timeoutId = this.handleFailure.defer(this.timeout, this, [trans]);
1732
1733             var script = document.createElement("script");
1734             script.setAttribute("src", url);
1735             script.setAttribute("type", "text/javascript");
1736             script.setAttribute("id", trans.scriptId);
1737             this.head.appendChild(script);
1738
1739             this.trans = trans;
1740         }else{
1741             callback.call(scope||this, null, arg, false);
1742         }
1743     },
1744
1745     // private
1746     isLoading : function(){
1747         return this.trans ? true : false;
1748     },
1749
1750     /**
1751      * Abort the current server request.
1752      */
1753     abort : function(){
1754         if(this.isLoading()){
1755             this.destroyTrans(this.trans);
1756         }
1757     },
1758
1759     // private
1760     destroyTrans : function(trans, isLoaded){
1761         this.head.removeChild(document.getElementById(trans.scriptId));
1762         clearTimeout(trans.timeoutId);
1763         if(isLoaded){
1764             window[trans.cb] = undefined;
1765             try{
1766                 delete window[trans.cb];
1767             }catch(e){}
1768         }else{
1769             // if hasn't been loaded, wait for load to remove it to prevent script error
1770             window[trans.cb] = function(){
1771                 window[trans.cb] = undefined;
1772                 try{
1773                     delete window[trans.cb];
1774                 }catch(e){}
1775             };
1776         }
1777     },
1778
1779     // private
1780     handleResponse : function(o, trans){
1781         this.trans = false;
1782         this.destroyTrans(trans, true);
1783         var result;
1784         try {
1785             result = trans.reader.readRecords(o);
1786         }catch(e){
1787             this.fireEvent("loadexception", this, o, trans.arg, e);
1788             trans.callback.call(trans.scope||window, null, trans.arg, false);
1789             return;
1790         }
1791         this.fireEvent("load", this, o, trans.arg);
1792         trans.callback.call(trans.scope||window, result, trans.arg, true);
1793     },
1794
1795     // private
1796     handleFailure : function(trans){
1797         this.trans = false;
1798         this.destroyTrans(trans, false);
1799         this.fireEvent("loadexception", this, null, trans.arg);
1800         trans.callback.call(trans.scope||window, null, trans.arg, false);
1801     }
1802 });/*
1803  * Based on:
1804  * Ext JS Library 1.1.1
1805  * Copyright(c) 2006-2007, Ext JS, LLC.
1806  *
1807  * Originally Released Under LGPL - original licence link has changed is not relivant.
1808  *
1809  * Fork - LGPL
1810  * <script type="text/javascript">
1811  */
1812
1813 /**
1814  * @class Roo.data.JsonReader
1815  * @extends Roo.data.DataReader
1816  * Data reader class to create an Array of Roo.data.Record objects from a JSON response
1817  * based on mappings in a provided Roo.data.Record constructor.
1818  * 
1819  * The default behaviour of a store is to send ?_requestMeta=1, unless the class has recieved 'metaData' property
1820  * in the reply previously. 
1821  * 
1822  * <p>
1823  * Example code:
1824  * <pre><code>
1825 var RecordDef = Roo.data.Record.create([
1826     {name: 'name', mapping: 'name'},     // "mapping" property not needed if it's the same as "name"
1827     {name: 'occupation'}                 // This field will use "occupation" as the mapping.
1828 ]);
1829 var myReader = new Roo.data.JsonReader({
1830     totalProperty: "results",    // The property which contains the total dataset size (optional)
1831     root: "rows",                // The property which contains an Array of row objects
1832     id: "id"                     // The property within each row object that provides an ID for the record (optional)
1833 }, RecordDef);
1834 </code></pre>
1835  * <p>
1836  * This would consume a JSON file like this:
1837  * <pre><code>
1838 { 'results': 2, 'rows': [
1839     { 'id': 1, 'name': 'Bill', occupation: 'Gardener' },
1840     { 'id': 2, 'name': 'Ben', occupation: 'Horticulturalist' } ]
1841 }
1842 </code></pre>
1843  * @cfg {String} totalProperty Name of the property from which to retrieve the total number of records
1844  * in the dataset. This is only needed if the whole dataset is not passed in one go, but is being
1845  * paged from the remote server.
1846  * @cfg {String} successProperty Name of the property from which to retrieve the success attribute used by forms.
1847  * @cfg {String} root name of the property which contains the Array of row objects.
1848  * @cfg {String} id Name of the property within a row object that contains a record identifier value.
1849  * @cfg {Array} fields Array of field definition objects
1850  * @constructor
1851  * Create a new JsonReader
1852  * @param {Object} meta Metadata configuration options
1853  * @param {Object} recordType Either an Array of field definition objects,
1854  * or an {@link Roo.data.Record} object created using {@link Roo.data.Record#create}.
1855  */
1856 Roo.data.JsonReader = function(meta, recordType){
1857     
1858     meta = meta || {};
1859     // set some defaults:
1860     Roo.applyIf(meta, {
1861         totalProperty: 'total',
1862         successProperty : 'success',
1863         root : 'data',
1864         id : 'id'
1865     });
1866     
1867     Roo.data.JsonReader.superclass.constructor.call(this, meta, recordType||meta.fields);
1868 };
1869 Roo.extend(Roo.data.JsonReader, Roo.data.DataReader, {
1870     
1871     readerType : 'Json',
1872     
1873     /**
1874      * @prop {Boolean} metaFromRemote  - if the meta data was loaded from the remote source.
1875      * Used by Store query builder to append _requestMeta to params.
1876      * 
1877      */
1878     metaFromRemote : false,
1879     /**
1880      * This method is only used by a DataProxy which has retrieved data from a remote server.
1881      * @param {Object} response The XHR object which contains the JSON data in its responseText.
1882      * @return {Object} data A data block which is used by an Roo.data.Store object as
1883      * a cache of Roo.data.Records.
1884      */
1885     read : function(response){
1886         var json = response.responseText;
1887        
1888         var o = /* eval:var:o */ eval("("+json+")");
1889         if(!o) {
1890             throw {message: "JsonReader.read: Json object not found"};
1891         }
1892         
1893         if(o.metaData){
1894             
1895             delete this.ef;
1896             this.metaFromRemote = true;
1897             this.meta = o.metaData;
1898             this.recordType = Roo.data.Record.create(o.metaData.fields);
1899             this.onMetaChange(this.meta, this.recordType, o);
1900         }
1901         return this.readRecords(o);
1902     },
1903
1904     // private function a store will implement
1905     onMetaChange : function(meta, recordType, o){
1906
1907     },
1908
1909     /**
1910          * @ignore
1911          */
1912     simpleAccess: function(obj, subsc) {
1913         return obj[subsc];
1914     },
1915
1916         /**
1917          * @ignore
1918          */
1919     getJsonAccessor: function(){
1920         var re = /[\[\.]/;
1921         return function(expr) {
1922             try {
1923                 return(re.test(expr))
1924                     ? new Function("obj", "return obj." + expr)
1925                     : function(obj){
1926                         return obj[expr];
1927                     };
1928             } catch(e){}
1929             return Roo.emptyFn;
1930         };
1931     }(),
1932
1933     /**
1934      * Create a data block containing Roo.data.Records from an XML document.
1935      * @param {Object} o An object which contains an Array of row objects in the property specified
1936      * in the config as 'root, and optionally a property, specified in the config as 'totalProperty'
1937      * which contains the total size of the dataset.
1938      * @return {Object} data A data block which is used by an Roo.data.Store object as
1939      * a cache of Roo.data.Records.
1940      */
1941     readRecords : function(o){
1942         /**
1943          * After any data loads, the raw JSON data is available for further custom processing.
1944          * @type Object
1945          */
1946         this.o = o;
1947         var s = this.meta, Record = this.recordType,
1948             f = Record ? Record.prototype.fields : null, fi = f ? f.items : [], fl = f ? f.length : 0;
1949
1950 //      Generate extraction functions for the totalProperty, the root, the id, and for each field
1951         if (!this.ef) {
1952             if(s.totalProperty) {
1953                     this.getTotal = this.getJsonAccessor(s.totalProperty);
1954                 }
1955                 if(s.successProperty) {
1956                     this.getSuccess = this.getJsonAccessor(s.successProperty);
1957                 }
1958                 this.getRoot = s.root ? this.getJsonAccessor(s.root) : function(p){return p;};
1959                 if (s.id) {
1960                         var g = this.getJsonAccessor(s.id);
1961                         this.getId = function(rec) {
1962                                 var r = g(rec);  
1963                                 return (r === undefined || r === "") ? null : r;
1964                         };
1965                 } else {
1966                         this.getId = function(){return null;};
1967                 }
1968             this.ef = [];
1969             for(var jj = 0; jj < fl; jj++){
1970                 f = fi[jj];
1971                 var map = (f.mapping !== undefined && f.mapping !== null) ? f.mapping : f.name;
1972                 this.ef[jj] = this.getJsonAccessor(map);
1973             }
1974         }
1975
1976         var root = this.getRoot(o), c = root.length, totalRecords = c, success = true;
1977         if(s.totalProperty){
1978             var vt = parseInt(this.getTotal(o), 10);
1979             if(!isNaN(vt)){
1980                 totalRecords = vt;
1981             }
1982         }
1983         if(s.successProperty){
1984             var vs = this.getSuccess(o);
1985             if(vs === false || vs === 'false'){
1986                 success = false;
1987             }
1988         }
1989         var records = [];
1990         for(var i = 0; i < c; i++){
1991             var n = root[i];
1992             var values = {};
1993             var id = this.getId(n);
1994             for(var j = 0; j < fl; j++){
1995                 f = fi[j];
1996                                 var v = this.ef[j](n);
1997                                 if (!f.convert) {
1998                                         Roo.log('missing convert for ' + f.name);
1999                                         Roo.log(f);
2000                                         continue;
2001                                 }
2002                                 values[f.name] = f.convert((v !== undefined) ? v : f.defaultValue);
2003             }
2004                         if (!Record) {
2005                                 return {
2006                                         raw : { errorMsg : "JSON Reader Error: fields or metadata not available to create Record" },
2007                                         success : false,
2008                                         records : [],
2009                                         totalRecords : 0
2010                                 };
2011                         }
2012             var record = new Record(values, id);
2013             record.json = n;
2014             records[i] = record;
2015         }
2016         return {
2017             raw : o,
2018             success : success,
2019             records : records,
2020             totalRecords : totalRecords
2021         };
2022     },
2023     // used when loading children.. @see loadDataFromChildren
2024     toLoadData: function(rec)
2025     {
2026         // expect rec just to be an array.. eg [a,b,c, [...] << cn ]
2027         var data = typeof(rec.data.cn) == 'undefined' ? [] : rec.data.cn;
2028         return { data : data, total : data.length };
2029         
2030     }
2031 });/*
2032  * Based on:
2033  * Ext JS Library 1.1.1
2034  * Copyright(c) 2006-2007, Ext JS, LLC.
2035  *
2036  * Originally Released Under LGPL - original licence link has changed is not relivant.
2037  *
2038  * Fork - LGPL
2039  * <script type="text/javascript">
2040  */
2041
2042 /**
2043  * @class Roo.data.XmlReader
2044  * @extends Roo.data.DataReader
2045  * Data reader class to create an Array of {@link Roo.data.Record} objects from an XML document
2046  * based on mappings in a provided Roo.data.Record constructor.<br><br>
2047  * <p>
2048  * <em>Note that in order for the browser to parse a returned XML document, the Content-Type
2049  * header in the HTTP response must be set to "text/xml".</em>
2050  * <p>
2051  * Example code:
2052  * <pre><code>
2053 var RecordDef = Roo.data.Record.create([
2054    {name: 'name', mapping: 'name'},     // "mapping" property not needed if it's the same as "name"
2055    {name: 'occupation'}                 // This field will use "occupation" as the mapping.
2056 ]);
2057 var myReader = new Roo.data.XmlReader({
2058    totalRecords: "results", // The element which contains the total dataset size (optional)
2059    record: "row",           // The repeated element which contains row information
2060    id: "id"                 // The element within the row that provides an ID for the record (optional)
2061 }, RecordDef);
2062 </code></pre>
2063  * <p>
2064  * This would consume an XML file like this:
2065  * <pre><code>
2066 &lt;?xml?>
2067 &lt;dataset>
2068  &lt;results>2&lt;/results>
2069  &lt;row>
2070    &lt;id>1&lt;/id>
2071    &lt;name>Bill&lt;/name>
2072    &lt;occupation>Gardener&lt;/occupation>
2073  &lt;/row>
2074  &lt;row>
2075    &lt;id>2&lt;/id>
2076    &lt;name>Ben&lt;/name>
2077    &lt;occupation>Horticulturalist&lt;/occupation>
2078  &lt;/row>
2079 &lt;/dataset>
2080 </code></pre>
2081  * @cfg {String} totalRecords The DomQuery path from which to retrieve the total number of records
2082  * in the dataset. This is only needed if the whole dataset is not passed in one go, but is being
2083  * paged from the remote server.
2084  * @cfg {String} record The DomQuery path to the repeated element which contains record information.
2085  * @cfg {String} success The DomQuery path to the success attribute used by forms.
2086  * @cfg {String} id The DomQuery path relative from the record element to the element that contains
2087  * a record identifier value.
2088  * @constructor
2089  * Create a new XmlReader
2090  * @param {Object} meta Metadata configuration options
2091  * @param {Mixed} recordType The definition of the data record type to produce.  This can be either a valid
2092  * Record subclass created with {@link Roo.data.Record#create}, or an array of objects with which to call
2093  * Roo.data.Record.create.  See the {@link Roo.data.Record} class for more details.
2094  */
2095 Roo.data.XmlReader = function(meta, recordType){
2096     meta = meta || {};
2097     Roo.data.XmlReader.superclass.constructor.call(this, meta, recordType||meta.fields);
2098 };
2099 Roo.extend(Roo.data.XmlReader, Roo.data.DataReader, {
2100     
2101     readerType : 'Xml',
2102     
2103     /**
2104      * This method is only used by a DataProxy which has retrieved data from a remote server.
2105          * @param {Object} response The XHR object which contains the parsed XML document.  The response is expected
2106          * to contain a method called 'responseXML' that returns an XML document object.
2107      * @return {Object} records A data block which is used by an {@link Roo.data.Store} as
2108      * a cache of Roo.data.Records.
2109      */
2110     read : function(response){
2111         var doc = response.responseXML;
2112         if(!doc) {
2113             throw {message: "XmlReader.read: XML Document not available"};
2114         }
2115         return this.readRecords(doc);
2116     },
2117
2118     /**
2119      * Create a data block containing Roo.data.Records from an XML document.
2120          * @param {Object} doc A parsed XML document.
2121      * @return {Object} records A data block which is used by an {@link Roo.data.Store} as
2122      * a cache of Roo.data.Records.
2123      */
2124     readRecords : function(doc){
2125         /**
2126          * After any data loads/reads, the raw XML Document is available for further custom processing.
2127          * @type XMLDocument
2128          */
2129         this.xmlData = doc;
2130         var root = doc.documentElement || doc;
2131         var q = Roo.DomQuery;
2132         var recordType = this.recordType, fields = recordType.prototype.fields;
2133         var sid = this.meta.id;
2134         var totalRecords = 0, success = true;
2135         if(this.meta.totalRecords){
2136             totalRecords = q.selectNumber(this.meta.totalRecords, root, 0);
2137         }
2138         
2139         if(this.meta.success){
2140             var sv = q.selectValue(this.meta.success, root, true);
2141             success = sv !== false && sv !== 'false';
2142         }
2143         var records = [];
2144         var ns = q.select(this.meta.record, root);
2145         for(var i = 0, len = ns.length; i < len; i++) {
2146                 var n = ns[i];
2147                 var values = {};
2148                 var id = sid ? q.selectValue(sid, n) : undefined;
2149                 for(var j = 0, jlen = fields.length; j < jlen; j++){
2150                     var f = fields.items[j];
2151                 var v = q.selectValue(f.mapping || f.name, n, f.defaultValue);
2152                     v = f.convert(v);
2153                     values[f.name] = v;
2154                 }
2155                 var record = new recordType(values, id);
2156                 record.node = n;
2157                 records[records.length] = record;
2158             }
2159
2160             return {
2161                 success : success,
2162                 records : records,
2163                 totalRecords : totalRecords || records.length
2164             };
2165     }
2166 });/*
2167  * Based on:
2168  * Ext JS Library 1.1.1
2169  * Copyright(c) 2006-2007, Ext JS, LLC.
2170  *
2171  * Originally Released Under LGPL - original licence link has changed is not relivant.
2172  *
2173  * Fork - LGPL
2174  * <script type="text/javascript">
2175  */
2176
2177 /**
2178  * @class Roo.data.ArrayReader
2179  * @extends Roo.data.DataReader
2180  * Data reader class to create an Array of Roo.data.Record objects from an Array.
2181  * Each element of that Array represents a row of data fields. The
2182  * fields are pulled into a Record object using as a subscript, the <em>mapping</em> property
2183  * of the field definition if it exists, or the field's ordinal position in the definition.<br>
2184  * <p>
2185  * Example code:.
2186  * <pre><code>
2187 var RecordDef = Roo.data.Record.create([
2188     {name: 'name', mapping: 1},         // "mapping" only needed if an "id" field is present which
2189     {name: 'occupation', mapping: 2}    // precludes using the ordinal position as the index.
2190 ]);
2191 var myReader = new Roo.data.ArrayReader({
2192     id: 0                     // The subscript within row Array that provides an ID for the Record (optional)
2193 }, RecordDef);
2194 </code></pre>
2195  * <p>
2196  * This would consume an Array like this:
2197  * <pre><code>
2198 [ [1, 'Bill', 'Gardener'], [2, 'Ben', 'Horticulturalist'] ]
2199   </code></pre>
2200  
2201  * @constructor
2202  * Create a new JsonReader
2203  * @param {Object} meta Metadata configuration options.
2204  * @param {Object|Array} recordType Either an Array of field definition objects
2205  * 
2206  * @cfg {Array} fields Array of field definition objects
2207  * @cfg {String} id Name of the property within a row object that contains a record identifier value.
2208  * as specified to {@link Roo.data.Record#create},
2209  * or an {@link Roo.data.Record} object
2210  *
2211  * 
2212  * created using {@link Roo.data.Record#create}.
2213  */
2214 Roo.data.ArrayReader = function(meta, recordType)
2215 {    
2216     Roo.data.ArrayReader.superclass.constructor.call(this, meta, recordType||meta.fields);
2217 };
2218
2219 Roo.extend(Roo.data.ArrayReader, Roo.data.JsonReader, {
2220     
2221       /**
2222      * Create a data block containing Roo.data.Records from an XML document.
2223      * @param {Object} o An Array of row objects which represents the dataset.
2224      * @return {Object} A data block which is used by an {@link Roo.data.Store} object as
2225      * a cache of Roo.data.Records.
2226      */
2227     readRecords : function(o)
2228     {
2229         var sid = this.meta ? this.meta.id : null;
2230         var recordType = this.recordType, fields = recordType.prototype.fields;
2231         var records = [];
2232         var root = o;
2233         for(var i = 0; i < root.length; i++){
2234             var n = root[i];
2235             var values = {};
2236             var id = ((sid || sid === 0) && n[sid] !== undefined && n[sid] !== "" ? n[sid] : null);
2237             for(var j = 0, jlen = fields.length; j < jlen; j++){
2238                 var f = fields.items[j];
2239                 var k = f.mapping !== undefined && f.mapping !== null ? f.mapping : j;
2240                 var v = n[k] !== undefined ? n[k] : f.defaultValue;
2241                 v = f.convert(v);
2242                 values[f.name] = v;
2243             }
2244             var record = new recordType(values, id);
2245             record.json = n;
2246             records[records.length] = record;
2247         }
2248         return {
2249             records : records,
2250             totalRecords : records.length
2251         };
2252     },
2253     // used when loading children.. @see loadDataFromChildren
2254     toLoadData: function(rec)
2255     {
2256         // expect rec just to be an array.. eg [a,b,c, [...] << cn ]
2257         return typeof(rec.data.cn) == 'undefined' ? [] : rec.data.cn;
2258         
2259     }
2260     
2261     
2262 });/*
2263  * Based on:
2264  * Ext JS Library 1.1.1
2265  * Copyright(c) 2006-2007, Ext JS, LLC.
2266  *
2267  * Originally Released Under LGPL - original licence link has changed is not relivant.
2268  *
2269  * Fork - LGPL
2270  * <script type="text/javascript">
2271  */
2272
2273
2274 /**
2275  * @class Roo.data.Tree
2276  * @extends Roo.util.Observable
2277  * Represents a tree data structure and bubbles all the events for its nodes. The nodes
2278  * in the tree have most standard DOM functionality.
2279  * @constructor
2280  * @param {Node} root (optional) The root node
2281  */
2282 Roo.data.Tree = function(root){
2283    this.nodeHash = {};
2284    /**
2285     * The root node for this tree
2286     * @type Node
2287     */
2288    this.root = null;
2289    if(root){
2290        this.setRootNode(root);
2291    }
2292    this.addEvents({
2293        /**
2294         * @event append
2295         * Fires when a new child node is appended to a node in this tree.
2296         * @param {Tree} tree The owner tree
2297         * @param {Node} parent The parent node
2298         * @param {Node} node The newly appended node
2299         * @param {Number} index The index of the newly appended node
2300         */
2301        "append" : true,
2302        /**
2303         * @event remove
2304         * Fires when a child node is removed from a node in this tree.
2305         * @param {Tree} tree The owner tree
2306         * @param {Node} parent The parent node
2307         * @param {Node} node The child node removed
2308         */
2309        "remove" : true,
2310        /**
2311         * @event move
2312         * Fires when a node is moved to a new location in the tree
2313         * @param {Tree} tree The owner tree
2314         * @param {Node} node The node moved
2315         * @param {Node} oldParent The old parent of this node
2316         * @param {Node} newParent The new parent of this node
2317         * @param {Number} index The index it was moved to
2318         */
2319        "move" : true,
2320        /**
2321         * @event insert
2322         * Fires when a new child node is inserted in a node in this tree.
2323         * @param {Tree} tree The owner tree
2324         * @param {Node} parent The parent node
2325         * @param {Node} node The child node inserted
2326         * @param {Node} refNode The child node the node was inserted before
2327         */
2328        "insert" : true,
2329        /**
2330         * @event beforeappend
2331         * Fires before a new child is appended to a node in this tree, return false to cancel the append.
2332         * @param {Tree} tree The owner tree
2333         * @param {Node} parent The parent node
2334         * @param {Node} node The child node to be appended
2335         */
2336        "beforeappend" : true,
2337        /**
2338         * @event beforeremove
2339         * Fires before a child is removed from a node in this tree, return false to cancel the remove.
2340         * @param {Tree} tree The owner tree
2341         * @param {Node} parent The parent node
2342         * @param {Node} node The child node to be removed
2343         */
2344        "beforeremove" : true,
2345        /**
2346         * @event beforemove
2347         * Fires before a node is moved to a new location in the tree. Return false to cancel the move.
2348         * @param {Tree} tree The owner tree
2349         * @param {Node} node The node being moved
2350         * @param {Node} oldParent The parent of the node
2351         * @param {Node} newParent The new parent the node is moving to
2352         * @param {Number} index The index it is being moved to
2353         */
2354        "beforemove" : true,
2355        /**
2356         * @event beforeinsert
2357         * Fires before a new child is inserted in a node in this tree, return false to cancel the insert.
2358         * @param {Tree} tree The owner tree
2359         * @param {Node} parent The parent node
2360         * @param {Node} node The child node to be inserted
2361         * @param {Node} refNode The child node the node is being inserted before
2362         */
2363        "beforeinsert" : true
2364    });
2365
2366     Roo.data.Tree.superclass.constructor.call(this);
2367 };
2368
2369 Roo.extend(Roo.data.Tree, Roo.util.Observable, {
2370     pathSeparator: "/",
2371
2372     proxyNodeEvent : function(){
2373         return this.fireEvent.apply(this, arguments);
2374     },
2375
2376     /**
2377      * Returns the root node for this tree.
2378      * @return {Node}
2379      */
2380     getRootNode : function(){
2381         return this.root;
2382     },
2383
2384     /**
2385      * Sets the root node for this tree.
2386      * @param {Node} node
2387      * @return {Node}
2388      */
2389     setRootNode : function(node){
2390         this.root = node;
2391         node.ownerTree = this;
2392         node.isRoot = true;
2393         this.registerNode(node);
2394         return node;
2395     },
2396
2397     /**
2398      * Gets a node in this tree by its id.
2399      * @param {String} id
2400      * @return {Node}
2401      */
2402     getNodeById : function(id){
2403         return this.nodeHash[id];
2404     },
2405
2406     registerNode : function(node){
2407         this.nodeHash[node.id] = node;
2408     },
2409
2410     unregisterNode : function(node){
2411         delete this.nodeHash[node.id];
2412     },
2413
2414     toString : function(){
2415         return "[Tree"+(this.id?" "+this.id:"")+"]";
2416     }
2417 });
2418
2419 /**
2420  * @class Roo.data.Node
2421  * @extends Roo.util.Observable
2422  * @cfg {Boolean} leaf true if this node is a leaf and does not have children
2423  * @cfg {String} id The id for this node. If one is not specified, one is generated.
2424  * @constructor
2425  * @param {Object} attributes The attributes/config for the node
2426  */
2427 Roo.data.Node = function(attributes){
2428     /**
2429      * The attributes supplied for the node. You can use this property to access any custom attributes you supplied.
2430      * @type {Object}
2431      */
2432     this.attributes = attributes || {};
2433     this.leaf = this.attributes.leaf;
2434     /**
2435      * The node id. @type String
2436      */
2437     this.id = this.attributes.id;
2438     if(!this.id){
2439         this.id = Roo.id(null, "ynode-");
2440         this.attributes.id = this.id;
2441     }
2442      
2443     
2444     /**
2445      * All child nodes of this node. @type Array
2446      */
2447     this.childNodes = [];
2448     if(!this.childNodes.indexOf){ // indexOf is a must
2449         this.childNodes.indexOf = function(o){
2450             for(var i = 0, len = this.length; i < len; i++){
2451                 if(this[i] == o) {
2452                     return i;
2453                 }
2454             }
2455             return -1;
2456         };
2457     }
2458     /**
2459      * The parent node for this node. @type Node
2460      */
2461     this.parentNode = null;
2462     /**
2463      * The first direct child node of this node, or null if this node has no child nodes. @type Node
2464      */
2465     this.firstChild = null;
2466     /**
2467      * The last direct child node of this node, or null if this node has no child nodes. @type Node
2468      */
2469     this.lastChild = null;
2470     /**
2471      * The node immediately preceding this node in the tree, or null if there is no sibling node. @type Node
2472      */
2473     this.previousSibling = null;
2474     /**
2475      * The node immediately following this node in the tree, or null if there is no sibling node. @type Node
2476      */
2477     this.nextSibling = null;
2478
2479     this.addEvents({
2480        /**
2481         * @event append
2482         * Fires when a new child node is appended
2483         * @param {Tree} tree The owner tree
2484         * @param {Node} this This node
2485         * @param {Node} node The newly appended node
2486         * @param {Number} index The index of the newly appended node
2487         */
2488        "append" : true,
2489        /**
2490         * @event remove
2491         * Fires when a child node is removed
2492         * @param {Tree} tree The owner tree
2493         * @param {Node} this This node
2494         * @param {Node} node The removed node
2495         */
2496        "remove" : true,
2497        /**
2498         * @event move
2499         * Fires when this node is moved to a new location in the tree
2500         * @param {Tree} tree The owner tree
2501         * @param {Node} this This node
2502         * @param {Node} oldParent The old parent of this node
2503         * @param {Node} newParent The new parent of this node
2504         * @param {Number} index The index it was moved to
2505         */
2506        "move" : true,
2507        /**
2508         * @event insert
2509         * Fires when a new child node is inserted.
2510         * @param {Tree} tree The owner tree
2511         * @param {Node} this This node
2512         * @param {Node} node The child node inserted
2513         * @param {Node} refNode The child node the node was inserted before
2514         */
2515        "insert" : true,
2516        /**
2517         * @event beforeappend
2518         * Fires before a new child is appended, return false to cancel the append.
2519         * @param {Tree} tree The owner tree
2520         * @param {Node} this This node
2521         * @param {Node} node The child node to be appended
2522         */
2523        "beforeappend" : true,
2524        /**
2525         * @event beforeremove
2526         * Fires before a child is removed, return false to cancel the remove.
2527         * @param {Tree} tree The owner tree
2528         * @param {Node} this This node
2529         * @param {Node} node The child node to be removed
2530         */
2531        "beforeremove" : true,
2532        /**
2533         * @event beforemove
2534         * Fires before this node is moved to a new location in the tree. Return false to cancel the move.
2535         * @param {Tree} tree The owner tree
2536         * @param {Node} this This node
2537         * @param {Node} oldParent The parent of this node
2538         * @param {Node} newParent The new parent this node is moving to
2539         * @param {Number} index The index it is being moved to
2540         */
2541        "beforemove" : true,
2542        /**
2543         * @event beforeinsert
2544         * Fires before a new child is inserted, return false to cancel the insert.
2545         * @param {Tree} tree The owner tree
2546         * @param {Node} this This node
2547         * @param {Node} node The child node to be inserted
2548         * @param {Node} refNode The child node the node is being inserted before
2549         */
2550        "beforeinsert" : true
2551    });
2552     this.listeners = this.attributes.listeners;
2553     Roo.data.Node.superclass.constructor.call(this);
2554 };
2555
2556 Roo.extend(Roo.data.Node, Roo.util.Observable, {
2557     fireEvent : function(evtName){
2558         // first do standard event for this node
2559         if(Roo.data.Node.superclass.fireEvent.apply(this, arguments) === false){
2560             return false;
2561         }
2562         // then bubble it up to the tree if the event wasn't cancelled
2563         var ot = this.getOwnerTree();
2564         if(ot){
2565             if(ot.proxyNodeEvent.apply(ot, arguments) === false){
2566                 return false;
2567             }
2568         }
2569         return true;
2570     },
2571
2572     /**
2573      * Returns true if this node is a leaf
2574      * @return {Boolean}
2575      */
2576     isLeaf : function(){
2577         return this.leaf === true;
2578     },
2579
2580     // private
2581     setFirstChild : function(node){
2582         this.firstChild = node;
2583     },
2584
2585     //private
2586     setLastChild : function(node){
2587         this.lastChild = node;
2588     },
2589
2590
2591     /**
2592      * Returns true if this node is the last child of its parent
2593      * @return {Boolean}
2594      */
2595     isLast : function(){
2596        return (!this.parentNode ? true : this.parentNode.lastChild == this);
2597     },
2598
2599     /**
2600      * Returns true if this node is the first child of its parent
2601      * @return {Boolean}
2602      */
2603     isFirst : function(){
2604        return (!this.parentNode ? true : this.parentNode.firstChild == this);
2605     },
2606
2607     hasChildNodes : function(){
2608         return !this.isLeaf() && this.childNodes.length > 0;
2609     },
2610
2611     /**
2612      * Insert node(s) as the last child node of this node.
2613      * @param {Node/Array} node The node or Array of nodes to append
2614      * @return {Node} The appended node if single append, or null if an array was passed
2615      */
2616     appendChild : function(node){
2617         var multi = false;
2618         if(node instanceof Array){
2619             multi = node;
2620         }else if(arguments.length > 1){
2621             multi = arguments;
2622         }
2623         
2624         // if passed an array or multiple args do them one by one
2625         if(multi){
2626             for(var i = 0, len = multi.length; i < len; i++) {
2627                 this.appendChild(multi[i]);
2628             }
2629         }else{
2630             if(this.fireEvent("beforeappend", this.ownerTree, this, node) === false){
2631                 return false;
2632             }
2633             var index = this.childNodes.length;
2634             var oldParent = node.parentNode;
2635             // it's a move, make sure we move it cleanly
2636             if(oldParent){
2637                 if(node.fireEvent("beforemove", node.getOwnerTree(), node, oldParent, this, index) === false){
2638                     return false;
2639                 }
2640                 oldParent.removeChild(node);
2641             }
2642             
2643             index = this.childNodes.length;
2644             if(index == 0){
2645                 this.setFirstChild(node);
2646             }
2647             this.childNodes.push(node);
2648             node.parentNode = this;
2649             var ps = this.childNodes[index-1];
2650             if(ps){
2651                 node.previousSibling = ps;
2652                 ps.nextSibling = node;
2653             }else{
2654                 node.previousSibling = null;
2655             }
2656             node.nextSibling = null;
2657             this.setLastChild(node);
2658             node.setOwnerTree(this.getOwnerTree());
2659             this.fireEvent("append", this.ownerTree, this, node, index);
2660             if(this.ownerTree) {
2661                 this.ownerTree.fireEvent("appendnode", this, node, index);
2662             }
2663             if(oldParent){
2664                 node.fireEvent("move", this.ownerTree, node, oldParent, this, index);
2665             }
2666             return node;
2667         }
2668     },
2669
2670     /**
2671      * Removes a child node from this node.
2672      * @param {Node} node The node to remove
2673      * @return {Node} The removed node
2674      */
2675     removeChild : function(node){
2676         var index = this.childNodes.indexOf(node);
2677         if(index == -1){
2678             return false;
2679         }
2680         if(this.fireEvent("beforeremove", this.ownerTree, this, node) === false){
2681             return false;
2682         }
2683
2684         // remove it from childNodes collection
2685         this.childNodes.splice(index, 1);
2686
2687         // update siblings
2688         if(node.previousSibling){
2689             node.previousSibling.nextSibling = node.nextSibling;
2690         }
2691         if(node.nextSibling){
2692             node.nextSibling.previousSibling = node.previousSibling;
2693         }
2694
2695         // update child refs
2696         if(this.firstChild == node){
2697             this.setFirstChild(node.nextSibling);
2698         }
2699         if(this.lastChild == node){
2700             this.setLastChild(node.previousSibling);
2701         }
2702
2703         node.setOwnerTree(null);
2704         // clear any references from the node
2705         node.parentNode = null;
2706         node.previousSibling = null;
2707         node.nextSibling = null;
2708         this.fireEvent("remove", this.ownerTree, this, node);
2709         return node;
2710     },
2711
2712     /**
2713      * Inserts the first node before the second node in this nodes childNodes collection.
2714      * @param {Node} node The node to insert
2715      * @param {Node} refNode The node to insert before (if null the node is appended)
2716      * @return {Node} The inserted node
2717      */
2718     insertBefore : function(node, refNode){
2719         if(!refNode){ // like standard Dom, refNode can be null for append
2720             return this.appendChild(node);
2721         }
2722         // nothing to do
2723         if(node == refNode){
2724             return false;
2725         }
2726
2727         if(this.fireEvent("beforeinsert", this.ownerTree, this, node, refNode) === false){
2728             return false;
2729         }
2730         var index = this.childNodes.indexOf(refNode);
2731         var oldParent = node.parentNode;
2732         var refIndex = index;
2733
2734         // when moving internally, indexes will change after remove
2735         if(oldParent == this && this.childNodes.indexOf(node) < index){
2736             refIndex--;
2737         }
2738
2739         // it's a move, make sure we move it cleanly
2740         if(oldParent){
2741             if(node.fireEvent("beforemove", node.getOwnerTree(), node, oldParent, this, index, refNode) === false){
2742                 return false;
2743             }
2744             oldParent.removeChild(node);
2745         }
2746         if(refIndex == 0){
2747             this.setFirstChild(node);
2748         }
2749         this.childNodes.splice(refIndex, 0, node);
2750         node.parentNode = this;
2751         var ps = this.childNodes[refIndex-1];
2752         if(ps){
2753             node.previousSibling = ps;
2754             ps.nextSibling = node;
2755         }else{
2756             node.previousSibling = null;
2757         }
2758         node.nextSibling = refNode;
2759         refNode.previousSibling = node;
2760         node.setOwnerTree(this.getOwnerTree());
2761         this.fireEvent("insert", this.ownerTree, this, node, refNode);
2762         if(oldParent){
2763             node.fireEvent("move", this.ownerTree, node, oldParent, this, refIndex, refNode);
2764         }
2765         return node;
2766     },
2767
2768     /**
2769      * Returns the child node at the specified index.
2770      * @param {Number} index
2771      * @return {Node}
2772      */
2773     item : function(index){
2774         return this.childNodes[index];
2775     },
2776
2777     /**
2778      * Replaces one child node in this node with another.
2779      * @param {Node} newChild The replacement node
2780      * @param {Node} oldChild The node to replace
2781      * @return {Node} The replaced node
2782      */
2783     replaceChild : function(newChild, oldChild){
2784         this.insertBefore(newChild, oldChild);
2785         this.removeChild(oldChild);
2786         return oldChild;
2787     },
2788
2789     /**
2790      * Returns the index of a child node
2791      * @param {Node} node
2792      * @return {Number} The index of the node or -1 if it was not found
2793      */
2794     indexOf : function(child){
2795         return this.childNodes.indexOf(child);
2796     },
2797
2798     /**
2799      * Returns the tree this node is in.
2800      * @return {Tree}
2801      */
2802     getOwnerTree : function(){
2803         // if it doesn't have one, look for one
2804         if(!this.ownerTree){
2805             var p = this;
2806             while(p){
2807                 if(p.ownerTree){
2808                     this.ownerTree = p.ownerTree;
2809                     break;
2810                 }
2811                 p = p.parentNode;
2812             }
2813         }
2814         return this.ownerTree;
2815     },
2816
2817     /**
2818      * Returns depth of this node (the root node has a depth of 0)
2819      * @return {Number}
2820      */
2821     getDepth : function(){
2822         var depth = 0;
2823         var p = this;
2824         while(p.parentNode){
2825             ++depth;
2826             p = p.parentNode;
2827         }
2828         return depth;
2829     },
2830
2831     // private
2832     setOwnerTree : function(tree){
2833         // if it's move, we need to update everyone
2834         if(tree != this.ownerTree){
2835             if(this.ownerTree){
2836                 this.ownerTree.unregisterNode(this);
2837             }
2838             this.ownerTree = tree;
2839             var cs = this.childNodes;
2840             for(var i = 0, len = cs.length; i < len; i++) {
2841                 cs[i].setOwnerTree(tree);
2842             }
2843             if(tree){
2844                 tree.registerNode(this);
2845             }
2846         }
2847     },
2848
2849     /**
2850      * Returns the path for this node. The path can be used to expand or select this node programmatically.
2851      * @param {String} attr (optional) The attr to use for the path (defaults to the node's id)
2852      * @return {String} The path
2853      */
2854     getPath : function(attr){
2855         attr = attr || "id";
2856         var p = this.parentNode;
2857         var b = [this.attributes[attr]];
2858         while(p){
2859             b.unshift(p.attributes[attr]);
2860             p = p.parentNode;
2861         }
2862         var sep = this.getOwnerTree().pathSeparator;
2863         return sep + b.join(sep);
2864     },
2865
2866     /**
2867      * Bubbles up the tree from this node, calling the specified function with each node. The scope (<i>this</i>) of
2868      * function call will be the scope provided or the current node. The arguments to the function
2869      * will be the args provided or the current node. If the function returns false at any point,
2870      * the bubble is stopped.
2871      * @param {Function} fn The function to call
2872      * @param {Object} scope (optional) The scope of the function (defaults to current node)
2873      * @param {Array} args (optional) The args to call the function with (default to passing the current node)
2874      */
2875     bubble : function(fn, scope, args){
2876         var p = this;
2877         while(p){
2878             if(fn.call(scope || p, args || p) === false){
2879                 break;
2880             }
2881             p = p.parentNode;
2882         }
2883     },
2884
2885     /**
2886      * Cascades down the tree from this node, calling the specified function with each node. The scope (<i>this</i>) of
2887      * function call will be the scope provided or the current node. The arguments to the function
2888      * will be the args provided or the current node. If the function returns false at any point,
2889      * the cascade is stopped on that branch.
2890      * @param {Function} fn The function to call
2891      * @param {Object} scope (optional) The scope of the function (defaults to current node)
2892      * @param {Array} args (optional) The args to call the function with (default to passing the current node)
2893      */
2894     cascade : function(fn, scope, args){
2895         if(fn.call(scope || this, args || this) !== false){
2896             var cs = this.childNodes;
2897             for(var i = 0, len = cs.length; i < len; i++) {
2898                 cs[i].cascade(fn, scope, args);
2899             }
2900         }
2901     },
2902
2903     /**
2904      * Interates the child nodes of this node, calling the specified function with each node. The scope (<i>this</i>) of
2905      * function call will be the scope provided or the current node. The arguments to the function
2906      * will be the args provided or the current node. If the function returns false at any point,
2907      * the iteration stops.
2908      * @param {Function} fn The function to call
2909      * @param {Object} scope (optional) The scope of the function (defaults to current node)
2910      * @param {Array} args (optional) The args to call the function with (default to passing the current node)
2911      */
2912     eachChild : function(fn, scope, args){
2913         var cs = this.childNodes;
2914         for(var i = 0, len = cs.length; i < len; i++) {
2915                 if(fn.call(scope || this, args || cs[i]) === false){
2916                     break;
2917                 }
2918         }
2919     },
2920
2921     /**
2922      * Finds the first child that has the attribute with the specified value.
2923      * @param {String} attribute The attribute name
2924      * @param {Mixed} value The value to search for
2925      * @return {Node} The found child or null if none was found
2926      */
2927     findChild : function(attribute, value){
2928         var cs = this.childNodes;
2929         for(var i = 0, len = cs.length; i < len; i++) {
2930                 if(cs[i].attributes[attribute] == value){
2931                     return cs[i];
2932                 }
2933         }
2934         return null;
2935     },
2936
2937     /**
2938      * Finds the first child by a custom function. The child matches if the function passed
2939      * returns true.
2940      * @param {Function} fn
2941      * @param {Object} scope (optional)
2942      * @return {Node} The found child or null if none was found
2943      */
2944     findChildBy : function(fn, scope){
2945         var cs = this.childNodes;
2946         for(var i = 0, len = cs.length; i < len; i++) {
2947                 if(fn.call(scope||cs[i], cs[i]) === true){
2948                     return cs[i];
2949                 }
2950         }
2951         return null;
2952     },
2953
2954     /**
2955      * Sorts this nodes children using the supplied sort function
2956      * @param {Function} fn
2957      * @param {Object} scope (optional)
2958      */
2959     sort : function(fn, scope){
2960         var cs = this.childNodes;
2961         var len = cs.length;
2962         if(len > 0){
2963             var sortFn = scope ? function(){fn.apply(scope, arguments);} : fn;
2964             cs.sort(sortFn);
2965             for(var i = 0; i < len; i++){
2966                 var n = cs[i];
2967                 n.previousSibling = cs[i-1];
2968                 n.nextSibling = cs[i+1];
2969                 if(i == 0){
2970                     this.setFirstChild(n);
2971                 }
2972                 if(i == len-1){
2973                     this.setLastChild(n);
2974                 }
2975             }
2976         }
2977     },
2978
2979     /**
2980      * Returns true if this node is an ancestor (at any point) of the passed node.
2981      * @param {Node} node
2982      * @return {Boolean}
2983      */
2984     contains : function(node){
2985         return node.isAncestor(this);
2986     },
2987
2988     /**
2989      * Returns true if the passed node is an ancestor (at any point) of this node.
2990      * @param {Node} node
2991      * @return {Boolean}
2992      */
2993     isAncestor : function(node){
2994         var p = this.parentNode;
2995         while(p){
2996             if(p == node){
2997                 return true;
2998             }
2999             p = p.parentNode;
3000         }
3001         return false;
3002     },
3003
3004     toString : function(){
3005         return "[Node"+(this.id?" "+this.id:"")+"]";
3006     }
3007 });/*
3008  * Based on:
3009  * Ext JS Library 1.1.1
3010  * Copyright(c) 2006-2007, Ext JS, LLC.
3011  *
3012  * Originally Released Under LGPL - original licence link has changed is not relivant.
3013  *
3014  * Fork - LGPL
3015  * <script type="text/javascript">
3016  */
3017
3018
3019 /**
3020  * @class Roo.Shadow
3021  * Simple class that can provide a shadow effect for any element.  Note that the element MUST be absolutely positioned,
3022  * and the shadow does not provide any shimming.  This should be used only in simple cases -- for more advanced
3023  * functionality that can also provide the same shadow effect, see the {@link Roo.Layer} class.
3024  * @constructor
3025  * Create a new Shadow
3026  * @param {Object} config The config object
3027  */
3028 Roo.Shadow = function(config){
3029     Roo.apply(this, config);
3030     if(typeof this.mode != "string"){
3031         this.mode = this.defaultMode;
3032     }
3033     var o = this.offset, a = {h: 0};
3034     var rad = Math.floor(this.offset/2);
3035     switch(this.mode.toLowerCase()){ // all this hideous nonsense calculates the various offsets for shadows
3036         case "drop":
3037             a.w = 0;
3038             a.l = a.t = o;
3039             a.t -= 1;
3040             if(Roo.isIE){
3041                 a.l -= this.offset + rad;
3042                 a.t -= this.offset + rad;
3043                 a.w -= rad;
3044                 a.h -= rad;
3045                 a.t += 1;
3046             }
3047         break;
3048         case "sides":
3049             a.w = (o*2);
3050             a.l = -o;
3051             a.t = o-1;
3052             if(Roo.isIE){
3053                 a.l -= (this.offset - rad);
3054                 a.t -= this.offset + rad;
3055                 a.l += 1;
3056                 a.w -= (this.offset - rad)*2;
3057                 a.w -= rad + 1;
3058                 a.h -= 1;
3059             }
3060         break;
3061         case "frame":
3062             a.w = a.h = (o*2);
3063             a.l = a.t = -o;
3064             a.t += 1;
3065             a.h -= 2;
3066             if(Roo.isIE){
3067                 a.l -= (this.offset - rad);
3068                 a.t -= (this.offset - rad);
3069                 a.l += 1;
3070                 a.w -= (this.offset + rad + 1);
3071                 a.h -= (this.offset + rad);
3072                 a.h += 1;
3073             }
3074         break;
3075     };
3076
3077     this.adjusts = a;
3078 };
3079
3080 Roo.Shadow.prototype = {
3081     /**
3082      * @cfg {String} mode
3083      * The shadow display mode.  Supports the following options:<br />
3084      * sides: Shadow displays on both sides and bottom only<br />
3085      * frame: Shadow displays equally on all four sides<br />
3086      * drop: Traditional bottom-right drop shadow (default)
3087      */
3088     mode: false,
3089     /**
3090      * @cfg {String} offset
3091      * The number of pixels to offset the shadow from the element (defaults to 4)
3092      */
3093     offset: 4,
3094
3095     // private
3096     defaultMode: "drop",
3097
3098     /**
3099      * Displays the shadow under the target element
3100      * @param {String/HTMLElement/Element} targetEl The id or element under which the shadow should display
3101      */
3102     show : function(target){
3103         target = Roo.get(target);
3104         if(!this.el){
3105             this.el = Roo.Shadow.Pool.pull();
3106             if(this.el.dom.nextSibling != target.dom){
3107                 this.el.insertBefore(target);
3108             }
3109         }
3110         this.el.setStyle("z-index", this.zIndex || parseInt(target.getStyle("z-index"), 10)-1);
3111         if(Roo.isIE){
3112             this.el.dom.style.filter="progid:DXImageTransform.Microsoft.alpha(opacity=50) progid:DXImageTransform.Microsoft.Blur(pixelradius="+(this.offset)+")";
3113         }
3114         this.realign(
3115             target.getLeft(true),
3116             target.getTop(true),
3117             target.getWidth(),
3118             target.getHeight()
3119         );
3120         this.el.dom.style.display = "block";
3121     },
3122
3123     /**
3124      * Returns true if the shadow is visible, else false
3125      */
3126     isVisible : function(){
3127         return this.el ? true : false;  
3128     },
3129
3130     /**
3131      * Direct alignment when values are already available. Show must be called at least once before
3132      * calling this method to ensure it is initialized.
3133      * @param {Number} left The target element left position
3134      * @param {Number} top The target element top position
3135      * @param {Number} width The target element width
3136      * @param {Number} height The target element height
3137      */
3138     realign : function(l, t, w, h){
3139         if(!this.el){
3140             return;
3141         }
3142         var a = this.adjusts, d = this.el.dom, s = d.style;
3143         var iea = 0;
3144         s.left = (l+a.l)+"px";
3145         s.top = (t+a.t)+"px";
3146         var sw = (w+a.w), sh = (h+a.h), sws = sw +"px", shs = sh + "px";
3147  
3148         if(s.width != sws || s.height != shs){
3149             s.width = sws;
3150             s.height = shs;
3151             if(!Roo.isIE){
3152                 var cn = d.childNodes;
3153                 var sww = Math.max(0, (sw-12))+"px";
3154                 cn[0].childNodes[1].style.width = sww;
3155                 cn[1].childNodes[1].style.width = sww;
3156                 cn[2].childNodes[1].style.width = sww;
3157                 cn[1].style.height = Math.max(0, (sh-12))+"px";
3158             }
3159         }
3160     },
3161
3162     /**
3163      * Hides this shadow
3164      */
3165     hide : function(){
3166         if(this.el){
3167             this.el.dom.style.display = "none";
3168             Roo.Shadow.Pool.push(this.el);
3169             delete this.el;
3170         }
3171     },
3172
3173     /**
3174      * Adjust the z-index of this shadow
3175      * @param {Number} zindex The new z-index
3176      */
3177     setZIndex : function(z){
3178         this.zIndex = z;
3179         if(this.el){
3180             this.el.setStyle("z-index", z);
3181         }
3182     }
3183 };
3184
3185 // Private utility class that manages the internal Shadow cache
3186 Roo.Shadow.Pool = function(){
3187     var p = [];
3188     var markup = Roo.isIE ?
3189                  '<div class="x-ie-shadow"></div>' :
3190                  '<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>';
3191     return {
3192         pull : function(){
3193             var sh = p.shift();
3194             if(!sh){
3195                 sh = Roo.get(Roo.DomHelper.insertHtml("beforeBegin", document.body.firstChild, markup));
3196                 sh.autoBoxAdjust = false;
3197             }
3198             return sh;
3199         },
3200
3201         push : function(sh){
3202             p.push(sh);
3203         }
3204     };
3205 }();/*
3206  * Based on:
3207  * Ext JS Library 1.1.1
3208  * Copyright(c) 2006-2007, Ext JS, LLC.
3209  *
3210  * Originally Released Under LGPL - original licence link has changed is not relivant.
3211  *
3212  * Fork - LGPL
3213  * <script type="text/javascript">
3214  */
3215
3216
3217 /**
3218  * @class Roo.SplitBar
3219  * @extends Roo.util.Observable
3220  * Creates draggable splitter bar functionality from two elements (element to be dragged and element to be resized).
3221  * <br><br>
3222  * Usage:
3223  * <pre><code>
3224 var split = new Roo.SplitBar("elementToDrag", "elementToSize",
3225                    Roo.SplitBar.HORIZONTAL, Roo.SplitBar.LEFT);
3226 split.setAdapter(new Roo.SplitBar.AbsoluteLayoutAdapter("container"));
3227 split.minSize = 100;
3228 split.maxSize = 600;
3229 split.animate = true;
3230 split.on('moved', splitterMoved);
3231 </code></pre>
3232  * @constructor
3233  * Create a new SplitBar
3234  * @param {String/HTMLElement/Roo.Element} dragElement The element to be dragged and act as the SplitBar. 
3235  * @param {String/HTMLElement/Roo.Element} resizingElement The element to be resized based on where the SplitBar element is dragged 
3236  * @param {Number} orientation (optional) Either Roo.SplitBar.HORIZONTAL or Roo.SplitBar.VERTICAL. (Defaults to HORIZONTAL)
3237  * @param {Number} placement (optional) Either Roo.SplitBar.LEFT or Roo.SplitBar.RIGHT for horizontal or  
3238                         Roo.SplitBar.TOP or Roo.SplitBar.BOTTOM for vertical. (By default, this is determined automatically by the initial
3239                         position of the SplitBar).
3240  */
3241 Roo.SplitBar = function(dragElement, resizingElement, orientation, placement, existingProxy){
3242     
3243     /** @private */
3244     this.el = Roo.get(dragElement, true);
3245     this.el.dom.unselectable = "on";
3246     /** @private */
3247     this.resizingEl = Roo.get(resizingElement, true);
3248
3249     /**
3250      * @private
3251      * The orientation of the split. Either Roo.SplitBar.HORIZONTAL or Roo.SplitBar.VERTICAL. (Defaults to HORIZONTAL)
3252      * Note: If this is changed after creating the SplitBar, the placement property must be manually updated
3253      * @type Number
3254      */
3255     this.orientation = orientation || Roo.SplitBar.HORIZONTAL;
3256     
3257     /**
3258      * The minimum size of the resizing element. (Defaults to 0)
3259      * @type Number
3260      */
3261     this.minSize = 0;
3262     
3263     /**
3264      * The maximum size of the resizing element. (Defaults to 2000)
3265      * @type Number
3266      */
3267     this.maxSize = 2000;
3268     
3269     /**
3270      * Whether to animate the transition to the new size
3271      * @type Boolean
3272      */
3273     this.animate = false;
3274     
3275     /**
3276      * Whether to create a transparent shim that overlays the page when dragging, enables dragging across iframes.
3277      * @type Boolean
3278      */
3279     this.useShim = false;
3280     
3281     /** @private */
3282     this.shim = null;
3283     
3284     if(!existingProxy){
3285         /** @private */
3286         this.proxy = Roo.SplitBar.createProxy(this.orientation);
3287     }else{
3288         this.proxy = Roo.get(existingProxy).dom;
3289     }
3290     /** @private */
3291     this.dd = new Roo.dd.DDProxy(this.el.dom.id, "XSplitBars", {dragElId : this.proxy.id});
3292     
3293     /** @private */
3294     this.dd.b4StartDrag = this.onStartProxyDrag.createDelegate(this);
3295     
3296     /** @private */
3297     this.dd.endDrag = this.onEndProxyDrag.createDelegate(this);
3298     
3299     /** @private */
3300     this.dragSpecs = {};
3301     
3302     /**
3303      * @private The adapter to use to positon and resize elements
3304      */
3305     this.adapter = new Roo.SplitBar.BasicLayoutAdapter();
3306     this.adapter.init(this);
3307     
3308     if(this.orientation == Roo.SplitBar.HORIZONTAL){
3309         /** @private */
3310         this.placement = placement || (this.el.getX() > this.resizingEl.getX() ? Roo.SplitBar.LEFT : Roo.SplitBar.RIGHT);
3311         this.el.addClass("x-splitbar-h");
3312     }else{
3313         /** @private */
3314         this.placement = placement || (this.el.getY() > this.resizingEl.getY() ? Roo.SplitBar.TOP : Roo.SplitBar.BOTTOM);
3315         this.el.addClass("x-splitbar-v");
3316     }
3317     
3318     this.addEvents({
3319         /**
3320          * @event resize
3321          * Fires when the splitter is moved (alias for {@link #event-moved})
3322          * @param {Roo.SplitBar} this
3323          * @param {Number} newSize the new width or height
3324          */
3325         "resize" : true,
3326         /**
3327          * @event moved
3328          * Fires when the splitter is moved
3329          * @param {Roo.SplitBar} this
3330          * @param {Number} newSize the new width or height
3331          */
3332         "moved" : true,
3333         /**
3334          * @event beforeresize
3335          * Fires before the splitter is dragged
3336          * @param {Roo.SplitBar} this
3337          */
3338         "beforeresize" : true,
3339
3340         "beforeapply" : true
3341     });
3342
3343     Roo.util.Observable.call(this);
3344 };
3345
3346 Roo.extend(Roo.SplitBar, Roo.util.Observable, {
3347     onStartProxyDrag : function(x, y){
3348         this.fireEvent("beforeresize", this);
3349         if(!this.overlay){
3350             var o = Roo.DomHelper.insertFirst(document.body,  {cls: "x-drag-overlay", html: "&#160;"}, true);
3351             o.unselectable();
3352             o.enableDisplayMode("block");
3353             // all splitbars share the same overlay
3354             Roo.SplitBar.prototype.overlay = o;
3355         }
3356         this.overlay.setSize(Roo.lib.Dom.getViewWidth(true), Roo.lib.Dom.getViewHeight(true));
3357         this.overlay.show();
3358         Roo.get(this.proxy).setDisplayed("block");
3359         var size = this.adapter.getElementSize(this);
3360         this.activeMinSize = this.getMinimumSize();;
3361         this.activeMaxSize = this.getMaximumSize();;
3362         var c1 = size - this.activeMinSize;
3363         var c2 = Math.max(this.activeMaxSize - size, 0);
3364         if(this.orientation == Roo.SplitBar.HORIZONTAL){
3365             this.dd.resetConstraints();
3366             this.dd.setXConstraint(
3367                 this.placement == Roo.SplitBar.LEFT ? c1 : c2, 
3368                 this.placement == Roo.SplitBar.LEFT ? c2 : c1
3369             );
3370             this.dd.setYConstraint(0, 0);
3371         }else{
3372             this.dd.resetConstraints();
3373             this.dd.setXConstraint(0, 0);
3374             this.dd.setYConstraint(
3375                 this.placement == Roo.SplitBar.TOP ? c1 : c2, 
3376                 this.placement == Roo.SplitBar.TOP ? c2 : c1
3377             );
3378          }
3379         this.dragSpecs.startSize = size;
3380         this.dragSpecs.startPoint = [x, y];
3381         Roo.dd.DDProxy.prototype.b4StartDrag.call(this.dd, x, y);
3382     },
3383     
3384     /** 
3385      * @private Called after the drag operation by the DDProxy
3386      */
3387     onEndProxyDrag : function(e){
3388         Roo.get(this.proxy).setDisplayed(false);
3389         var endPoint = Roo.lib.Event.getXY(e);
3390         if(this.overlay){
3391             this.overlay.hide();
3392         }
3393         var newSize;
3394         if(this.orientation == Roo.SplitBar.HORIZONTAL){
3395             newSize = this.dragSpecs.startSize + 
3396                 (this.placement == Roo.SplitBar.LEFT ?
3397                     endPoint[0] - this.dragSpecs.startPoint[0] :
3398                     this.dragSpecs.startPoint[0] - endPoint[0]
3399                 );
3400         }else{
3401             newSize = this.dragSpecs.startSize + 
3402                 (this.placement == Roo.SplitBar.TOP ?
3403                     endPoint[1] - this.dragSpecs.startPoint[1] :
3404                     this.dragSpecs.startPoint[1] - endPoint[1]
3405                 );
3406         }
3407         newSize = Math.min(Math.max(newSize, this.activeMinSize), this.activeMaxSize);
3408         if(newSize != this.dragSpecs.startSize){
3409             if(this.fireEvent('beforeapply', this, newSize) !== false){
3410                 this.adapter.setElementSize(this, newSize);
3411                 this.fireEvent("moved", this, newSize);
3412                 this.fireEvent("resize", this, newSize);
3413             }
3414         }
3415     },
3416     
3417     /**
3418      * Get the adapter this SplitBar uses
3419      * @return The adapter object
3420      */
3421     getAdapter : function(){
3422         return this.adapter;
3423     },
3424     
3425     /**
3426      * Set the adapter this SplitBar uses
3427      * @param {Object} adapter A SplitBar adapter object
3428      */
3429     setAdapter : function(adapter){
3430         this.adapter = adapter;
3431         this.adapter.init(this);
3432     },
3433     
3434     /**
3435      * Gets the minimum size for the resizing element
3436      * @return {Number} The minimum size
3437      */
3438     getMinimumSize : function(){
3439         return this.minSize;
3440     },
3441     
3442     /**
3443      * Sets the minimum size for the resizing element
3444      * @param {Number} minSize The minimum size
3445      */
3446     setMinimumSize : function(minSize){
3447         this.minSize = minSize;
3448     },
3449     
3450     /**
3451      * Gets the maximum size for the resizing element
3452      * @return {Number} The maximum size
3453      */
3454     getMaximumSize : function(){
3455         return this.maxSize;
3456     },
3457     
3458     /**
3459      * Sets the maximum size for the resizing element
3460      * @param {Number} maxSize The maximum size
3461      */
3462     setMaximumSize : function(maxSize){
3463         this.maxSize = maxSize;
3464     },
3465     
3466     /**
3467      * Sets the initialize size for the resizing element
3468      * @param {Number} size The initial size
3469      */
3470     setCurrentSize : function(size){
3471         var oldAnimate = this.animate;
3472         this.animate = false;
3473         this.adapter.setElementSize(this, size);
3474         this.animate = oldAnimate;
3475     },
3476     
3477     /**
3478      * Destroy this splitbar. 
3479      * @param {Boolean} removeEl True to remove the element
3480      */
3481     destroy : function(removeEl){
3482         if(this.shim){
3483             this.shim.remove();
3484         }
3485         this.dd.unreg();
3486         this.proxy.parentNode.removeChild(this.proxy);
3487         if(removeEl){
3488             this.el.remove();
3489         }
3490     }
3491 });
3492
3493 /**
3494  * @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.
3495  */
3496 Roo.SplitBar.createProxy = function(dir){
3497     var proxy = new Roo.Element(document.createElement("div"));
3498     proxy.unselectable();
3499     var cls = 'x-splitbar-proxy';
3500     proxy.addClass(cls + ' ' + (dir == Roo.SplitBar.HORIZONTAL ? cls +'-h' : cls + '-v'));
3501     document.body.appendChild(proxy.dom);
3502     return proxy.dom;
3503 };
3504
3505 /** 
3506  * @class Roo.SplitBar.BasicLayoutAdapter
3507  * Default Adapter. It assumes the splitter and resizing element are not positioned
3508  * elements and only gets/sets the width of the element. Generally used for table based layouts.
3509  */
3510 Roo.SplitBar.BasicLayoutAdapter = function(){
3511 };
3512
3513 Roo.SplitBar.BasicLayoutAdapter.prototype = {
3514     // do nothing for now
3515     init : function(s){
3516     
3517     },
3518     /**
3519      * Called before drag operations to get the current size of the resizing element. 
3520      * @param {Roo.SplitBar} s The SplitBar using this adapter
3521      */
3522      getElementSize : function(s){
3523         if(s.orientation == Roo.SplitBar.HORIZONTAL){
3524             return s.resizingEl.getWidth();
3525         }else{
3526             return s.resizingEl.getHeight();
3527         }
3528     },
3529     
3530     /**
3531      * Called after drag operations to set the size of the resizing element.
3532      * @param {Roo.SplitBar} s The SplitBar using this adapter
3533      * @param {Number} newSize The new size to set
3534      * @param {Function} onComplete A function to be invoked when resizing is complete
3535      */
3536     setElementSize : function(s, newSize, onComplete){
3537         if(s.orientation == Roo.SplitBar.HORIZONTAL){
3538             if(!s.animate){
3539                 s.resizingEl.setWidth(newSize);
3540                 if(onComplete){
3541                     onComplete(s, newSize);
3542                 }
3543             }else{
3544                 s.resizingEl.setWidth(newSize, true, .1, onComplete, 'easeOut');
3545             }
3546         }else{
3547             
3548             if(!s.animate){
3549                 s.resizingEl.setHeight(newSize);
3550                 if(onComplete){
3551                     onComplete(s, newSize);
3552                 }
3553             }else{
3554                 s.resizingEl.setHeight(newSize, true, .1, onComplete, 'easeOut');
3555             }
3556         }
3557     }
3558 };
3559
3560 /** 
3561  *@class Roo.SplitBar.AbsoluteLayoutAdapter
3562  * @extends Roo.SplitBar.BasicLayoutAdapter
3563  * Adapter that  moves the splitter element to align with the resized sizing element. 
3564  * Used with an absolute positioned SplitBar.
3565  * @param {String/HTMLElement/Roo.Element} container The container that wraps around the absolute positioned content. If it's
3566  * document.body, make sure you assign an id to the body element.
3567  */
3568 Roo.SplitBar.AbsoluteLayoutAdapter = function(container){
3569     this.basic = new Roo.SplitBar.BasicLayoutAdapter();
3570     this.container = Roo.get(container);
3571 };
3572
3573 Roo.SplitBar.AbsoluteLayoutAdapter.prototype = {
3574     init : function(s){
3575         this.basic.init(s);
3576     },
3577     
3578     getElementSize : function(s){
3579         return this.basic.getElementSize(s);
3580     },
3581     
3582     setElementSize : function(s, newSize, onComplete){
3583         this.basic.setElementSize(s, newSize, this.moveSplitter.createDelegate(this, [s]));
3584     },
3585     
3586     moveSplitter : function(s){
3587         var yes = Roo.SplitBar;
3588         switch(s.placement){
3589             case yes.LEFT:
3590                 s.el.setX(s.resizingEl.getRight());
3591                 break;
3592             case yes.RIGHT:
3593                 s.el.setStyle("right", (this.container.getWidth() - s.resizingEl.getLeft()) + "px");
3594                 break;
3595             case yes.TOP:
3596                 s.el.setY(s.resizingEl.getBottom());
3597                 break;
3598             case yes.BOTTOM:
3599                 s.el.setY(s.resizingEl.getTop() - s.el.getHeight());
3600                 break;
3601         }
3602     }
3603 };
3604
3605 /**
3606  * Orientation constant - Create a vertical SplitBar
3607  * @static
3608  * @type Number
3609  */
3610 Roo.SplitBar.VERTICAL = 1;
3611
3612 /**
3613  * Orientation constant - Create a horizontal SplitBar
3614  * @static
3615  * @type Number
3616  */
3617 Roo.SplitBar.HORIZONTAL = 2;
3618
3619 /**
3620  * Placement constant - The resizing element is to the left of the splitter element
3621  * @static
3622  * @type Number
3623  */
3624 Roo.SplitBar.LEFT = 1;
3625
3626 /**
3627  * Placement constant - The resizing element is to the right of the splitter element
3628  * @static
3629  * @type Number
3630  */
3631 Roo.SplitBar.RIGHT = 2;
3632
3633 /**
3634  * Placement constant - The resizing element is positioned above the splitter element
3635  * @static
3636  * @type Number
3637  */
3638 Roo.SplitBar.TOP = 3;
3639
3640 /**
3641  * Placement constant - The resizing element is positioned under splitter element
3642  * @static
3643  * @type Number
3644  */
3645 Roo.SplitBar.BOTTOM = 4;
3646 /*
3647  * Based on:
3648  * Ext JS Library 1.1.1
3649  * Copyright(c) 2006-2007, Ext JS, LLC.
3650  *
3651  * Originally Released Under LGPL - original licence link has changed is not relivant.
3652  *
3653  * Fork - LGPL
3654  * <script type="text/javascript">
3655  */
3656
3657 /**
3658  * @class Roo.View
3659  * @extends Roo.util.Observable
3660  * Create a "View" for an element based on a data model or UpdateManager and the supplied DomHelper template. 
3661  * This class also supports single and multi selection modes. <br>
3662  * Create a data model bound view:
3663  <pre><code>
3664  var store = new Roo.data.Store(...);
3665
3666  var view = new Roo.View({
3667     el : "my-element",
3668     tpl : '&lt;div id="{0}"&gt;{2} - {1}&lt;/div&gt;', // auto create template
3669  
3670     singleSelect: true,
3671     selectedClass: "ydataview-selected",
3672     store: store
3673  });
3674
3675  // listen for node click?
3676  view.on("click", function(vw, index, node, e){
3677  alert('Node "' + node.id + '" at index: ' + index + " was clicked.");
3678  });
3679
3680  // load XML data
3681  dataModel.load("foobar.xml");
3682  </code></pre>
3683  For an example of creating a JSON/UpdateManager view, see {@link Roo.JsonView}.
3684  * <br><br>
3685  * <b>Note: The root of your template must be a single node. Table/row implementations may work but are not supported due to
3686  * IE"s limited insertion support with tables and Opera"s faulty event bubbling.</b>
3687  * 
3688  * Note: old style constructor is still suported (container, template, config)
3689  * 
3690  * @constructor
3691  * Create a new View
3692  * @param {Object} config The config object
3693  * 
3694  */
3695 Roo.View = function(config, depreciated_tpl, depreciated_config){
3696     
3697     this.parent = false;
3698     
3699     if (typeof(depreciated_tpl) == 'undefined') {
3700         // new way.. - universal constructor.
3701         Roo.apply(this, config);
3702         this.el  = Roo.get(this.el);
3703     } else {
3704         // old format..
3705         this.el  = Roo.get(config);
3706         this.tpl = depreciated_tpl;
3707         Roo.apply(this, depreciated_config);
3708     }
3709     this.wrapEl  = this.el.wrap().wrap();
3710     ///this.el = this.wrapEla.appendChild(document.createElement("div"));
3711     
3712     
3713     if(typeof(this.tpl) == "string"){
3714         this.tpl = new Roo.Template(this.tpl);
3715     } else {
3716         // support xtype ctors..
3717         this.tpl = new Roo.factory(this.tpl, Roo);
3718     }
3719     
3720     
3721     this.tpl.compile();
3722     
3723     /** @private */
3724     this.addEvents({
3725         /**
3726          * @event beforeclick
3727          * Fires before a click is processed. Returns false to cancel the default action.
3728          * @param {Roo.View} this
3729          * @param {Number} index The index of the target node
3730          * @param {HTMLElement} node The target node
3731          * @param {Roo.EventObject} e The raw event object
3732          */
3733             "beforeclick" : true,
3734         /**
3735          * @event click
3736          * Fires when a template node is clicked.
3737          * @param {Roo.View} this
3738          * @param {Number} index The index of the target node
3739          * @param {HTMLElement} node The target node
3740          * @param {Roo.EventObject} e The raw event object
3741          */
3742             "click" : true,
3743         /**
3744          * @event dblclick
3745          * Fires when a template node is double clicked.
3746          * @param {Roo.View} this
3747          * @param {Number} index The index of the target node
3748          * @param {HTMLElement} node The target node
3749          * @param {Roo.EventObject} e The raw event object
3750          */
3751             "dblclick" : true,
3752         /**
3753          * @event contextmenu
3754          * Fires when a template node is right clicked.
3755          * @param {Roo.View} this
3756          * @param {Number} index The index of the target node
3757          * @param {HTMLElement} node The target node
3758          * @param {Roo.EventObject} e The raw event object
3759          */
3760             "contextmenu" : true,
3761         /**
3762          * @event selectionchange
3763          * Fires when the selected nodes change.
3764          * @param {Roo.View} this
3765          * @param {Array} selections Array of the selected nodes
3766          */
3767             "selectionchange" : true,
3768     
3769         /**
3770          * @event beforeselect
3771          * Fires before a selection is made. If any handlers return false, the selection is cancelled.
3772          * @param {Roo.View} this
3773          * @param {HTMLElement} node The node to be selected
3774          * @param {Array} selections Array of currently selected nodes
3775          */
3776             "beforeselect" : true,
3777         /**
3778          * @event preparedata
3779          * Fires on every row to render, to allow you to change the data.
3780          * @param {Roo.View} this
3781          * @param {Object} data to be rendered (change this)
3782          */
3783           "preparedata" : true
3784           
3785           
3786         });
3787
3788
3789
3790     this.el.on({
3791         "click": this.onClick,
3792         "dblclick": this.onDblClick,
3793         "contextmenu": this.onContextMenu,
3794         scope:this
3795     });
3796
3797     this.selections = [];
3798     this.nodes = [];
3799     this.cmp = new Roo.CompositeElementLite([]);
3800     if(this.store){
3801         this.store = Roo.factory(this.store, Roo.data);
3802         this.setStore(this.store, true);
3803     }
3804     
3805     if ( this.footer && this.footer.xtype) {
3806            
3807          var fctr = this.wrapEl.appendChild(document.createElement("div"));
3808         
3809         this.footer.dataSource = this.store;
3810         this.footer.container = fctr;
3811         this.footer = Roo.factory(this.footer, Roo);
3812         fctr.insertFirst(this.el);
3813         
3814         // this is a bit insane - as the paging toolbar seems to detach the el..
3815 //        dom.parentNode.parentNode.parentNode
3816          // they get detached?
3817     }
3818     
3819     
3820     Roo.View.superclass.constructor.call(this);
3821     
3822     
3823 };
3824
3825 Roo.extend(Roo.View, Roo.util.Observable, {
3826     
3827      /**
3828      * @cfg {Roo.data.Store} store Data store to load data from.
3829      */
3830     store : false,
3831     
3832     /**
3833      * @cfg {String|Roo.Element} el The container element.
3834      */
3835     el : '',
3836     
3837     /**
3838      * @cfg {String|Roo.Template} tpl The template used by this View 
3839      */
3840     tpl : false,
3841     /**
3842      * @cfg {String} dataName the named area of the template to use as the data area
3843      *                          Works with domtemplates roo-name="name"
3844      */
3845     dataName: false,
3846     /**
3847      * @cfg {String} selectedClass The css class to add to selected nodes
3848      */
3849     selectedClass : "x-view-selected",
3850      /**
3851      * @cfg {String} emptyText The empty text to show when nothing is loaded.
3852      */
3853     emptyText : "",
3854     
3855     /**
3856      * @cfg {String} text to display on mask (default Loading)
3857      */
3858     mask : false,
3859     /**
3860      * @cfg {Boolean} multiSelect Allow multiple selection
3861      */
3862     multiSelect : false,
3863     /**
3864      * @cfg {Boolean} singleSelect Allow single selection
3865      */
3866     singleSelect:  false,
3867     
3868     /**
3869      * @cfg {Boolean} toggleSelect - selecting 
3870      */
3871     toggleSelect : false,
3872     
3873     /**
3874      * @cfg {Boolean} tickable - selecting 
3875      */
3876     tickable : false,
3877     
3878     /**
3879      * Returns the element this view is bound to.
3880      * @return {Roo.Element}
3881      */
3882     getEl : function(){
3883         return this.wrapEl;
3884     },
3885     
3886     
3887
3888     /**
3889      * Refreshes the view. - called by datachanged on the store. - do not call directly.
3890      */
3891     refresh : function(){
3892         //Roo.log('refresh');
3893         var t = this.tpl;
3894         
3895         // if we are using something like 'domtemplate', then
3896         // the what gets used is:
3897         // t.applySubtemplate(NAME, data, wrapping data..)
3898         // the outer template then get' applied with
3899         //     the store 'extra data'
3900         // and the body get's added to the
3901         //      roo-name="data" node?
3902         //      <span class='roo-tpl-{name}'></span> ?????
3903         
3904         
3905         
3906         this.clearSelections();
3907         this.el.update("");
3908         var html = [];
3909         var records = this.store.getRange();
3910         if(records.length < 1) {
3911             
3912             // is this valid??  = should it render a template??
3913             
3914             this.el.update(this.emptyText);
3915             return;
3916         }
3917         var el = this.el;
3918         if (this.dataName) {
3919             this.el.update(t.apply(this.store.meta)); //????
3920             el = this.el.child('.roo-tpl-' + this.dataName);
3921         }
3922         
3923         for(var i = 0, len = records.length; i < len; i++){
3924             var data = this.prepareData(records[i].data, i, records[i]);
3925             this.fireEvent("preparedata", this, data, i, records[i]);
3926             
3927             var d = Roo.apply({}, data);
3928             
3929             if(this.tickable){
3930                 Roo.apply(d, {'roo-id' : Roo.id()});
3931                 
3932                 var _this = this;
3933             
3934                 Roo.each(this.parent.item, function(item){
3935                     if(item[_this.parent.valueField] != data[_this.parent.valueField]){
3936                         return;
3937                     }
3938                     Roo.apply(d, {'roo-data-checked' : 'checked'});
3939                 });
3940             }
3941             
3942             html[html.length] = Roo.util.Format.trim(
3943                 this.dataName ?
3944                     t.applySubtemplate(this.dataName, d, this.store.meta) :
3945                     t.apply(d)
3946             );
3947         }
3948         
3949         
3950         
3951         el.update(html.join(""));
3952         this.nodes = el.dom.childNodes;
3953         this.updateIndexes(0);
3954     },
3955     
3956
3957     /**
3958      * Function to override to reformat the data that is sent to
3959      * the template for each node.
3960      * DEPRICATED - use the preparedata event handler.
3961      * @param {Array/Object} data The raw data (array of colData for a data model bound view or
3962      * a JSON object for an UpdateManager bound view).
3963      */
3964     prepareData : function(data, index, record)
3965     {
3966         this.fireEvent("preparedata", this, data, index, record);
3967         return data;
3968     },
3969
3970     onUpdate : function(ds, record){
3971         // Roo.log('on update');   
3972         this.clearSelections();
3973         var index = this.store.indexOf(record);
3974         var n = this.nodes[index];
3975         this.tpl.insertBefore(n, this.prepareData(record.data, index, record));
3976         n.parentNode.removeChild(n);
3977         this.updateIndexes(index, index);
3978     },
3979
3980     
3981     
3982 // --------- FIXME     
3983     onAdd : function(ds, records, index)
3984     {
3985         //Roo.log(['on Add', ds, records, index] );        
3986         this.clearSelections();
3987         if(this.nodes.length == 0){
3988             this.refresh();
3989             return;
3990         }
3991         var n = this.nodes[index];
3992         for(var i = 0, len = records.length; i < len; i++){
3993             var d = this.prepareData(records[i].data, i, records[i]);
3994             if(n){
3995                 this.tpl.insertBefore(n, d);
3996             }else{
3997                 
3998                 this.tpl.append(this.el, d);
3999             }
4000         }
4001         this.updateIndexes(index);
4002     },
4003
4004     onRemove : function(ds, record, index){
4005        // Roo.log('onRemove');
4006         this.clearSelections();
4007         var el = this.dataName  ?
4008             this.el.child('.roo-tpl-' + this.dataName) :
4009             this.el; 
4010         
4011         el.dom.removeChild(this.nodes[index]);
4012         this.updateIndexes(index);
4013     },
4014
4015     /**
4016      * Refresh an individual node.
4017      * @param {Number} index
4018      */
4019     refreshNode : function(index){
4020         this.onUpdate(this.store, this.store.getAt(index));
4021     },
4022
4023     updateIndexes : function(startIndex, endIndex){
4024         var ns = this.nodes;
4025         startIndex = startIndex || 0;
4026         endIndex = endIndex || ns.length - 1;
4027         for(var i = startIndex; i <= endIndex; i++){
4028             ns[i].nodeIndex = i;
4029         }
4030     },
4031
4032     /**
4033      * Changes the data store this view uses and refresh the view.
4034      * @param {Store} store
4035      */
4036     setStore : function(store, initial){
4037         if(!initial && this.store){
4038             this.store.un("datachanged", this.refresh);
4039             this.store.un("add", this.onAdd);
4040             this.store.un("remove", this.onRemove);
4041             this.store.un("update", this.onUpdate);
4042             this.store.un("clear", this.refresh);
4043             this.store.un("beforeload", this.onBeforeLoad);
4044             this.store.un("load", this.onLoad);
4045             this.store.un("loadexception", this.onLoad);
4046         }
4047         if(store){
4048           
4049             store.on("datachanged", this.refresh, this);
4050             store.on("add", this.onAdd, this);
4051             store.on("remove", this.onRemove, this);
4052             store.on("update", this.onUpdate, this);
4053             store.on("clear", this.refresh, this);
4054             store.on("beforeload", this.onBeforeLoad, this);
4055             store.on("load", this.onLoad, this);
4056             store.on("loadexception", this.onLoad, this);
4057         }
4058         
4059         if(store){
4060             this.refresh();
4061         }
4062     },
4063     /**
4064      * onbeforeLoad - masks the loading area.
4065      *
4066      */
4067     onBeforeLoad : function(store,opts)
4068     {
4069          //Roo.log('onBeforeLoad');   
4070         if (!opts.add) {
4071             this.el.update("");
4072         }
4073         this.el.mask(this.mask ? this.mask : "Loading" ); 
4074     },
4075     onLoad : function ()
4076     {
4077         this.el.unmask();
4078     },
4079     
4080
4081     /**
4082      * Returns the template node the passed child belongs to or null if it doesn't belong to one.
4083      * @param {HTMLElement} node
4084      * @return {HTMLElement} The template node
4085      */
4086     findItemFromChild : function(node){
4087         var el = this.dataName  ?
4088             this.el.child('.roo-tpl-' + this.dataName,true) :
4089             this.el.dom; 
4090         
4091         if(!node || node.parentNode == el){
4092                     return node;
4093             }
4094             var p = node.parentNode;
4095             while(p && p != el){
4096             if(p.parentNode == el){
4097                 return p;
4098             }
4099             p = p.parentNode;
4100         }
4101             return null;
4102     },
4103
4104     /** @ignore */
4105     onClick : function(e){
4106         var item = this.findItemFromChild(e.getTarget());
4107         if(item){
4108             var index = this.indexOf(item);
4109             if(this.onItemClick(item, index, e) !== false){
4110                 this.fireEvent("click", this, index, item, e);
4111             }
4112         }else{
4113             this.clearSelections();
4114         }
4115     },
4116
4117     /** @ignore */
4118     onContextMenu : function(e){
4119         var item = this.findItemFromChild(e.getTarget());
4120         if(item){
4121             this.fireEvent("contextmenu", this, this.indexOf(item), item, e);
4122         }
4123     },
4124
4125     /** @ignore */
4126     onDblClick : function(e){
4127         var item = this.findItemFromChild(e.getTarget());
4128         if(item){
4129             this.fireEvent("dblclick", this, this.indexOf(item), item, e);
4130         }
4131     },
4132
4133     onItemClick : function(item, index, e)
4134     {
4135         if(this.fireEvent("beforeclick", this, index, item, e) === false){
4136             return false;
4137         }
4138         if (this.toggleSelect) {
4139             var m = this.isSelected(item) ? 'unselect' : 'select';
4140             //Roo.log(m);
4141             var _t = this;
4142             _t[m](item, true, false);
4143             return true;
4144         }
4145         if(this.multiSelect || this.singleSelect){
4146             if(this.multiSelect && e.shiftKey && this.lastSelection){
4147                 this.select(this.getNodes(this.indexOf(this.lastSelection), index), false);
4148             }else{
4149                 this.select(item, this.multiSelect && e.ctrlKey);
4150                 this.lastSelection = item;
4151             }
4152             
4153             if(!this.tickable){
4154                 e.preventDefault();
4155             }
4156             
4157         }
4158         return true;
4159     },
4160
4161     /**
4162      * Get the number of selected nodes.
4163      * @return {Number}
4164      */
4165     getSelectionCount : function(){
4166         return this.selections.length;
4167     },
4168
4169     /**
4170      * Get the currently selected nodes.
4171      * @return {Array} An array of HTMLElements
4172      */
4173     getSelectedNodes : function(){
4174         return this.selections;
4175     },
4176
4177     /**
4178      * Get the indexes of the selected nodes.
4179      * @return {Array}
4180      */
4181     getSelectedIndexes : function(){
4182         var indexes = [], s = this.selections;
4183         for(var i = 0, len = s.length; i < len; i++){
4184             indexes.push(s[i].nodeIndex);
4185         }
4186         return indexes;
4187     },
4188
4189     /**
4190      * Clear all selections
4191      * @param {Boolean} suppressEvent (optional) true to skip firing of the selectionchange event
4192      */
4193     clearSelections : function(suppressEvent){
4194         if(this.nodes && (this.multiSelect || this.singleSelect) && this.selections.length > 0){
4195             this.cmp.elements = this.selections;
4196             this.cmp.removeClass(this.selectedClass);
4197             this.selections = [];
4198             if(!suppressEvent){
4199                 this.fireEvent("selectionchange", this, this.selections);
4200             }
4201         }
4202     },
4203
4204     /**
4205      * Returns true if the passed node is selected
4206      * @param {HTMLElement/Number} node The node or node index
4207      * @return {Boolean}
4208      */
4209     isSelected : function(node){
4210         var s = this.selections;
4211         if(s.length < 1){
4212             return false;
4213         }
4214         node = this.getNode(node);
4215         return s.indexOf(node) !== -1;
4216     },
4217
4218     /**
4219      * Selects nodes.
4220      * @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
4221      * @param {Boolean} keepExisting (optional) true to keep existing selections
4222      * @param {Boolean} suppressEvent (optional) true to skip firing of the selectionchange vent
4223      */
4224     select : function(nodeInfo, keepExisting, suppressEvent){
4225         if(nodeInfo instanceof Array){
4226             if(!keepExisting){
4227                 this.clearSelections(true);
4228             }
4229             for(var i = 0, len = nodeInfo.length; i < len; i++){
4230                 this.select(nodeInfo[i], true, true);
4231             }
4232             return;
4233         } 
4234         var node = this.getNode(nodeInfo);
4235         if(!node || this.isSelected(node)){
4236             return; // already selected.
4237         }
4238         if(!keepExisting){
4239             this.clearSelections(true);
4240         }
4241         
4242         if(this.fireEvent("beforeselect", this, node, this.selections) !== false){
4243             Roo.fly(node).addClass(this.selectedClass);
4244             this.selections.push(node);
4245             if(!suppressEvent){
4246                 this.fireEvent("selectionchange", this, this.selections);
4247             }
4248         }
4249         
4250         
4251     },
4252       /**
4253      * Unselects nodes.
4254      * @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
4255      * @param {Boolean} keepExisting (optional) true IGNORED (for campatibility with select)
4256      * @param {Boolean} suppressEvent (optional) true to skip firing of the selectionchange vent
4257      */
4258     unselect : function(nodeInfo, keepExisting, suppressEvent)
4259     {
4260         if(nodeInfo instanceof Array){
4261             Roo.each(this.selections, function(s) {
4262                 this.unselect(s, nodeInfo);
4263             }, this);
4264             return;
4265         }
4266         var node = this.getNode(nodeInfo);
4267         if(!node || !this.isSelected(node)){
4268             //Roo.log("not selected");
4269             return; // not selected.
4270         }
4271         // fireevent???
4272         var ns = [];
4273         Roo.each(this.selections, function(s) {
4274             if (s == node ) {
4275                 Roo.fly(node).removeClass(this.selectedClass);
4276
4277                 return;
4278             }
4279             ns.push(s);
4280         },this);
4281         
4282         this.selections= ns;
4283         this.fireEvent("selectionchange", this, this.selections);
4284     },
4285
4286     /**
4287      * Gets a template node.
4288      * @param {HTMLElement/String/Number} nodeInfo An HTMLElement template node, index of a template node or the id of a template node
4289      * @return {HTMLElement} The node or null if it wasn't found
4290      */
4291     getNode : function(nodeInfo){
4292         if(typeof nodeInfo == "string"){
4293             return document.getElementById(nodeInfo);
4294         }else if(typeof nodeInfo == "number"){
4295             return this.nodes[nodeInfo];
4296         }
4297         return nodeInfo;
4298     },
4299
4300     /**
4301      * Gets a range template nodes.
4302      * @param {Number} startIndex
4303      * @param {Number} endIndex
4304      * @return {Array} An array of nodes
4305      */
4306     getNodes : function(start, end){
4307         var ns = this.nodes;
4308         start = start || 0;
4309         end = typeof end == "undefined" ? ns.length - 1 : end;
4310         var nodes = [];
4311         if(start <= end){
4312             for(var i = start; i <= end; i++){
4313                 nodes.push(ns[i]);
4314             }
4315         } else{
4316             for(var i = start; i >= end; i--){
4317                 nodes.push(ns[i]);
4318             }
4319         }
4320         return nodes;
4321     },
4322
4323     /**
4324      * Finds the index of the passed node
4325      * @param {HTMLElement/String/Number} nodeInfo An HTMLElement template node, index of a template node or the id of a template node
4326      * @return {Number} The index of the node or -1
4327      */
4328     indexOf : function(node){
4329         node = this.getNode(node);
4330         if(typeof node.nodeIndex == "number"){
4331             return node.nodeIndex;
4332         }
4333         var ns = this.nodes;
4334         for(var i = 0, len = ns.length; i < len; i++){
4335             if(ns[i] == node){
4336                 return i;
4337             }
4338         }
4339         return -1;
4340     }
4341 });
4342 /*
4343  * Based on:
4344  * Ext JS Library 1.1.1
4345  * Copyright(c) 2006-2007, Ext JS, LLC.
4346  *
4347  * Originally Released Under LGPL - original licence link has changed is not relivant.
4348  *
4349  * Fork - LGPL
4350  * <script type="text/javascript">
4351  */
4352
4353 /**
4354  * @class Roo.JsonView
4355  * @extends Roo.View
4356  * Shortcut class to create a JSON + {@link Roo.UpdateManager} template view. Usage:
4357 <pre><code>
4358 var view = new Roo.JsonView({
4359     container: "my-element",
4360     tpl: '&lt;div id="{id}"&gt;{foo} - {bar}&lt;/div&gt;', // auto create template
4361     multiSelect: true, 
4362     jsonRoot: "data" 
4363 });
4364
4365 // listen for node click?
4366 view.on("click", function(vw, index, node, e){
4367     alert('Node "' + node.id + '" at index: ' + index + " was clicked.");
4368 });
4369
4370 // direct load of JSON data
4371 view.load("foobar.php");
4372
4373 // Example from my blog list
4374 var tpl = new Roo.Template(
4375     '&lt;div class="entry"&gt;' +
4376     '&lt;a class="entry-title" href="{link}"&gt;{title}&lt;/a&gt;' +
4377     "&lt;h4&gt;{date} by {author} | {comments} Comments&lt;/h4&gt;{description}" +
4378     "&lt;/div&gt;&lt;hr /&gt;"
4379 );
4380
4381 var moreView = new Roo.JsonView({
4382     container :  "entry-list", 
4383     template : tpl,
4384     jsonRoot: "posts"
4385 });
4386 moreView.on("beforerender", this.sortEntries, this);
4387 moreView.load({
4388     url: "/blog/get-posts.php",
4389     params: "allposts=true",
4390     text: "Loading Blog Entries..."
4391 });
4392 </code></pre>
4393
4394 * Note: old code is supported with arguments : (container, template, config)
4395
4396
4397  * @constructor
4398  * Create a new JsonView
4399  * 
4400  * @param {Object} config The config object
4401  * 
4402  */
4403 Roo.JsonView = function(config, depreciated_tpl, depreciated_config){
4404     
4405     
4406     Roo.JsonView.superclass.constructor.call(this, config, depreciated_tpl, depreciated_config);
4407
4408     var um = this.el.getUpdateManager();
4409     um.setRenderer(this);
4410     um.on("update", this.onLoad, this);
4411     um.on("failure", this.onLoadException, this);
4412
4413     /**
4414      * @event beforerender
4415      * Fires before rendering of the downloaded JSON data.
4416      * @param {Roo.JsonView} this
4417      * @param {Object} data The JSON data loaded
4418      */
4419     /**
4420      * @event load
4421      * Fires when data is loaded.
4422      * @param {Roo.JsonView} this
4423      * @param {Object} data The JSON data loaded
4424      * @param {Object} response The raw Connect response object
4425      */
4426     /**
4427      * @event loadexception
4428      * Fires when loading fails.
4429      * @param {Roo.JsonView} this
4430      * @param {Object} response The raw Connect response object
4431      */
4432     this.addEvents({
4433         'beforerender' : true,
4434         'load' : true,
4435         'loadexception' : true
4436     });
4437 };
4438 Roo.extend(Roo.JsonView, Roo.View, {
4439     /**
4440      * @type {String} The root property in the loaded JSON object that contains the data
4441      */
4442     jsonRoot : "",
4443
4444     /**
4445      * Refreshes the view.
4446      */
4447     refresh : function(){
4448         this.clearSelections();
4449         this.el.update("");
4450         var html = [];
4451         var o = this.jsonData;
4452         if(o && o.length > 0){
4453             for(var i = 0, len = o.length; i < len; i++){
4454                 var data = this.prepareData(o[i], i, o);
4455                 html[html.length] = this.tpl.apply(data);
4456             }
4457         }else{
4458             html.push(this.emptyText);
4459         }
4460         this.el.update(html.join(""));
4461         this.nodes = this.el.dom.childNodes;
4462         this.updateIndexes(0);
4463     },
4464
4465     /**
4466      * 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.
4467      * @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:
4468      <pre><code>
4469      view.load({
4470          url: "your-url.php",
4471          params: {param1: "foo", param2: "bar"}, // or a URL encoded string
4472          callback: yourFunction,
4473          scope: yourObject, //(optional scope)
4474          discardUrl: false,
4475          nocache: false,
4476          text: "Loading...",
4477          timeout: 30,
4478          scripts: false
4479      });
4480      </code></pre>
4481      * The only required property is <i>url</i>. The optional properties <i>nocache</i>, <i>text</i> and <i>scripts</i>
4482      * 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.
4483      * @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}
4484      * @param {Function} callback (optional) Callback when transaction is complete - called with signature (oElement, bSuccess)
4485      * @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.
4486      */
4487     load : function(){
4488         var um = this.el.getUpdateManager();
4489         um.update.apply(um, arguments);
4490     },
4491
4492     // note - render is a standard framework call...
4493     // using it for the response is really flaky... - it's called by UpdateManager normally, except when called by the XComponent/addXtype.
4494     render : function(el, response){
4495         
4496         this.clearSelections();
4497         this.el.update("");
4498         var o;
4499         try{
4500             if (response != '') {
4501                 o = Roo.util.JSON.decode(response.responseText);
4502                 if(this.jsonRoot){
4503                     
4504                     o = o[this.jsonRoot];
4505                 }
4506             }
4507         } catch(e){
4508         }
4509         /**
4510          * The current JSON data or null
4511          */
4512         this.jsonData = o;
4513         this.beforeRender();
4514         this.refresh();
4515     },
4516
4517 /**
4518  * Get the number of records in the current JSON dataset
4519  * @return {Number}
4520  */
4521     getCount : function(){
4522         return this.jsonData ? this.jsonData.length : 0;
4523     },
4524
4525 /**
4526  * Returns the JSON object for the specified node(s)
4527  * @param {HTMLElement/Array} node The node or an array of nodes
4528  * @return {Object/Array} If you pass in an array, you get an array back, otherwise
4529  * you get the JSON object for the node
4530  */
4531     getNodeData : function(node){
4532         if(node instanceof Array){
4533             var data = [];
4534             for(var i = 0, len = node.length; i < len; i++){
4535                 data.push(this.getNodeData(node[i]));
4536             }
4537             return data;
4538         }
4539         return this.jsonData[this.indexOf(node)] || null;
4540     },
4541
4542     beforeRender : function(){
4543         this.snapshot = this.jsonData;
4544         if(this.sortInfo){
4545             this.sort.apply(this, this.sortInfo);
4546         }
4547         this.fireEvent("beforerender", this, this.jsonData);
4548     },
4549
4550     onLoad : function(el, o){
4551         this.fireEvent("load", this, this.jsonData, o);
4552     },
4553
4554     onLoadException : function(el, o){
4555         this.fireEvent("loadexception", this, o);
4556     },
4557
4558 /**
4559  * Filter the data by a specific property.
4560  * @param {String} property A property on your JSON objects
4561  * @param {String/RegExp} value Either string that the property values
4562  * should start with, or a RegExp to test against the property
4563  */
4564     filter : function(property, value){
4565         if(this.jsonData){
4566             var data = [];
4567             var ss = this.snapshot;
4568             if(typeof value == "string"){
4569                 var vlen = value.length;
4570                 if(vlen == 0){
4571                     this.clearFilter();
4572                     return;
4573                 }
4574                 value = value.toLowerCase();
4575                 for(var i = 0, len = ss.length; i < len; i++){
4576                     var o = ss[i];
4577                     if(o[property].substr(0, vlen).toLowerCase() == value){
4578                         data.push(o);
4579                     }
4580                 }
4581             } else if(value.exec){ // regex?
4582                 for(var i = 0, len = ss.length; i < len; i++){
4583                     var o = ss[i];
4584                     if(value.test(o[property])){
4585                         data.push(o);
4586                     }
4587                 }
4588             } else{
4589                 return;
4590             }
4591             this.jsonData = data;
4592             this.refresh();
4593         }
4594     },
4595
4596 /**
4597  * Filter by a function. The passed function will be called with each
4598  * object in the current dataset. If the function returns true the value is kept,
4599  * otherwise it is filtered.
4600  * @param {Function} fn
4601  * @param {Object} scope (optional) The scope of the function (defaults to this JsonView)
4602  */
4603     filterBy : function(fn, scope){
4604         if(this.jsonData){
4605             var data = [];
4606             var ss = this.snapshot;
4607             for(var i = 0, len = ss.length; i < len; i++){
4608                 var o = ss[i];
4609                 if(fn.call(scope || this, o)){
4610                     data.push(o);
4611                 }
4612             }
4613             this.jsonData = data;
4614             this.refresh();
4615         }
4616     },
4617
4618 /**
4619  * Clears the current filter.
4620  */
4621     clearFilter : function(){
4622         if(this.snapshot && this.jsonData != this.snapshot){
4623             this.jsonData = this.snapshot;
4624             this.refresh();
4625         }
4626     },
4627
4628
4629 /**
4630  * Sorts the data for this view and refreshes it.
4631  * @param {String} property A property on your JSON objects to sort on
4632  * @param {String} direction (optional) "desc" or "asc" (defaults to "asc")
4633  * @param {Function} sortType (optional) A function to call to convert the data to a sortable value.
4634  */
4635     sort : function(property, dir, sortType){
4636         this.sortInfo = Array.prototype.slice.call(arguments, 0);
4637         if(this.jsonData){
4638             var p = property;
4639             var dsc = dir && dir.toLowerCase() == "desc";
4640             var f = function(o1, o2){
4641                 var v1 = sortType ? sortType(o1[p]) : o1[p];
4642                 var v2 = sortType ? sortType(o2[p]) : o2[p];
4643                 ;
4644                 if(v1 < v2){
4645                     return dsc ? +1 : -1;
4646                 } else if(v1 > v2){
4647                     return dsc ? -1 : +1;
4648                 } else{
4649                     return 0;
4650                 }
4651             };
4652             this.jsonData.sort(f);
4653             this.refresh();
4654             if(this.jsonData != this.snapshot){
4655                 this.snapshot.sort(f);
4656             }
4657         }
4658     }
4659 });/*
4660  * Based on:
4661  * Ext JS Library 1.1.1
4662  * Copyright(c) 2006-2007, Ext JS, LLC.
4663  *
4664  * Originally Released Under LGPL - original licence link has changed is not relivant.
4665  *
4666  * Fork - LGPL
4667  * <script type="text/javascript">
4668  */
4669  
4670
4671 /**
4672  * @class Roo.ColorPalette
4673  * @extends Roo.Component
4674  * Simple color palette class for choosing colors.  The palette can be rendered to any container.<br />
4675  * Here's an example of typical usage:
4676  * <pre><code>
4677 var cp = new Roo.ColorPalette({value:'993300'});  // initial selected color
4678 cp.render('my-div');
4679
4680 cp.on('select', function(palette, selColor){
4681     // do something with selColor
4682 });
4683 </code></pre>
4684  * @constructor
4685  * Create a new ColorPalette
4686  * @param {Object} config The config object
4687  */
4688 Roo.ColorPalette = function(config){
4689     Roo.ColorPalette.superclass.constructor.call(this, config);
4690     this.addEvents({
4691         /**
4692              * @event select
4693              * Fires when a color is selected
4694              * @param {ColorPalette} this
4695              * @param {String} color The 6-digit color hex code (without the # symbol)
4696              */
4697         select: true
4698     });
4699
4700     if(this.handler){
4701         this.on("select", this.handler, this.scope, true);
4702     }
4703 };
4704 Roo.extend(Roo.ColorPalette, Roo.Component, {
4705     /**
4706      * @cfg {String} itemCls
4707      * The CSS class to apply to the containing element (defaults to "x-color-palette")
4708      */
4709     itemCls : "x-color-palette",
4710     /**
4711      * @cfg {String} value
4712      * The initial color to highlight (should be a valid 6-digit color hex code without the # symbol).  Note that
4713      * the hex codes are case-sensitive.
4714      */
4715     value : null,
4716     clickEvent:'click',
4717     // private
4718     ctype: "Roo.ColorPalette",
4719
4720     /**
4721      * @cfg {Boolean} allowReselect If set to true then reselecting a color that is already selected fires the selection event
4722      */
4723     allowReselect : false,
4724
4725     /**
4726      * <p>An array of 6-digit color hex code strings (without the # symbol).  This array can contain any number
4727      * of colors, and each hex code should be unique.  The width of the palette is controlled via CSS by adjusting
4728      * the width property of the 'x-color-palette' class (or assigning a custom class), so you can balance the number
4729      * of colors with the width setting until the box is symmetrical.</p>
4730      * <p>You can override individual colors if needed:</p>
4731      * <pre><code>
4732 var cp = new Roo.ColorPalette();
4733 cp.colors[0] = "FF0000";  // change the first box to red
4734 </code></pre>
4735
4736 Or you can provide a custom array of your own for complete control:
4737 <pre><code>
4738 var cp = new Roo.ColorPalette();
4739 cp.colors = ["000000", "993300", "333300"];
4740 </code></pre>
4741      * @type Array
4742      */
4743     colors : [
4744         "000000", "993300", "333300", "003300", "003366", "000080", "333399", "333333",
4745         "800000", "FF6600", "808000", "008000", "008080", "0000FF", "666699", "808080",
4746         "FF0000", "FF9900", "99CC00", "339966", "33CCCC", "3366FF", "800080", "969696",
4747         "FF00FF", "FFCC00", "FFFF00", "00FF00", "00FFFF", "00CCFF", "993366", "C0C0C0",
4748         "FF99CC", "FFCC99", "FFFF99", "CCFFCC", "CCFFFF", "99CCFF", "CC99FF", "FFFFFF"
4749     ],
4750
4751     // private
4752     onRender : function(container, position){
4753         var t = new Roo.MasterTemplate(
4754             '<tpl><a href="#" class="color-{0}" hidefocus="on"><em><span style="background:#{0}" unselectable="on">&#160;</span></em></a></tpl>'
4755         );
4756         var c = this.colors;
4757         for(var i = 0, len = c.length; i < len; i++){
4758             t.add([c[i]]);
4759         }
4760         var el = document.createElement("div");
4761         el.className = this.itemCls;
4762         t.overwrite(el);
4763         container.dom.insertBefore(el, position);
4764         this.el = Roo.get(el);
4765         this.el.on(this.clickEvent, this.handleClick,  this, {delegate: "a"});
4766         if(this.clickEvent != 'click'){
4767             this.el.on('click', Roo.emptyFn,  this, {delegate: "a", preventDefault:true});
4768         }
4769     },
4770
4771     // private
4772     afterRender : function(){
4773         Roo.ColorPalette.superclass.afterRender.call(this);
4774         if(this.value){
4775             var s = this.value;
4776             this.value = null;
4777             this.select(s);
4778         }
4779     },
4780
4781     // private
4782     handleClick : function(e, t){
4783         e.preventDefault();
4784         if(!this.disabled){
4785             var c = t.className.match(/(?:^|\s)color-(.{6})(?:\s|$)/)[1];
4786             this.select(c.toUpperCase());
4787         }
4788     },
4789
4790     /**
4791      * Selects the specified color in the palette (fires the select event)
4792      * @param {String} color A valid 6-digit color hex code (# will be stripped if included)
4793      */
4794     select : function(color){
4795         color = color.replace("#", "");
4796         if(color != this.value || this.allowReselect){
4797             var el = this.el;
4798             if(this.value){
4799                 el.child("a.color-"+this.value).removeClass("x-color-palette-sel");
4800             }
4801             el.child("a.color-"+color).addClass("x-color-palette-sel");
4802             this.value = color;
4803             this.fireEvent("select", this, color);
4804         }
4805     }
4806 });/*
4807  * Based on:
4808  * Ext JS Library 1.1.1
4809  * Copyright(c) 2006-2007, Ext JS, LLC.
4810  *
4811  * Originally Released Under LGPL - original licence link has changed is not relivant.
4812  *
4813  * Fork - LGPL
4814  * <script type="text/javascript">
4815  */
4816  
4817 /**
4818  * @class Roo.DatePicker
4819  * @extends Roo.Component
4820  * Simple date picker class.
4821  * @constructor
4822  * Create a new DatePicker
4823  * @param {Object} config The config object
4824  */
4825 Roo.DatePicker = function(config){
4826     Roo.DatePicker.superclass.constructor.call(this, config);
4827
4828     this.value = config && config.value ?
4829                  config.value.clearTime() : new Date().clearTime();
4830
4831     this.addEvents({
4832         /**
4833              * @event select
4834              * Fires when a date is selected
4835              * @param {DatePicker} this
4836              * @param {Date} date The selected date
4837              */
4838         'select': true,
4839         /**
4840              * @event monthchange
4841              * Fires when the displayed month changes 
4842              * @param {DatePicker} this
4843              * @param {Date} date The selected month
4844              */
4845         'monthchange': true
4846     });
4847
4848     if(this.handler){
4849         this.on("select", this.handler,  this.scope || this);
4850     }
4851     // build the disabledDatesRE
4852     if(!this.disabledDatesRE && this.disabledDates){
4853         var dd = this.disabledDates;
4854         var re = "(?:";
4855         for(var i = 0; i < dd.length; i++){
4856             re += dd[i];
4857             if(i != dd.length-1) {
4858                 re += "|";
4859             }
4860         }
4861         this.disabledDatesRE = new RegExp(re + ")");
4862     }
4863 };
4864
4865 Roo.extend(Roo.DatePicker, Roo.Component, {
4866     /**
4867      * @cfg {String} todayText
4868      * The text to display on the button that selects the current date (defaults to "Today")
4869      */
4870     todayText : "Today",
4871     /**
4872      * @cfg {String} okText
4873      * The text to display on the ok button
4874      */
4875     okText : "&#160;OK&#160;", // &#160; to give the user extra clicking room
4876     /**
4877      * @cfg {String} cancelText
4878      * The text to display on the cancel button
4879      */
4880     cancelText : "Cancel",
4881     /**
4882      * @cfg {String} todayTip
4883      * The tooltip to display for the button that selects the current date (defaults to "{current date} (Spacebar)")
4884      */
4885     todayTip : "{0} (Spacebar)",
4886     /**
4887      * @cfg {Date} minDate
4888      * Minimum allowable date (JavaScript date object, defaults to null)
4889      */
4890     minDate : null,
4891     /**
4892      * @cfg {Date} maxDate
4893      * Maximum allowable date (JavaScript date object, defaults to null)
4894      */
4895     maxDate : null,
4896     /**
4897      * @cfg {String} minText
4898      * The error text to display if the minDate validation fails (defaults to "This date is before the minimum date")
4899      */
4900     minText : "This date is before the minimum date",
4901     /**
4902      * @cfg {String} maxText
4903      * The error text to display if the maxDate validation fails (defaults to "This date is after the maximum date")
4904      */
4905     maxText : "This date is after the maximum date",
4906     /**
4907      * @cfg {String} format
4908      * The default date format string which can be overriden for localization support.  The format must be
4909      * valid according to {@link Date#parseDate} (defaults to 'm/d/y').
4910      */
4911     format : "m/d/y",
4912     /**
4913      * @cfg {Array} disabledDays
4914      * An array of days to disable, 0-based. For example, [0, 6] disables Sunday and Saturday (defaults to null).
4915      */
4916     disabledDays : null,
4917     /**
4918      * @cfg {String} disabledDaysText
4919      * The tooltip to display when the date falls on a disabled day (defaults to "")
4920      */
4921     disabledDaysText : "",
4922     /**
4923      * @cfg {RegExp} disabledDatesRE
4924      * JavaScript regular expression used to disable a pattern of dates (defaults to null)
4925      */
4926     disabledDatesRE : null,
4927     /**
4928      * @cfg {String} disabledDatesText
4929      * The tooltip text to display when the date falls on a disabled date (defaults to "")
4930      */
4931     disabledDatesText : "",
4932     /**
4933      * @cfg {Boolean} constrainToViewport
4934      * True to constrain the date picker to the viewport (defaults to true)
4935      */
4936     constrainToViewport : true,
4937     /**
4938      * @cfg {Array} monthNames
4939      * An array of textual month names which can be overriden for localization support (defaults to Date.monthNames)
4940      */
4941     monthNames : Date.monthNames,
4942     /**
4943      * @cfg {Array} dayNames
4944      * An array of textual day names which can be overriden for localization support (defaults to Date.dayNames)
4945      */
4946     dayNames : Date.dayNames,
4947     /**
4948      * @cfg {String} nextText
4949      * The next month navigation button tooltip (defaults to 'Next Month (Control+Right)')
4950      */
4951     nextText: 'Next Month (Control+Right)',
4952     /**
4953      * @cfg {String} prevText
4954      * The previous month navigation button tooltip (defaults to 'Previous Month (Control+Left)')
4955      */
4956     prevText: 'Previous Month (Control+Left)',
4957     /**
4958      * @cfg {String} monthYearText
4959      * The header month selector tooltip (defaults to 'Choose a month (Control+Up/Down to move years)')
4960      */
4961     monthYearText: 'Choose a month (Control+Up/Down to move years)',
4962     /**
4963      * @cfg {Number} startDay
4964      * Day index at which the week should begin, 0-based (defaults to 0, which is Sunday)
4965      */
4966     startDay : 0,
4967     /**
4968      * @cfg {Bool} showClear
4969      * Show a clear button (usefull for date form elements that can be blank.)
4970      */
4971     
4972     showClear: false,
4973     
4974     /**
4975      * Sets the value of the date field
4976      * @param {Date} value The date to set
4977      */
4978     setValue : function(value){
4979         var old = this.value;
4980         
4981         if (typeof(value) == 'string') {
4982          
4983             value = Date.parseDate(value, this.format);
4984         }
4985         if (!value) {
4986             value = new Date();
4987         }
4988         
4989         this.value = value.clearTime(true);
4990         if(this.el){
4991             this.update(this.value);
4992         }
4993     },
4994
4995     /**
4996      * Gets the current selected value of the date field
4997      * @return {Date} The selected date
4998      */
4999     getValue : function(){
5000         return this.value;
5001     },
5002
5003     // private
5004     focus : function(){
5005         if(this.el){
5006             this.update(this.activeDate);
5007         }
5008     },
5009
5010     // privateval
5011     onRender : function(container, position){
5012         
5013         var m = [
5014              '<table cellspacing="0">',
5015                 '<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>',
5016                 '<tr><td colspan="3"><table class="x-date-inner" cellspacing="0"><thead><tr>'];
5017         var dn = this.dayNames;
5018         for(var i = 0; i < 7; i++){
5019             var d = this.startDay+i;
5020             if(d > 6){
5021                 d = d-7;
5022             }
5023             m.push("<th><span>", dn[d].substr(0,1), "</span></th>");
5024         }
5025         m[m.length] = "</tr></thead><tbody><tr>";
5026         for(var i = 0; i < 42; i++) {
5027             if(i % 7 == 0 && i != 0){
5028                 m[m.length] = "</tr><tr>";
5029             }
5030             m[m.length] = '<td><a href="#" hidefocus="on" class="x-date-date" tabIndex="1"><em><span></span></em></a></td>';
5031         }
5032         m[m.length] = '</tr></tbody></table></td></tr><tr>'+
5033             '<td colspan="3" class="x-date-bottom" align="center"></td></tr></table><div class="x-date-mp"></div>';
5034
5035         var el = document.createElement("div");
5036         el.className = "x-date-picker";
5037         el.innerHTML = m.join("");
5038
5039         container.dom.insertBefore(el, position);
5040
5041         this.el = Roo.get(el);
5042         this.eventEl = Roo.get(el.firstChild);
5043
5044         new Roo.util.ClickRepeater(this.el.child("td.x-date-left a"), {
5045             handler: this.showPrevMonth,
5046             scope: this,
5047             preventDefault:true,
5048             stopDefault:true
5049         });
5050
5051         new Roo.util.ClickRepeater(this.el.child("td.x-date-right a"), {
5052             handler: this.showNextMonth,
5053             scope: this,
5054             preventDefault:true,
5055             stopDefault:true
5056         });
5057
5058         this.eventEl.on("mousewheel", this.handleMouseWheel,  this);
5059
5060         this.monthPicker = this.el.down('div.x-date-mp');
5061         this.monthPicker.enableDisplayMode('block');
5062         
5063         var kn = new Roo.KeyNav(this.eventEl, {
5064             "left" : function(e){
5065                 e.ctrlKey ?
5066                     this.showPrevMonth() :
5067                     this.update(this.activeDate.add("d", -1));
5068             },
5069
5070             "right" : function(e){
5071                 e.ctrlKey ?
5072                     this.showNextMonth() :
5073                     this.update(this.activeDate.add("d", 1));
5074             },
5075
5076             "up" : function(e){
5077                 e.ctrlKey ?
5078                     this.showNextYear() :
5079                     this.update(this.activeDate.add("d", -7));
5080             },
5081
5082             "down" : function(e){
5083                 e.ctrlKey ?
5084                     this.showPrevYear() :
5085                     this.update(this.activeDate.add("d", 7));
5086             },
5087
5088             "pageUp" : function(e){
5089                 this.showNextMonth();
5090             },
5091
5092             "pageDown" : function(e){
5093                 this.showPrevMonth();
5094             },
5095
5096             "enter" : function(e){
5097                 e.stopPropagation();
5098                 return true;
5099             },
5100
5101             scope : this
5102         });
5103
5104         this.eventEl.on("click", this.handleDateClick,  this, {delegate: "a.x-date-date"});
5105
5106         this.eventEl.addKeyListener(Roo.EventObject.SPACE, this.selectToday,  this);
5107
5108         this.el.unselectable();
5109         
5110         this.cells = this.el.select("table.x-date-inner tbody td");
5111         this.textNodes = this.el.query("table.x-date-inner tbody span");
5112
5113         this.mbtn = new Roo.Button(this.el.child("td.x-date-middle", true), {
5114             text: "&#160;",
5115             tooltip: this.monthYearText
5116         });
5117
5118         this.mbtn.on('click', this.showMonthPicker, this);
5119         this.mbtn.el.child(this.mbtn.menuClassTarget).addClass("x-btn-with-menu");
5120
5121
5122         var today = (new Date()).dateFormat(this.format);
5123         
5124         var baseTb = new Roo.Toolbar(this.el.child("td.x-date-bottom", true));
5125         if (this.showClear) {
5126             baseTb.add( new Roo.Toolbar.Fill());
5127         }
5128         baseTb.add({
5129             text: String.format(this.todayText, today),
5130             tooltip: String.format(this.todayTip, today),
5131             handler: this.selectToday,
5132             scope: this
5133         });
5134         
5135         //var todayBtn = new Roo.Button(this.el.child("td.x-date-bottom", true), {
5136             
5137         //});
5138         if (this.showClear) {
5139             
5140             baseTb.add( new Roo.Toolbar.Fill());
5141             baseTb.add({
5142                 text: '&#160;',
5143                 cls: 'x-btn-icon x-btn-clear',
5144                 handler: function() {
5145                     //this.value = '';
5146                     this.fireEvent("select", this, '');
5147                 },
5148                 scope: this
5149             });
5150         }
5151         
5152         
5153         if(Roo.isIE){
5154             this.el.repaint();
5155         }
5156         this.update(this.value);
5157     },
5158
5159     createMonthPicker : function(){
5160         if(!this.monthPicker.dom.firstChild){
5161             var buf = ['<table border="0" cellspacing="0">'];
5162             for(var i = 0; i < 6; i++){
5163                 buf.push(
5164                     '<tr><td class="x-date-mp-month"><a href="#">', this.monthNames[i].substr(0, 3), '</a></td>',
5165                     '<td class="x-date-mp-month x-date-mp-sep"><a href="#">', this.monthNames[i+6].substr(0, 3), '</a></td>',
5166                     i == 0 ?
5167                     '<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>' :
5168                     '<td class="x-date-mp-year"><a href="#"></a></td><td class="x-date-mp-year"><a href="#"></a></td></tr>'
5169                 );
5170             }
5171             buf.push(
5172                 '<tr class="x-date-mp-btns"><td colspan="4"><button type="button" class="x-date-mp-ok">',
5173                     this.okText,
5174                     '</button><button type="button" class="x-date-mp-cancel">',
5175                     this.cancelText,
5176                     '</button></td></tr>',
5177                 '</table>'
5178             );
5179             this.monthPicker.update(buf.join(''));
5180             this.monthPicker.on('click', this.onMonthClick, this);
5181             this.monthPicker.on('dblclick', this.onMonthDblClick, this);
5182
5183             this.mpMonths = this.monthPicker.select('td.x-date-mp-month');
5184             this.mpYears = this.monthPicker.select('td.x-date-mp-year');
5185
5186             this.mpMonths.each(function(m, a, i){
5187                 i += 1;
5188                 if((i%2) == 0){
5189                     m.dom.xmonth = 5 + Math.round(i * .5);
5190                 }else{
5191                     m.dom.xmonth = Math.round((i-1) * .5);
5192                 }
5193             });
5194         }
5195     },
5196
5197     showMonthPicker : function(){
5198         this.createMonthPicker();
5199         var size = this.el.getSize();
5200         this.monthPicker.setSize(size);
5201         this.monthPicker.child('table').setSize(size);
5202
5203         this.mpSelMonth = (this.activeDate || this.value).getMonth();
5204         this.updateMPMonth(this.mpSelMonth);
5205         this.mpSelYear = (this.activeDate || this.value).getFullYear();
5206         this.updateMPYear(this.mpSelYear);
5207
5208         this.monthPicker.slideIn('t', {duration:.2});
5209     },
5210
5211     updateMPYear : function(y){
5212         this.mpyear = y;
5213         var ys = this.mpYears.elements;
5214         for(var i = 1; i <= 10; i++){
5215             var td = ys[i-1], y2;
5216             if((i%2) == 0){
5217                 y2 = y + Math.round(i * .5);
5218                 td.firstChild.innerHTML = y2;
5219                 td.xyear = y2;
5220             }else{
5221                 y2 = y - (5-Math.round(i * .5));
5222                 td.firstChild.innerHTML = y2;
5223                 td.xyear = y2;
5224             }
5225             this.mpYears.item(i-1)[y2 == this.mpSelYear ? 'addClass' : 'removeClass']('x-date-mp-sel');
5226         }
5227     },
5228
5229     updateMPMonth : function(sm){
5230         this.mpMonths.each(function(m, a, i){
5231             m[m.dom.xmonth == sm ? 'addClass' : 'removeClass']('x-date-mp-sel');
5232         });
5233     },
5234
5235     selectMPMonth: function(m){
5236         
5237     },
5238
5239     onMonthClick : function(e, t){
5240         e.stopEvent();
5241         var el = new Roo.Element(t), pn;
5242         if(el.is('button.x-date-mp-cancel')){
5243             this.hideMonthPicker();
5244         }
5245         else if(el.is('button.x-date-mp-ok')){
5246             this.update(new Date(this.mpSelYear, this.mpSelMonth, (this.activeDate || this.value).getDate()));
5247             this.hideMonthPicker();
5248         }
5249         else if(pn = el.up('td.x-date-mp-month', 2)){
5250             this.mpMonths.removeClass('x-date-mp-sel');
5251             pn.addClass('x-date-mp-sel');
5252             this.mpSelMonth = pn.dom.xmonth;
5253         }
5254         else if(pn = el.up('td.x-date-mp-year', 2)){
5255             this.mpYears.removeClass('x-date-mp-sel');
5256             pn.addClass('x-date-mp-sel');
5257             this.mpSelYear = pn.dom.xyear;
5258         }
5259         else if(el.is('a.x-date-mp-prev')){
5260             this.updateMPYear(this.mpyear-10);
5261         }
5262         else if(el.is('a.x-date-mp-next')){
5263             this.updateMPYear(this.mpyear+10);
5264         }
5265     },
5266
5267     onMonthDblClick : function(e, t){
5268         e.stopEvent();
5269         var el = new Roo.Element(t), pn;
5270         if(pn = el.up('td.x-date-mp-month', 2)){
5271             this.update(new Date(this.mpSelYear, pn.dom.xmonth, (this.activeDate || this.value).getDate()));
5272             this.hideMonthPicker();
5273         }
5274         else if(pn = el.up('td.x-date-mp-year', 2)){
5275             this.update(new Date(pn.dom.xyear, this.mpSelMonth, (this.activeDate || this.value).getDate()));
5276             this.hideMonthPicker();
5277         }
5278     },
5279
5280     hideMonthPicker : function(disableAnim){
5281         if(this.monthPicker){
5282             if(disableAnim === true){
5283                 this.monthPicker.hide();
5284             }else{
5285                 this.monthPicker.slideOut('t', {duration:.2});
5286             }
5287         }
5288     },
5289
5290     // private
5291     showPrevMonth : function(e){
5292         this.update(this.activeDate.add("mo", -1));
5293     },
5294
5295     // private
5296     showNextMonth : function(e){
5297         this.update(this.activeDate.add("mo", 1));
5298     },
5299
5300     // private
5301     showPrevYear : function(){
5302         this.update(this.activeDate.add("y", -1));
5303     },
5304
5305     // private
5306     showNextYear : function(){
5307         this.update(this.activeDate.add("y", 1));
5308     },
5309
5310     // private
5311     handleMouseWheel : function(e){
5312         var delta = e.getWheelDelta();
5313         if(delta > 0){
5314             this.showPrevMonth();
5315             e.stopEvent();
5316         } else if(delta < 0){
5317             this.showNextMonth();
5318             e.stopEvent();
5319         }
5320     },
5321
5322     // private
5323     handleDateClick : function(e, t){
5324         e.stopEvent();
5325         if(t.dateValue && !Roo.fly(t.parentNode).hasClass("x-date-disabled")){
5326             this.setValue(new Date(t.dateValue));
5327             this.fireEvent("select", this, this.value);
5328         }
5329     },
5330
5331     // private
5332     selectToday : function(){
5333         this.setValue(new Date().clearTime());
5334         this.fireEvent("select", this, this.value);
5335     },
5336
5337     // private
5338     update : function(date)
5339     {
5340         var vd = this.activeDate;
5341         this.activeDate = date;
5342         if(vd && this.el){
5343             var t = date.getTime();
5344             if(vd.getMonth() == date.getMonth() && vd.getFullYear() == date.getFullYear()){
5345                 this.cells.removeClass("x-date-selected");
5346                 this.cells.each(function(c){
5347                    if(c.dom.firstChild.dateValue == t){
5348                        c.addClass("x-date-selected");
5349                        setTimeout(function(){
5350                             try{c.dom.firstChild.focus();}catch(e){}
5351                        }, 50);
5352                        return false;
5353                    }
5354                 });
5355                 return;
5356             }
5357         }
5358         
5359         var days = date.getDaysInMonth();
5360         var firstOfMonth = date.getFirstDateOfMonth();
5361         var startingPos = firstOfMonth.getDay()-this.startDay;
5362
5363         if(startingPos <= this.startDay){
5364             startingPos += 7;
5365         }
5366
5367         var pm = date.add("mo", -1);
5368         var prevStart = pm.getDaysInMonth()-startingPos;
5369
5370         var cells = this.cells.elements;
5371         var textEls = this.textNodes;
5372         days += startingPos;
5373
5374         // convert everything to numbers so it's fast
5375         var day = 86400000;
5376         var d = (new Date(pm.getFullYear(), pm.getMonth(), prevStart)).clearTime();
5377         var today = new Date().clearTime().getTime();
5378         var sel = date.clearTime().getTime();
5379         var min = this.minDate ? this.minDate.clearTime() : Number.NEGATIVE_INFINITY;
5380         var max = this.maxDate ? this.maxDate.clearTime() : Number.POSITIVE_INFINITY;
5381         var ddMatch = this.disabledDatesRE;
5382         var ddText = this.disabledDatesText;
5383         var ddays = this.disabledDays ? this.disabledDays.join("") : false;
5384         var ddaysText = this.disabledDaysText;
5385         var format = this.format;
5386
5387         var setCellClass = function(cal, cell){
5388             cell.title = "";
5389             var t = d.getTime();
5390             cell.firstChild.dateValue = t;
5391             if(t == today){
5392                 cell.className += " x-date-today";
5393                 cell.title = cal.todayText;
5394             }
5395             if(t == sel){
5396                 cell.className += " x-date-selected";
5397                 setTimeout(function(){
5398                     try{cell.firstChild.focus();}catch(e){}
5399                 }, 50);
5400             }
5401             // disabling
5402             if(t < min) {
5403                 cell.className = " x-date-disabled";
5404                 cell.title = cal.minText;
5405                 return;
5406             }
5407             if(t > max) {
5408                 cell.className = " x-date-disabled";
5409                 cell.title = cal.maxText;
5410                 return;
5411             }
5412             if(ddays){
5413                 if(ddays.indexOf(d.getDay()) != -1){
5414                     cell.title = ddaysText;
5415                     cell.className = " x-date-disabled";
5416                 }
5417             }
5418             if(ddMatch && format){
5419                 var fvalue = d.dateFormat(format);
5420                 if(ddMatch.test(fvalue)){
5421                     cell.title = ddText.replace("%0", fvalue);
5422                     cell.className = " x-date-disabled";
5423                 }
5424             }
5425         };
5426
5427         var i = 0;
5428         for(; i < startingPos; i++) {
5429             textEls[i].innerHTML = (++prevStart);
5430             d.setDate(d.getDate()+1);
5431             cells[i].className = "x-date-prevday";
5432             setCellClass(this, cells[i]);
5433         }
5434         for(; i < days; i++){
5435             intDay = i - startingPos + 1;
5436             textEls[i].innerHTML = (intDay);
5437             d.setDate(d.getDate()+1);
5438             cells[i].className = "x-date-active";
5439             setCellClass(this, cells[i]);
5440         }
5441         var extraDays = 0;
5442         for(; i < 42; i++) {
5443              textEls[i].innerHTML = (++extraDays);
5444              d.setDate(d.getDate()+1);
5445              cells[i].className = "x-date-nextday";
5446              setCellClass(this, cells[i]);
5447         }
5448
5449         this.mbtn.setText(this.monthNames[date.getMonth()] + " " + date.getFullYear());
5450         this.fireEvent('monthchange', this, date);
5451         
5452         if(!this.internalRender){
5453             var main = this.el.dom.firstChild;
5454             var w = main.offsetWidth;
5455             this.el.setWidth(w + this.el.getBorderWidth("lr"));
5456             Roo.fly(main).setWidth(w);
5457             this.internalRender = true;
5458             // opera does not respect the auto grow header center column
5459             // then, after it gets a width opera refuses to recalculate
5460             // without a second pass
5461             if(Roo.isOpera && !this.secondPass){
5462                 main.rows[0].cells[1].style.width = (w - (main.rows[0].cells[0].offsetWidth+main.rows[0].cells[2].offsetWidth)) + "px";
5463                 this.secondPass = true;
5464                 this.update.defer(10, this, [date]);
5465             }
5466         }
5467         
5468         
5469     }
5470 });Roo.panel = {};
5471 /*
5472 * Licence: LGPL
5473 */
5474
5475 /**
5476  * @class Roo.panel.Cropbox
5477  * @extends Roo.BoxComponent
5478  * Panel Cropbox class
5479  * @cfg {String} emptyText show when image has been loaded
5480  * @cfg {String} rotateNotify show when image too small to rotate
5481  * @cfg {Number} errorTimeout default 3000
5482  * @cfg {Number} minWidth default 300
5483  * @cfg {Number} minHeight default 300
5484  * @cfg {Number} outputMaxWidth default 1200
5485  * @cfg {Number} windowSize default 300
5486  * @cfg {Array} buttons default ['rotateLeft', 'pictureBtn', 'rotateRight']
5487  * @cfg {Boolean} isDocument (true|false) default false
5488  * @cfg {String} url action url
5489  * @cfg {String} paramName default 'imageUpload'
5490  * @cfg {String} method default POST
5491  * @cfg {Boolean} loadMask (true|false) default true
5492  * @cfg {Boolean} loadingText default 'Loading...'
5493  * 
5494  * @constructor
5495  * Create a new Cropbox
5496  * @param {Object} config The config object
5497  */
5498
5499  Roo.panel.Cropbox = function(config){
5500     Roo.panel.Cropbox.superclass.constructor.call(this, config);
5501     
5502     this.addEvents({
5503         /**
5504          * @event beforeselectfile
5505          * Fire before select file
5506          * @param {Roo.panel.Cropbox} this
5507          */
5508         "beforeselectfile" : true,
5509         /**
5510          * @event initial
5511          * Fire after initEvent
5512          * @param {Roo.panel.Cropbox} this
5513          */
5514         "initial" : true,
5515         /**
5516          * @event crop
5517          * Fire after initEvent
5518          * @param {Roo.panel.Cropbox} this
5519          * @param {String} data
5520          */
5521         "crop" : true,
5522         /**
5523          * @event prepare
5524          * Fire when preparing the file data
5525          * @param {Roo.panel.Cropbox} this
5526          * @param {Object} file
5527          */
5528         "prepare" : true,
5529         /**
5530          * @event exception
5531          * Fire when get exception
5532          * @param {Roo.panel.Cropbox} this
5533          * @param {XMLHttpRequest} xhr
5534          */
5535         "exception" : true,
5536         /**
5537          * @event beforeloadcanvas
5538          * Fire before load the canvas
5539          * @param {Roo.panel.Cropbox} this
5540          * @param {String} src
5541          */
5542         "beforeloadcanvas" : true,
5543         /**
5544          * @event trash
5545          * Fire when trash image
5546          * @param {Roo.panel.Cropbox} this
5547          */
5548         "trash" : true,
5549         /**
5550          * @event download
5551          * Fire when download the image
5552          * @param {Roo.panel.Cropbox} this
5553          */
5554         "download" : true,
5555         /**
5556          * @event footerbuttonclick
5557          * Fire when footerbuttonclick
5558          * @param {Roo.panel.Cropbox} this
5559          * @param {String} type
5560          */
5561         "footerbuttonclick" : true,
5562         /**
5563          * @event resize
5564          * Fire when resize
5565          * @param {Roo.panel.Cropbox} this
5566          */
5567         "resize" : true,
5568         /**
5569          * @event rotate
5570          * Fire when rotate the image
5571          * @param {Roo.panel.Cropbox} this
5572          * @param {String} pos
5573          */
5574         "rotate" : true,
5575         /**
5576          * @event inspect
5577          * Fire when inspect the file
5578          * @param {Roo.panel.Cropbox} this
5579          * @param {Object} file
5580          */
5581         "inspect" : true,
5582         /**
5583          * @event upload
5584          * Fire when xhr upload the file
5585          * @param {Roo.panel.Cropbox} this
5586          * @param {Object} data
5587          */
5588         "upload" : true,
5589         /**
5590          * @event arrange
5591          * Fire when arrange the file data
5592          * @param {Roo.panel.Cropbox} this
5593          * @param {Object} formData
5594          */
5595         "arrange" : true,
5596         /**
5597          * @event loadcanvas
5598          * Fire after load the canvas
5599          * @param {Roo.panel.Cropbox}
5600          * @param {Object} imgEl
5601          */
5602         "loadcanvas" : true
5603     });
5604     
5605     this.buttons = this.buttons || Roo.panel.Cropbox.footer.STANDARD;
5606 };
5607
5608 Roo.extend(Roo.panel.Cropbox, Roo.Component,  {
5609     
5610     emptyText : 'Click to upload image',
5611     rotateNotify : 'Image is too small to rotate',
5612     errorTimeout : 3000,
5613     scale : 0,
5614     baseScale : 1,
5615     rotate : 0,
5616     dragable : false,
5617     pinching : false,
5618     mouseX : 0,
5619     mouseY : 0,
5620     cropData : false,
5621     minWidth : 300,
5622     minHeight : 300,
5623     outputMaxWidth : 1200,
5624     windowSize : 300,
5625     file : false,
5626     exif : {},
5627     baseRotate : 1,
5628     cropType : 'image/jpeg',
5629     buttons : false,
5630     canvasLoaded : false,
5631     isDocument : false,
5632     method : 'POST',
5633     paramName : 'imageUpload',
5634     loadMask : true,
5635     loadingText : 'Loading...',
5636     maskEl : false,
5637     
5638     getAutoCreate : function()
5639     {
5640         var cfg = {
5641             tag : 'div',
5642             cls : 'roo-upload-cropbox',
5643             cn : [
5644                 {
5645                     tag : 'input',
5646                     cls : 'roo-upload-cropbox-selector',
5647                     type : 'file'
5648                 },
5649                 {
5650                     tag : 'div',
5651                     cls : 'roo-upload-cropbox-body',
5652                     style : 'cursor:pointer',
5653                     cn : [
5654                         {
5655                             tag : 'div',
5656                             cls : 'roo-upload-cropbox-preview'
5657                         },
5658                         {
5659                             tag : 'div',
5660                             cls : 'roo-upload-cropbox-thumb'
5661                         },
5662                         {
5663                             tag : 'div',
5664                             cls : 'roo-upload-cropbox-empty-notify',
5665                             html : this.emptyText
5666                         },
5667                         {
5668                             tag : 'div',
5669                             cls : 'roo-upload-cropbox-error-notify alert alert-danger',
5670                             html : this.rotateNotify
5671                         }
5672                     ]
5673                 },
5674                 {
5675                     tag : 'div',
5676                     cls : 'roo-upload-cropbox-footer',
5677                     cn : {
5678                         tag : 'div',
5679                         cls : 'btn-group btn-group-justified roo-upload-cropbox-btn-group',
5680                         cn : []
5681                     }
5682                 }
5683             ]
5684         };
5685         
5686         return cfg;
5687     },
5688     
5689     onRender : function(ct, position)
5690     {
5691         Roo.panel.Cropbox.superclass.onRender.call(this, ct, position);
5692
5693         if(this.el){
5694             if (this.el.attr('xtype')) {
5695                 this.el.attr('xtypex', this.el.attr('xtype'));
5696                 this.el.dom.removeAttribute('xtype');
5697                 
5698                 this.initEvents();
5699             }
5700         }
5701         else {
5702             var cfg = Roo.apply({},  this.getAutoCreate());
5703         
5704             cfg.id = this.id || Roo.id();
5705             
5706             if (this.cls) {
5707                 cfg.cls = (typeof(cfg.cls) == 'undefined' ? this.cls : cfg.cls) + ' ' + this.cls;
5708             }
5709             
5710             if (this.style) { // fixme needs to support more complex style data.
5711                 cfg.style = (typeof(cfg.style) == 'undefined' ? this.style : cfg.style) + '; ' + this.style;
5712             }
5713             
5714             this.el = ct.createChild(cfg, position);
5715             
5716             this.initEvents();
5717         }
5718         
5719         if (this.buttons.length) {
5720             
5721             Roo.each(this.buttons, function(bb) {
5722                 
5723                 var btn = this.el.select('.roo-upload-cropbox-footer div.roo-upload-cropbox-btn-group').first().createChild(bb);
5724                 
5725                 btn.on('click', this.onFooterButtonClick.createDelegate(this, [bb.action], true));
5726                 
5727             }, this);
5728         }
5729         
5730         if(this.loadMask){
5731             this.maskEl = this.el;
5732         }
5733     },
5734     
5735     initEvents : function()
5736     {
5737         this.urlAPI = (window.createObjectURL && window) || 
5738                                 (window.URL && URL.revokeObjectURL && URL) || 
5739                                 (window.webkitURL && webkitURL);
5740                         
5741         this.bodyEl = this.el.select('.roo-upload-cropbox-body', true).first();
5742         this.bodyEl.setVisibilityMode(Roo.Element.DISPLAY).originalDisplay = 'block';
5743         
5744         this.selectorEl = this.el.select('.roo-upload-cropbox-selector', true).first();
5745         this.selectorEl.hide();
5746         
5747         this.previewEl = this.el.select('.roo-upload-cropbox-preview', true).first();
5748         this.previewEl.setVisibilityMode(Roo.Element.DISPLAY).originalDisplay = 'block';
5749         
5750         this.thumbEl = this.el.select('.roo-upload-cropbox-thumb', true).first();
5751         this.thumbEl.setVisibilityMode(Roo.Element.DISPLAY).originalDisplay = 'block';
5752         this.thumbEl.hide();
5753         
5754         this.notifyEl = this.el.select('.roo-upload-cropbox-empty-notify', true).first();
5755         this.notifyEl.setVisibilityMode(Roo.Element.DISPLAY).originalDisplay = 'block';
5756         
5757         this.errorEl = this.el.select('.roo-upload-cropbox-error-notify', true).first();
5758         this.errorEl.setVisibilityMode(Roo.Element.DISPLAY).originalDisplay = 'block';
5759         this.errorEl.hide();
5760         
5761         this.footerEl = this.el.select('.roo-upload-cropbox-footer', true).first();
5762         this.footerEl.setVisibilityMode(Roo.Element.DISPLAY).originalDisplay = 'block';
5763         this.footerEl.hide();
5764         
5765         this.setThumbBoxSize();
5766         
5767         this.bind();
5768         
5769         this.resize();
5770         
5771         this.fireEvent('initial', this);
5772     },
5773
5774     bind : function()
5775     {
5776         var _this = this;
5777         
5778         window.addEventListener("resize", function() { _this.resize(); } );
5779         
5780         this.bodyEl.on('click', this.beforeSelectFile, this);
5781         
5782         if(Roo.isTouch){
5783             this.bodyEl.on('touchstart', this.onTouchStart, this);
5784             this.bodyEl.on('touchmove', this.onTouchMove, this);
5785             this.bodyEl.on('touchend', this.onTouchEnd, this);
5786         }
5787         
5788         if(!Roo.isTouch){
5789             this.bodyEl.on('mousedown', this.onMouseDown, this);
5790             this.bodyEl.on('mousemove', this.onMouseMove, this);
5791             var mousewheel = (/Firefox/i.test(navigator.userAgent))? 'DOMMouseScroll' : 'mousewheel';
5792             this.bodyEl.on(mousewheel, this.onMouseWheel, this);
5793             Roo.get(document).on('mouseup', this.onMouseUp, this);
5794         }
5795         
5796         this.selectorEl.on('change', this.onFileSelected, this);
5797     },
5798     
5799     reset : function()
5800     {    
5801         this.scale = 0;
5802         this.baseScale = 1;
5803         this.rotate = 0;
5804         this.baseRotate = 1;
5805         this.dragable = false;
5806         this.pinching = false;
5807         this.mouseX = 0;
5808         this.mouseY = 0;
5809         this.cropData = false;
5810         this.notifyEl.dom.innerHTML = this.emptyText;
5811         
5812         // this.selectorEl.dom.value = '';
5813         
5814     },
5815     
5816     resize : function()
5817     {
5818         if(this.fireEvent('resize', this) != false){
5819             this.setThumbBoxPosition();
5820             this.setCanvasPosition();
5821         }
5822     },
5823     
5824     onFooterButtonClick : function(e, el, o, type)
5825     {
5826         switch (type) {
5827             case 'rotate-left' :
5828                 this.onRotateLeft(e);
5829                 break;
5830             case 'rotate-right' :
5831                 this.onRotateRight(e);
5832                 break;
5833             case 'picture' :
5834                 this.beforeSelectFile(e);
5835                 break;
5836             case 'trash' :
5837                 this.trash(e);
5838                 break;
5839             case 'crop' :
5840                 this.crop(e);
5841                 break;
5842             case 'download' :
5843                 this.download(e);
5844                 break;
5845             case 'center' :
5846                 this.center(e);
5847                 break;
5848             default :
5849                 break;
5850         }
5851         
5852         this.fireEvent('footerbuttonclick', this, type);
5853     },
5854     
5855     beforeSelectFile : function(e)
5856     {
5857         e.preventDefault();
5858         
5859         if(this.fireEvent('beforeselectfile', this) != false){
5860             this.selectorEl.dom.click();
5861         }
5862     },
5863     
5864     onFileSelected : function(e)
5865     {
5866         e.preventDefault();
5867         
5868         if(typeof(this.selectorEl.dom.files) == 'undefined' || !this.selectorEl.dom.files.length){
5869             return;
5870         }
5871         
5872         var file = this.selectorEl.dom.files[0];
5873         
5874         if(this.fireEvent('inspect', this, file) != false){
5875             this.prepare(file);
5876         }
5877         
5878     },
5879     
5880     trash : function(e)
5881     {
5882         this.fireEvent('trash', this);
5883     },
5884     
5885     download : function(e)
5886     {
5887         this.fireEvent('download', this);
5888     },
5889
5890     center : function(e)
5891     {
5892         this.setCanvasPosition();
5893     },
5894     
5895     loadCanvas : function(src)
5896     {   
5897         if(this.fireEvent('beforeloadcanvas', this, src) != false){
5898             
5899             this.reset();
5900             
5901             this.imageEl = document.createElement('img');
5902             
5903             var _this = this;
5904             
5905             this.imageEl.addEventListener("load", function(){ _this.onLoadCanvas(); });
5906             
5907             this.imageEl.src = src;
5908         }
5909     },
5910     
5911     onLoadCanvas : function()
5912     {   
5913         this.imageEl.OriginWidth = this.imageEl.naturalWidth || this.imageEl.width;
5914         this.imageEl.OriginHeight = this.imageEl.naturalHeight || this.imageEl.height;
5915
5916         if(this.fireEvent('loadcanvas', this, this.imageEl) != false){
5917         
5918             this.bodyEl.un('click', this.beforeSelectFile, this);
5919             
5920             this.notifyEl.hide();
5921             this.thumbEl.show();
5922             this.footerEl.show();
5923             
5924             this.baseRotateLevel();
5925             
5926             if(this.isDocument){
5927                 this.setThumbBoxSize();
5928             }
5929             
5930             this.setThumbBoxPosition();
5931             
5932             this.baseScaleLevel();
5933             
5934             this.draw();
5935             
5936             this.resize();
5937             
5938             this.canvasLoaded = true;
5939         
5940         }
5941         
5942         if(this.loadMask){
5943             this.maskEl.unmask();
5944         }
5945         
5946     },
5947     
5948     setCanvasPosition : function(center = true)
5949     {   
5950         if(!this.canvasEl){
5951             return;
5952         }
5953
5954         var newCenterLeft = Math.ceil((this.bodyEl.getWidth() - this.canvasEl.width) / 2);
5955         var newCenterTop = Math.ceil((this.bodyEl.getHeight() - this.canvasEl.height) / 2);
5956
5957         if(center) {
5958             this.previewEl.setLeft(newCenterLeft);
5959             this.previewEl.setTop(newCenterTop);
5960
5961             return;
5962         }
5963         
5964         var oldScaleLevel = this.baseScale * Math.pow(1.02, this.startScale);
5965         var oldCanvasWidth = Math.floor(this.imageEl.OriginWidth * oldScaleLevel);
5966         var oldCanvasHeight = Math.floor(this.imageEl.OriginHeight * oldScaleLevel);
5967
5968         var oldCenterLeft = Math.ceil((this.bodyEl.getWidth() - oldCanvasWidth) / 2);
5969         var oldCenterTop = Math.ceil((this.bodyEl.getHeight() - oldCanvasHeight) / 2);
5970
5971         var leftDiff = newCenterLeft - oldCenterLeft;
5972         var topDiff = newCenterTop - oldCenterTop;
5973
5974         var newPreviewLeft = this.previewEl.getLeft(true) + leftDiff;
5975         var newPreviewTop = this.previewEl.getTop(true) + topDiff;
5976
5977         this.previewEl.setLeft(newPreviewLeft);
5978         this.previewEl.setTop(newPreviewTop);
5979         
5980     },
5981     
5982     onMouseDown : function(e)
5983     {   
5984         e.stopEvent();
5985         
5986         this.dragable = true;
5987         this.pinching = false;
5988         
5989         if(this.isDocument && (this.canvasEl.width < this.thumbEl.getWidth() || this.canvasEl.height < this.thumbEl.getHeight())){
5990             this.dragable = false;
5991             return;
5992         }
5993         
5994         this.mouseX = Roo.isTouch ? e.browserEvent.touches[0].pageX : e.getPageX();
5995         this.mouseY = Roo.isTouch ? e.browserEvent.touches[0].pageY : e.getPageY();
5996         
5997     },
5998     
5999     onMouseMove : function(e)
6000     {   
6001         e.stopEvent();
6002         
6003         if(!this.canvasLoaded){
6004             return;
6005         }
6006         
6007         if (!this.dragable){
6008             return;
6009         }
6010
6011         var maxPaddingLeft = this.canvasEl.width / 0.9 * 0.05;
6012         var maxPaddingTop = maxPaddingLeft * this.minHeight / this.minWidth;
6013
6014         if ((this.imageEl.OriginWidth / this.imageEl.OriginHeight <= this.minWidth / this.minHeight)) {
6015             maxPaddingLeft = (this.canvasEl.height * this.minWidth / this.minHeight - this.canvasEl.width) / 2 + maxPaddingLeft;
6016         }
6017
6018         if ((this.imageEl.OriginWidth / this.imageEl.OriginHeight >= this.minWidth / this.minHeight)) {
6019             maxPaddingTop = (this.canvasEl.width * this.minHeight / this.minWidth - this.canvasEl.height) / 2 + maxPaddingTop;
6020         }
6021         
6022         var minX = Math.ceil(this.thumbEl.getLeft(true) + this.thumbEl.getWidth() - this.canvasEl.width - maxPaddingLeft);
6023         var minY = Math.ceil(this.thumbEl.getTop(true) + this.thumbEl.getHeight() - this.canvasEl.height - maxPaddingTop);
6024         
6025         var maxX = Math.ceil(this.thumbEl.getLeft(true) + maxPaddingLeft);
6026         var maxY = Math.ceil(this.thumbEl.getTop(true) +  maxPaddingTop);
6027
6028         if(minX > maxX) {
6029             var tempX = minX;
6030             minX = maxX;
6031             maxX = tempX;
6032         }
6033
6034         if(minY > maxY) {
6035             var tempY = minY;
6036             minY = maxY;
6037             maxY = tempY;
6038         }
6039
6040         var x = Roo.isTouch ? e.browserEvent.touches[0].pageX : e.getPageX();
6041         var y = Roo.isTouch ? e.browserEvent.touches[0].pageY : e.getPageY();
6042         
6043         x = x - this.mouseX;
6044         y = y - this.mouseY;
6045
6046         var bgX = Math.ceil(x + this.previewEl.getLeft(true));
6047         var bgY = Math.ceil(y + this.previewEl.getTop(true));
6048         
6049         bgX = (bgX < minX) ? minX : ((bgX > maxX) ? maxX : bgX);
6050         bgY = (bgY < minY) ? minY : ((bgY > maxY) ? maxY : bgY);
6051         
6052         this.previewEl.setLeft(bgX);
6053         this.previewEl.setTop(bgY);
6054         
6055         this.mouseX = Roo.isTouch ? e.browserEvent.touches[0].pageX : e.getPageX();
6056         this.mouseY = Roo.isTouch ? e.browserEvent.touches[0].pageY : e.getPageY();
6057     },
6058     
6059     onMouseUp : function(e)
6060     {   
6061         e.stopEvent();
6062         
6063         this.dragable = false;
6064     },
6065     
6066     onMouseWheel : function(e)
6067     {   
6068         e.stopEvent();
6069         
6070         this.startScale = this.scale;
6071         this.scale = (e.getWheelDelta() > 0) ? (this.scale + 1) : (this.scale - 1);
6072         
6073         if(!this.zoomable()){
6074             this.scale = this.startScale;
6075             return;
6076         }
6077
6078         
6079         this.draw();
6080         
6081         return;
6082     },
6083     
6084     zoomable : function()
6085     {
6086         var minScale = this.thumbEl.getWidth() / this.minWidth;
6087         
6088         if(this.minWidth < this.minHeight){
6089             minScale = this.thumbEl.getHeight() / this.minHeight;
6090         }
6091         
6092         var width = Math.ceil(this.imageEl.OriginWidth * this.getScaleLevel() / minScale);
6093         var height = Math.ceil(this.imageEl.OriginHeight * this.getScaleLevel() / minScale);
6094  
6095         var maxWidth = this.imageEl.OriginWidth;
6096         var maxHeight = this.imageEl.OriginHeight;
6097
6098
6099         var newCanvasWidth = Math.floor(this.imageEl.OriginWidth * this.getScaleLevel());
6100         var newCanvasHeight = Math.floor(this.imageEl.OriginHeight * this.getScaleLevel());
6101
6102         var oldCenterLeft = Math.ceil((this.bodyEl.getWidth() - this.canvasEl.width) / 2);
6103         var oldCenterTop = Math.ceil((this.bodyEl.getHeight() - this.canvasEl.height) / 2);
6104
6105         var newCenterLeft = Math.ceil((this.bodyEl.getWidth() - newCanvasWidth) / 2);
6106         var newCenterTop = Math.ceil((this.bodyEl.getHeight() - newCanvasHeight) / 2);
6107
6108         var leftDiff = newCenterLeft - oldCenterLeft;
6109         var topDiff = newCenterTop - oldCenterTop;
6110
6111         var newPreviewLeft = this.previewEl.getLeft(true) + leftDiff;
6112         var newPreviewTop = this.previewEl.getTop(true) + topDiff;
6113
6114         var paddingLeft = newPreviewLeft - this.thumbEl.getLeft(true);
6115         var paddingTop = newPreviewTop - this.thumbEl.getTop(true);
6116
6117         var paddingRight = this.thumbEl.getLeft(true) + this.thumbEl.getWidth() - newCanvasWidth - newPreviewLeft;
6118         var paddingBottom = this.thumbEl.getTop(true) + this.thumbEl.getHeight() - newCanvasHeight - newPreviewTop;
6119
6120         var maxPaddingLeft = newCanvasWidth / 0.9 * 0.05;
6121         var maxPaddingTop = maxPaddingLeft * this.minHeight / this.minWidth;
6122
6123         if ((this.imageEl.OriginWidth / this.imageEl.OriginHeight <= this.minWidth / this.minHeight)) {
6124             maxPaddingLeft = (newCanvasHeight * this.minWidth / this.minHeight - newCanvasWidth) / 2 + maxPaddingLeft;
6125         }
6126
6127         if ((this.imageEl.OriginWidth / this.imageEl.OriginHeight >= this.minWidth / this.minHeight)) {
6128             maxPaddingTop = (newCanvasWidth * this.minHeight / this.minWidth - newCanvasHeight) / 2 + maxPaddingTop;
6129         }
6130         
6131         if(
6132                 this.isDocument &&
6133                 (this.rotate == 0 || this.rotate == 180) && 
6134                 (
6135                     width > this.imageEl.OriginWidth || 
6136                     height > this.imageEl.OriginHeight ||
6137                     (width < this.minWidth && height < this.minHeight)
6138                 )
6139         ){
6140             return false;
6141         }
6142         
6143         if(
6144                 this.isDocument &&
6145                 (this.rotate == 90 || this.rotate == 270) && 
6146                 (
6147                     width > this.imageEl.OriginWidth || 
6148                     height > this.imageEl.OriginHeight ||
6149                     (width < this.minHeight && height < this.minWidth)
6150                 )
6151         ){
6152             return false;
6153         }
6154         
6155         if(
6156                 !this.isDocument &&
6157                 (this.rotate == 0 || this.rotate == 180) && 
6158                 (
6159                     // for zoom out
6160                     paddingLeft > maxPaddingLeft ||
6161                     paddingRight > maxPaddingLeft ||
6162                     paddingTop > maxPaddingTop ||
6163                     paddingBottom > maxPaddingTop ||
6164                     // for zoom in
6165                     width > maxWidth ||
6166                     height > maxHeight
6167                 )
6168         ){
6169             return false;
6170         }
6171         
6172         if(
6173                 !this.isDocument &&
6174                 (this.rotate == 90 || this.rotate == 270) && 
6175                 (
6176                     width < this.minHeight || 
6177                     width > this.imageEl.OriginWidth || 
6178                     height < this.minWidth || 
6179                     height > this.imageEl.OriginHeight
6180                 )
6181         ){
6182             return false;
6183         }
6184         
6185         return true;
6186         
6187     },
6188     
6189     onRotateLeft : function(e)
6190     {   
6191         if(!this.isDocument && (this.canvasEl.height < this.thumbEl.getWidth() || this.canvasEl.width < this.thumbEl.getHeight())){
6192             
6193             var minScale = this.thumbEl.getWidth() / this.minWidth;
6194             
6195             var bw = Math.ceil(this.canvasEl.width / this.getScaleLevel());
6196             var bh = Math.ceil(this.canvasEl.height / this.getScaleLevel());
6197             
6198             this.startScale = this.scale;
6199             
6200             while (this.getScaleLevel() < minScale){
6201             
6202                 this.scale = this.scale + 1;
6203                 
6204                 if(!this.zoomable()){
6205                     break;
6206                 }
6207                 
6208                 if(
6209                         Math.ceil(bw * this.getScaleLevel()) < this.thumbEl.getHeight() ||
6210                         Math.ceil(bh * this.getScaleLevel()) < this.thumbEl.getWidth()
6211                 ){
6212                     continue;
6213                 }
6214                 
6215                 this.rotate = (this.rotate < 90) ? 270 : this.rotate - 90;
6216
6217                 this.draw();
6218                 
6219                 return;
6220             }
6221             
6222             this.scale = this.startScale;
6223             
6224             this.onRotateFail();
6225             
6226             return false;
6227         }
6228         
6229         this.rotate = (this.rotate < 90) ? 270 : this.rotate - 90;
6230
6231         if(this.isDocument){
6232             this.setThumbBoxSize();
6233             this.setThumbBoxPosition();
6234             this.setCanvasPosition();
6235         }
6236         
6237         this.draw();
6238         
6239         this.fireEvent('rotate', this, 'left');
6240         
6241     },
6242     
6243     onRotateRight : function(e)
6244     {
6245         if(!this.isDocument && (this.canvasEl.height < this.thumbEl.getWidth() || this.canvasEl.width < this.thumbEl.getHeight())){
6246             
6247             var minScale = this.thumbEl.getWidth() / this.minWidth;
6248         
6249             var bw = Math.ceil(this.canvasEl.width / this.getScaleLevel());
6250             var bh = Math.ceil(this.canvasEl.height / this.getScaleLevel());
6251             
6252             this.startScale = this.scale;
6253             
6254             while (this.getScaleLevel() < minScale){
6255             
6256                 this.scale = this.scale + 1;
6257                 
6258                 if(!this.zoomable()){
6259                     break;
6260                 }
6261                 
6262                 if(
6263                         Math.ceil(bw * this.getScaleLevel()) < this.thumbEl.getHeight() ||
6264                         Math.ceil(bh * this.getScaleLevel()) < this.thumbEl.getWidth()
6265                 ){
6266                     continue;
6267                 }
6268                 
6269                 this.rotate = (this.rotate > 180) ? 0 : this.rotate + 90;
6270
6271                 this.draw();
6272                 
6273                 return;
6274             }
6275             
6276             this.scale = this.startScale;
6277             
6278             this.onRotateFail();
6279             
6280             return false;
6281         }
6282         
6283         this.rotate = (this.rotate > 180) ? 0 : this.rotate + 90;
6284
6285         if(this.isDocument){
6286             this.setThumbBoxSize();
6287             this.setThumbBoxPosition();
6288             this.setCanvasPosition();
6289         }
6290         
6291         this.draw();
6292         
6293         this.fireEvent('rotate', this, 'right');
6294     },
6295     
6296     onRotateFail : function()
6297     {
6298         this.errorEl.show(true);
6299         
6300         var _this = this;
6301         
6302         (function() { _this.errorEl.hide(true); }).defer(this.errorTimeout);
6303     },
6304     
6305     draw : function()
6306     {
6307         this.previewEl.dom.innerHTML = '';
6308         
6309         var canvasEl = document.createElement("canvas");
6310         
6311         var contextEl = canvasEl.getContext("2d");
6312         
6313         canvasEl.width = this.imageEl.OriginWidth * this.getScaleLevel();
6314         canvasEl.height = this.imageEl.OriginWidth * this.getScaleLevel();
6315         var center = this.imageEl.OriginWidth / 2;
6316         
6317         if(this.imageEl.OriginWidth < this.imageEl.OriginHeight){
6318             canvasEl.width = this.imageEl.OriginHeight * this.getScaleLevel();
6319             canvasEl.height = this.imageEl.OriginHeight * this.getScaleLevel();
6320             center = this.imageEl.OriginHeight / 2;
6321         }
6322         
6323         contextEl.scale(this.getScaleLevel(), this.getScaleLevel());
6324         
6325         contextEl.translate(center, center);
6326         contextEl.rotate(this.rotate * Math.PI / 180);
6327
6328         contextEl.drawImage(this.imageEl, 0, 0, this.imageEl.OriginWidth, this.imageEl.OriginHeight, center * -1, center * -1, this.imageEl.OriginWidth, this.imageEl.OriginHeight);
6329         
6330         this.canvasEl = document.createElement("canvas");
6331         
6332         this.contextEl = this.canvasEl.getContext("2d");
6333         
6334         switch (this.rotate) {
6335             case 0 :
6336                 
6337                 this.canvasEl.width = this.imageEl.OriginWidth * this.getScaleLevel();
6338                 this.canvasEl.height = this.imageEl.OriginHeight * this.getScaleLevel();
6339                 
6340                 this.contextEl.drawImage(canvasEl, 0, 0, this.canvasEl.width, this.canvasEl.height, 0, 0, this.canvasEl.width, this.canvasEl.height);
6341                 
6342                 break;
6343             case 90 : 
6344                 
6345                 this.canvasEl.width = this.imageEl.OriginHeight * this.getScaleLevel();
6346                 this.canvasEl.height = this.imageEl.OriginWidth * this.getScaleLevel();
6347                 
6348                 if(this.imageEl.OriginWidth > this.imageEl.OriginHeight){
6349                     this.contextEl.drawImage(canvasEl, Math.abs(this.canvasEl.width - this.canvasEl.height), 0, this.canvasEl.width, this.canvasEl.height, 0, 0, this.canvasEl.width, this.canvasEl.height);
6350                     break;
6351                 }
6352                 
6353                 this.contextEl.drawImage(canvasEl, 0, 0, this.canvasEl.width, this.canvasEl.height, 0, 0, this.canvasEl.width, this.canvasEl.height);
6354                 
6355                 break;
6356             case 180 :
6357                 
6358                 this.canvasEl.width = this.imageEl.OriginWidth * this.getScaleLevel();
6359                 this.canvasEl.height = this.imageEl.OriginHeight * this.getScaleLevel();
6360                 
6361                 if(this.imageEl.OriginWidth > this.imageEl.OriginHeight){
6362                     this.contextEl.drawImage(canvasEl, 0, Math.abs(this.canvasEl.width - this.canvasEl.height), this.canvasEl.width, this.canvasEl.height, 0, 0, this.canvasEl.width, this.canvasEl.height);
6363                     break;
6364                 }
6365                 
6366                 this.contextEl.drawImage(canvasEl, Math.abs(this.canvasEl.width - this.canvasEl.height), 0, this.canvasEl.width, this.canvasEl.height, 0, 0, this.canvasEl.width, this.canvasEl.height);
6367                 
6368                 break;
6369             case 270 :
6370                 
6371                 this.canvasEl.width = this.imageEl.OriginHeight * this.getScaleLevel();
6372                 this.canvasEl.height = this.imageEl.OriginWidth * this.getScaleLevel();
6373         
6374                 if(this.imageEl.OriginWidth > this.imageEl.OriginHeight){
6375                     this.contextEl.drawImage(canvasEl, 0, 0, this.canvasEl.width, this.canvasEl.height, 0, 0, this.canvasEl.width, this.canvasEl.height);
6376                     break;
6377                 }
6378                 
6379                 this.contextEl.drawImage(canvasEl, 0, Math.abs(this.canvasEl.width - this.canvasEl.height), this.canvasEl.width, this.canvasEl.height, 0, 0, this.canvasEl.width, this.canvasEl.height);
6380                 
6381                 break;
6382             default : 
6383                 break;
6384         }
6385         
6386         this.previewEl.appendChild(this.canvasEl);
6387         
6388         this.setCanvasPosition(false);
6389     },
6390     
6391     crop : function()
6392     {
6393         if(!this.canvasLoaded){
6394             return;
6395         }
6396         
6397         var imageCanvas = document.createElement("canvas");
6398         
6399         var imageContext = imageCanvas.getContext("2d");
6400         
6401         imageCanvas.width = (this.imageEl.OriginWidth > this.imageEl.OriginHeight) ? this.imageEl.OriginWidth : this.imageEl.OriginHeight;
6402         imageCanvas.height = (this.imageEl.OriginWidth > this.imageEl.OriginHeight) ? this.imageEl.OriginWidth : this.imageEl.OriginHeight;
6403         
6404         var center = imageCanvas.width / 2;
6405         
6406         imageContext.translate(center, center);
6407         
6408         imageContext.rotate(this.rotate * Math.PI / 180);
6409         
6410         imageContext.drawImage(this.imageEl, 0, 0, this.imageEl.OriginWidth, this.imageEl.OriginHeight, center * -1, center * -1, this.imageEl.OriginWidth, this.imageEl.OriginHeight);
6411         
6412         var canvas = document.createElement("canvas");
6413         
6414         var context = canvas.getContext("2d");
6415
6416         canvas.width = this.thumbEl.getWidth() / this.getScaleLevel();
6417         
6418         canvas.height = this.thumbEl.getHeight() / this.getScaleLevel();
6419
6420         switch (this.rotate) {
6421             case 0 :
6422                 
6423                 var width = (this.thumbEl.getWidth() / this.getScaleLevel() > this.imageEl.OriginWidth) ? this.imageEl.OriginWidth : (this.thumbEl.getWidth() / this.getScaleLevel());
6424                 var height = (this.thumbEl.getHeight() / this.getScaleLevel() > this.imageEl.OriginHeight) ? this.imageEl.OriginHeight : (this.thumbEl.getHeight() / this.getScaleLevel());
6425                 
6426                 var x = (this.thumbEl.getLeft(true) > this.previewEl.getLeft(true)) ? 0 : ((this.previewEl.getLeft(true) - this.thumbEl.getLeft(true)) / this.getScaleLevel());
6427                 var y = (this.thumbEl.getTop(true) > this.previewEl.getTop(true)) ? 0 : ((this.previewEl.getTop(true) - this.thumbEl.getTop(true)) / this.getScaleLevel());
6428                 
6429                 var sx = this.thumbEl.getLeft(true) - this.previewEl.getLeft(true);
6430                 var sy = this.thumbEl.getTop(true) - this.previewEl.getTop(true);
6431
6432                 sx = sx < 0 ? 0 : (sx / this.getScaleLevel());
6433                 sy = sy < 0 ? 0 : (sy / this.getScaleLevel());
6434
6435                 if(canvas.width > this.outputMaxWidth) {
6436                     var scale = this.outputMaxWidth / canvas.width;
6437                     canvas.width = canvas.width * scale;
6438                     canvas.height = canvas.height * scale;
6439                     context.scale(scale, scale);
6440                 }
6441
6442                 context.fillStyle = 'white';
6443                 context.fillRect(0, 0, this.thumbEl.getWidth() / this.getScaleLevel(), this.thumbEl.getHeight() / this.getScaleLevel());
6444
6445
6446                 context.drawImage(imageCanvas, sx, sy, width, height, x, y, width, height);
6447                 
6448                 break;
6449             case 90 : 
6450                 
6451                 var width = (this.thumbEl.getWidth() / this.getScaleLevel() > this.imageEl.OriginHeight) ? this.imageEl.OriginHeight : (this.thumbEl.getWidth() / this.getScaleLevel());
6452                 var height = (this.thumbEl.getHeight() / this.getScaleLevel() > this.imageEl.OriginWidth) ? this.imageEl.OriginWidth : (this.thumbEl.getHeight() / this.getScaleLevel());
6453                 
6454                 var x = (this.thumbEl.getLeft(true) > this.previewEl.getLeft(true)) ? 0 : ((this.previewEl.getLeft(true) - this.thumbEl.getLeft(true)) / this.getScaleLevel());
6455                 var y = (this.thumbEl.getTop(true) > this.previewEl.getTop(true)) ? 0 : ((this.previewEl.getTop(true) - this.thumbEl.getTop(true)) / this.getScaleLevel());
6456                 
6457                 var targetWidth = this.minWidth - 2 * x;
6458                 var targetHeight = this.minHeight - 2 * y;
6459                 
6460                 var scale = 1;
6461                 
6462                 if((x == 0 && y == 0) || (x == 0 && y > 0)){
6463                     scale = targetWidth / width;
6464                 }
6465                 
6466                 if(x > 0 && y == 0){
6467                     scale = targetHeight / height;
6468                 }
6469                 
6470                 if(x > 0 && y > 0){
6471                     scale = targetWidth / width;
6472                     
6473                     if(width < height){
6474                         scale = targetHeight / height;
6475                     }
6476                 }
6477                 
6478                 context.scale(scale, scale);
6479                 
6480                 var sx = Math.min(this.canvasEl.width - this.thumbEl.getWidth(), this.thumbEl.getLeft(true) - this.previewEl.getLeft(true));
6481                 var sy = Math.min(this.canvasEl.height - this.thumbEl.getHeight(), this.thumbEl.getTop(true) - this.previewEl.getTop(true));
6482
6483                 sx = sx < 0 ? 0 : (sx / this.getScaleLevel());
6484                 sy = sy < 0 ? 0 : (sy / this.getScaleLevel());
6485                 
6486                 sx += (this.imageEl.OriginWidth > this.imageEl.OriginHeight) ? Math.abs(this.imageEl.OriginWidth - this.imageEl.OriginHeight) : 0;
6487                 
6488                 context.drawImage(imageCanvas, sx, sy, width, height, x, y, width, height);
6489                 
6490                 break;
6491             case 180 :
6492                 
6493                 var width = (this.thumbEl.getWidth() / this.getScaleLevel() > this.imageEl.OriginWidth) ? this.imageEl.OriginWidth : (this.thumbEl.getWidth() / this.getScaleLevel());
6494                 var height = (this.thumbEl.getHeight() / this.getScaleLevel() > this.imageEl.OriginHeight) ? this.imageEl.OriginHeight : (this.thumbEl.getHeight() / this.getScaleLevel());
6495                 
6496                 var x = (this.thumbEl.getLeft(true) > this.previewEl.getLeft(true)) ? 0 : ((this.previewEl.getLeft(true) - this.thumbEl.getLeft(true)) / this.getScaleLevel());
6497                 var y = (this.thumbEl.getTop(true) > this.previewEl.getTop(true)) ? 0 : ((this.previewEl.getTop(true) - this.thumbEl.getTop(true)) / this.getScaleLevel());
6498                 
6499                 var targetWidth = this.minWidth - 2 * x;
6500                 var targetHeight = this.minHeight - 2 * y;
6501                 
6502                 var scale = 1;
6503                 
6504                 if((x == 0 && y == 0) || (x == 0 && y > 0)){
6505                     scale = targetWidth / width;
6506                 }
6507                 
6508                 if(x > 0 && y == 0){
6509                     scale = targetHeight / height;
6510                 }
6511                 
6512                 if(x > 0 && y > 0){
6513                     scale = targetWidth / width;
6514                     
6515                     if(width < height){
6516                         scale = targetHeight / height;
6517                     }
6518                 }
6519                 
6520                 context.scale(scale, scale);
6521                 
6522                 var sx = Math.min(this.canvasEl.width - this.thumbEl.getWidth(), this.thumbEl.getLeft(true) - this.previewEl.getLeft(true));
6523                 var sy = Math.min(this.canvasEl.height - this.thumbEl.getHeight(), this.thumbEl.getTop(true) - this.previewEl.getTop(true));
6524
6525                 sx = sx < 0 ? 0 : (sx / this.getScaleLevel());
6526                 sy = sy < 0 ? 0 : (sy / this.getScaleLevel());
6527
6528                 sx += (this.imageEl.OriginWidth > this.imageEl.OriginHeight) ? 0 : Math.abs(this.imageEl.OriginWidth - this.imageEl.OriginHeight);
6529                 sy += (this.imageEl.OriginWidth > this.imageEl.OriginHeight) ? Math.abs(this.imageEl.OriginWidth - this.imageEl.OriginHeight) : 0;
6530                 
6531                 context.drawImage(imageCanvas, sx, sy, width, height, x, y, width, height);
6532                 
6533                 break;
6534             case 270 :
6535                 
6536                 var width = (this.thumbEl.getWidth() / this.getScaleLevel() > this.imageEl.OriginHeight) ? this.imageEl.OriginHeight : (this.thumbEl.getWidth() / this.getScaleLevel());
6537                 var height = (this.thumbEl.getHeight() / this.getScaleLevel() > this.imageEl.OriginWidth) ? this.imageEl.OriginWidth : (this.thumbEl.getHeight() / this.getScaleLevel());
6538                 
6539                 var x = (this.thumbEl.getLeft(true) > this.previewEl.getLeft(true)) ? 0 : ((this.previewEl.getLeft(true) - this.thumbEl.getLeft(true)) / this.getScaleLevel());
6540                 var y = (this.thumbEl.getTop(true) > this.previewEl.getTop(true)) ? 0 : ((this.previewEl.getTop(true) - this.thumbEl.getTop(true)) / this.getScaleLevel());
6541                 
6542                 var targetWidth = this.minWidth - 2 * x;
6543                 var targetHeight = this.minHeight - 2 * y;
6544                 
6545                 var scale = 1;
6546                 
6547                 if((x == 0 && y == 0) || (x == 0 && y > 0)){
6548                     scale = targetWidth / width;
6549                 }
6550                 
6551                 if(x > 0 && y == 0){
6552                     scale = targetHeight / height;
6553                 }
6554                 
6555                 if(x > 0 && y > 0){
6556                     scale = targetWidth / width;
6557                     
6558                     if(width < height){
6559                         scale = targetHeight / height;
6560                     }
6561                 }
6562                 
6563                 context.scale(scale, scale);
6564                 var sx = Math.min(this.canvasEl.width - this.thumbEl.getWidth(), this.thumbEl.getLeft(true) - this.previewEl.getLeft(true));
6565                 var sy = Math.min(this.canvasEl.height - this.thumbEl.getHeight(), this.thumbEl.getTop(true) - this.previewEl.getTop(true));
6566
6567                 sx = sx < 0 ? 0 : (sx / this.getScaleLevel());
6568                 sy = sy < 0 ? 0 : (sy / this.getScaleLevel());
6569                 
6570                 sy += (this.imageEl.OriginWidth > this.imageEl.OriginHeight) ? 0 : Math.abs(this.imageEl.OriginWidth - this.imageEl.OriginHeight);
6571                 
6572                 context.drawImage(imageCanvas, sx, sy, width, height, x, y, width, height);
6573                 
6574                 break;
6575             default : 
6576                 break;
6577         }
6578         
6579         this.cropData = canvas.toDataURL(this.cropType);
6580         
6581         if(this.fireEvent('crop', this, this.cropData) !== false){
6582             this.process(this.file, this.cropData);
6583         }
6584         
6585         return;
6586         
6587     },
6588     
6589     setThumbBoxSize : function()
6590     {
6591         var width, height;
6592         
6593         if(this.isDocument && typeof(this.imageEl) != 'undefined'){
6594             width = (this.imageEl.OriginWidth > this.imageEl.OriginHeight) ? Math.max(this.minWidth, this.minHeight) : Math.min(this.minWidth, this.minHeight);
6595             height = (this.imageEl.OriginWidth > this.imageEl.OriginHeight) ? Math.min(this.minWidth, this.minHeight) : Math.max(this.minWidth, this.minHeight);
6596             
6597             this.minWidth = width;
6598             this.minHeight = height;
6599             
6600             if(this.rotate == 90 || this.rotate == 270){
6601                 this.minWidth = height;
6602                 this.minHeight = width;
6603             }
6604         }
6605         
6606         height = this.windowSize;
6607         width = Math.ceil(this.minWidth * height / this.minHeight);
6608         
6609         if(this.minWidth > this.minHeight){
6610             width = this.windowSize;
6611             height = Math.ceil(this.minHeight * width / this.minWidth);
6612         }
6613         
6614         this.thumbEl.setStyle({
6615             width : width + 'px',
6616             height : height + 'px'
6617         });
6618
6619         return;
6620             
6621     },
6622     
6623     setThumbBoxPosition : function()
6624     {
6625         var x = Math.ceil((this.bodyEl.getWidth() - this.thumbEl.getWidth()) / 2 );
6626         var y = Math.ceil((this.bodyEl.getHeight() - this.thumbEl.getHeight()) / 2);
6627         
6628         this.thumbEl.setLeft(x);
6629         this.thumbEl.setTop(y);
6630         
6631     },
6632     
6633     baseRotateLevel : function()
6634     {
6635         this.baseRotate = 1;
6636         
6637         if(
6638                 typeof(this.exif) != 'undefined' &&
6639                 typeof(this.exif[Roo.panel.Cropbox['tags']['Orientation']]) != 'undefined' &&
6640                 [1, 3, 6, 8].indexOf(this.exif[Roo.panel.Cropbox['tags']['Orientation']]) != -1
6641         ){
6642             this.baseRotate = this.exif[Roo.panel.Cropbox['tags']['Orientation']];
6643         }
6644         
6645         this.rotate = Roo.panel.Cropbox['Orientation'][this.baseRotate];
6646         
6647     },
6648     
6649     baseScaleLevel : function()
6650     {
6651         var width, height;
6652         
6653         if(this.isDocument){
6654             
6655             if(this.baseRotate == 6 || this.baseRotate == 8){
6656             
6657                 height = this.thumbEl.getHeight();
6658                 this.baseScale = height / this.imageEl.OriginWidth;
6659
6660                 if(this.imageEl.OriginHeight * this.baseScale > this.thumbEl.getWidth()){
6661                     width = this.thumbEl.getWidth();
6662                     this.baseScale = width / this.imageEl.OriginHeight;
6663                 }
6664
6665                 return;
6666             }
6667
6668             height = this.thumbEl.getHeight();
6669             this.baseScale = height / this.imageEl.OriginHeight;
6670
6671             if(this.imageEl.OriginWidth * this.baseScale > this.thumbEl.getWidth()){
6672                 width = this.thumbEl.getWidth();
6673                 this.baseScale = width / this.imageEl.OriginWidth;
6674             }
6675
6676             return;
6677         }
6678         
6679         if(this.baseRotate == 6 || this.baseRotate == 8){
6680             
6681             width = this.thumbEl.getHeight();
6682             this.baseScale = width / this.imageEl.OriginHeight;
6683             
6684             if(this.imageEl.OriginHeight * this.baseScale < this.thumbEl.getWidth()){
6685                 height = this.thumbEl.getWidth();
6686                 this.baseScale = height / this.imageEl.OriginHeight;
6687             }
6688             
6689             if(this.imageEl.OriginWidth > this.imageEl.OriginHeight){
6690                 height = this.thumbEl.getWidth();
6691                 this.baseScale = height / this.imageEl.OriginHeight;
6692                 
6693                 if(this.imageEl.OriginWidth * this.baseScale < this.thumbEl.getHeight()){
6694                     width = this.thumbEl.getHeight();
6695                     this.baseScale = width / this.imageEl.OriginWidth;
6696                 }
6697             }
6698             
6699             return;
6700         }
6701         
6702         width = this.thumbEl.getWidth();
6703         this.baseScale = width / this.imageEl.OriginWidth;
6704         
6705         if(this.imageEl.OriginHeight * this.baseScale < this.thumbEl.getHeight()){
6706             height = this.thumbEl.getHeight();
6707             this.baseScale = height / this.imageEl.OriginHeight;
6708         }
6709         
6710         if(this.imageEl.OriginWidth > this.imageEl.OriginHeight){
6711             
6712             height = this.thumbEl.getHeight();
6713             this.baseScale = height / this.imageEl.OriginHeight;
6714             
6715             if(this.imageEl.OriginWidth * this.baseScale < this.thumbEl.getWidth()){
6716                 width = this.thumbEl.getWidth();
6717                 this.baseScale = width / this.imageEl.OriginWidth;
6718             }
6719             
6720         }
6721
6722         if(this.imageEl.OriginWidth < this.minWidth || this.imageEl.OriginHeight < this.minHeight) {
6723             this.baseScale = width / this.minWidth;
6724         }
6725
6726         return;
6727     },
6728     
6729     getScaleLevel : function()
6730     {
6731         return this.baseScale * Math.pow(1.02, this.scale);
6732     },
6733     
6734     onTouchStart : function(e)
6735     {
6736         if(!this.canvasLoaded){
6737             this.beforeSelectFile(e);
6738             return;
6739         }
6740         
6741         var touches = e.browserEvent.touches;
6742         
6743         if(!touches){
6744             return;
6745         }
6746         
6747         if(touches.length == 1){
6748             this.onMouseDown(e);
6749             return;
6750         }
6751         
6752         if(touches.length != 2){
6753             return;
6754         }
6755         
6756         var coords = [];
6757         
6758         for(var i = 0, finger; finger = touches[i]; i++){
6759             coords.push(finger.pageX, finger.pageY);
6760         }
6761         
6762         var x = Math.pow(coords[0] - coords[2], 2);
6763         var y = Math.pow(coords[1] - coords[3], 2);
6764         
6765         this.startDistance = Math.sqrt(x + y);
6766         
6767         this.startScale = this.scale;
6768         
6769         this.pinching = true;
6770         this.dragable = false;
6771         
6772     },
6773     
6774     onTouchMove : function(e)
6775     {
6776         if(!this.pinching && !this.dragable){
6777             return;
6778         }
6779         
6780         var touches = e.browserEvent.touches;
6781         
6782         if(!touches){
6783             return;
6784         }
6785         
6786         if(this.dragable){
6787             this.onMouseMove(e);
6788             return;
6789         }
6790         
6791         var coords = [];
6792         
6793         for(var i = 0, finger; finger = touches[i]; i++){
6794             coords.push(finger.pageX, finger.pageY);
6795         }
6796         
6797         var x = Math.pow(coords[0] - coords[2], 2);
6798         var y = Math.pow(coords[1] - coords[3], 2);
6799         
6800         this.endDistance = Math.sqrt(x + y);
6801         
6802         this.scale = this.startScale + Math.floor(Math.log(this.endDistance / this.startDistance) / Math.log(1.1));
6803         
6804         if(!this.zoomable()){
6805             this.scale = this.startScale;
6806             return;
6807         }
6808         
6809         this.draw();
6810         
6811     },
6812     
6813     onTouchEnd : function(e)
6814     {
6815         this.pinching = false;
6816         this.dragable = false;
6817         
6818     },
6819     
6820     process : function(file, crop)
6821     {
6822         if(this.loadMask){
6823             this.maskEl.mask(this.loadingText);
6824         }
6825         
6826         this.xhr = new XMLHttpRequest();
6827         
6828         file.xhr = this.xhr;
6829
6830         this.xhr.open(this.method, this.url, true);
6831         
6832         var headers = {
6833             "Accept": "application/json",
6834             "Cache-Control": "no-cache",
6835             "X-Requested-With": "XMLHttpRequest"
6836         };
6837         
6838         for (var headerName in headers) {
6839             var headerValue = headers[headerName];
6840             if (headerValue) {
6841                 this.xhr.setRequestHeader(headerName, headerValue);
6842             }
6843         }
6844         
6845         var _this = this;
6846         
6847         this.xhr.onload = function()
6848         {
6849             _this.xhrOnLoad(_this.xhr);
6850         }
6851         
6852         this.xhr.onerror = function()
6853         {
6854             _this.xhrOnError(_this.xhr);
6855         }
6856         
6857         var formData = new FormData();
6858
6859         formData.append('returnHTML', 'NO');
6860
6861         if(crop){
6862             formData.append('crop', crop);
6863             var blobBin = atob(crop.split(',')[1]);
6864             var array = [];
6865             for(var i = 0; i < blobBin.length; i++) {
6866                 array.push(blobBin.charCodeAt(i));
6867             }
6868             var croppedFile =new Blob([new Uint8Array(array)], {type: this.cropType});
6869             formData.append(this.paramName, croppedFile, file.name);
6870         }
6871         
6872         if(typeof(file.filename) != 'undefined'){
6873             formData.append('filename', file.filename);
6874         }
6875         
6876         if(typeof(file.mimetype) != 'undefined'){
6877             formData.append('mimetype', file.mimetype);
6878         }
6879
6880         if(this.fireEvent('arrange', this, formData) != false){
6881             this.xhr.send(formData);
6882         };
6883     },
6884     
6885     xhrOnLoad : function(xhr)
6886     {
6887         if(this.loadMask){
6888             this.maskEl.unmask();
6889         }
6890         
6891         if (xhr.readyState !== 4) {
6892             this.fireEvent('exception', this, xhr);
6893             return;
6894         }
6895
6896         var response = Roo.decode(xhr.responseText);
6897         
6898         if(!response.success){
6899             this.fireEvent('exception', this, xhr);
6900             return;
6901         }
6902         
6903         var response = Roo.decode(xhr.responseText);
6904         
6905         this.fireEvent('upload', this, response);
6906         
6907     },
6908     
6909     xhrOnError : function()
6910     {
6911         if(this.loadMask){
6912             this.maskEl.unmask();
6913         }
6914         
6915         Roo.log('xhr on error');
6916         
6917         var response = Roo.decode(xhr.responseText);
6918           
6919         Roo.log(response);
6920         
6921     },
6922     
6923     prepare : function(file)
6924     {   
6925         if(this.loadMask){
6926             this.maskEl.mask(this.loadingText);
6927         }
6928         
6929         this.file = false;
6930         this.exif = {};
6931         
6932         if(typeof(file) === 'string'){
6933             this.loadCanvas(file);
6934             return;
6935         }
6936         
6937         if(!file || !this.urlAPI){
6938             return;
6939         }
6940         
6941         this.file = file;
6942         if(typeof(file.type) != 'undefined' && file.type.length != 0) {
6943             this.cropType = file.type;
6944         }
6945         
6946         var _this = this;
6947         
6948         if(this.fireEvent('prepare', this, this.file) != false){
6949             
6950             var reader = new FileReader();
6951             
6952             reader.onload = function (e) {
6953                 if (e.target.error) {
6954                     Roo.log(e.target.error);
6955                     return;
6956                 }
6957                 
6958                 var buffer = e.target.result,
6959                     dataView = new DataView(buffer),
6960                     offset = 2,
6961                     maxOffset = dataView.byteLength - 4,
6962                     markerBytes,
6963                     markerLength;
6964                 
6965                 if (dataView.getUint16(0) === 0xffd8) {
6966                     while (offset < maxOffset) {
6967                         markerBytes = dataView.getUint16(offset);
6968                         
6969                         if ((markerBytes >= 0xffe0 && markerBytes <= 0xffef) || markerBytes === 0xfffe) {
6970                             markerLength = dataView.getUint16(offset + 2) + 2;
6971                             if (offset + markerLength > dataView.byteLength) {
6972                                 Roo.log('Invalid meta data: Invalid segment size.');
6973                                 break;
6974                             }
6975                             
6976                             if(markerBytes == 0xffe1){
6977                                 _this.parseExifData(
6978                                     dataView,
6979                                     offset,
6980                                     markerLength
6981                                 );
6982                             }
6983                             
6984                             offset += markerLength;
6985                             
6986                             continue;
6987                         }
6988                         
6989                         break;
6990                     }
6991                     
6992                 }
6993                 
6994                 var url = _this.urlAPI.createObjectURL(_this.file);
6995                 
6996                 _this.loadCanvas(url);
6997                 
6998                 return;
6999             }
7000             
7001             reader.readAsArrayBuffer(this.file);
7002             
7003         }
7004         
7005     },
7006     
7007     parseExifData : function(dataView, offset, length)
7008     {
7009         var tiffOffset = offset + 10,
7010             littleEndian,
7011             dirOffset;
7012     
7013         if (dataView.getUint32(offset + 4) !== 0x45786966) {
7014             // No Exif data, might be XMP data instead
7015             return;
7016         }
7017         
7018         // Check for the ASCII code for "Exif" (0x45786966):
7019         if (dataView.getUint32(offset + 4) !== 0x45786966) {
7020             // No Exif data, might be XMP data instead
7021             return;
7022         }
7023         if (tiffOffset + 8 > dataView.byteLength) {
7024             Roo.log('Invalid Exif data: Invalid segment size.');
7025             return;
7026         }
7027         // Check for the two null bytes:
7028         if (dataView.getUint16(offset + 8) !== 0x0000) {
7029             Roo.log('Invalid Exif data: Missing byte alignment offset.');
7030             return;
7031         }
7032         // Check the byte alignment:
7033         switch (dataView.getUint16(tiffOffset)) {
7034         case 0x4949:
7035             littleEndian = true;
7036             break;
7037         case 0x4D4D:
7038             littleEndian = false;
7039             break;
7040         default:
7041             Roo.log('Invalid Exif data: Invalid byte alignment marker.');
7042             return;
7043         }
7044         // Check for the TIFF tag marker (0x002A):
7045         if (dataView.getUint16(tiffOffset + 2, littleEndian) !== 0x002A) {
7046             Roo.log('Invalid Exif data: Missing TIFF marker.');
7047             return;
7048         }
7049         // Retrieve the directory offset bytes, usually 0x00000008 or 8 decimal:
7050         dirOffset = dataView.getUint32(tiffOffset + 4, littleEndian);
7051         
7052         this.parseExifTags(
7053             dataView,
7054             tiffOffset,
7055             tiffOffset + dirOffset,
7056             littleEndian
7057         );
7058     },
7059     
7060     parseExifTags : function(dataView, tiffOffset, dirOffset, littleEndian)
7061     {
7062         var tagsNumber,
7063             dirEndOffset,
7064             i;
7065         if (dirOffset + 6 > dataView.byteLength) {
7066             Roo.log('Invalid Exif data: Invalid directory offset.');
7067             return;
7068         }
7069         tagsNumber = dataView.getUint16(dirOffset, littleEndian);
7070         dirEndOffset = dirOffset + 2 + 12 * tagsNumber;
7071         if (dirEndOffset + 4 > dataView.byteLength) {
7072             Roo.log('Invalid Exif data: Invalid directory size.');
7073             return;
7074         }
7075         for (i = 0; i < tagsNumber; i += 1) {
7076             this.parseExifTag(
7077                 dataView,
7078                 tiffOffset,
7079                 dirOffset + 2 + 12 * i, // tag offset
7080                 littleEndian
7081             );
7082         }
7083         // Return the offset to the next directory:
7084         return dataView.getUint32(dirEndOffset, littleEndian);
7085     },
7086     
7087     parseExifTag : function (dataView, tiffOffset, offset, littleEndian) 
7088     {
7089         var tag = dataView.getUint16(offset, littleEndian);
7090         
7091         this.exif[tag] = this.getExifValue(
7092             dataView,
7093             tiffOffset,
7094             offset,
7095             dataView.getUint16(offset + 2, littleEndian), // tag type
7096             dataView.getUint32(offset + 4, littleEndian), // tag length
7097             littleEndian
7098         );
7099     },
7100     
7101     getExifValue : function (dataView, tiffOffset, offset, type, length, littleEndian)
7102     {
7103         var tagType = Roo.panel.Cropbox.exifTagTypes[type],
7104             tagSize,
7105             dataOffset,
7106             values,
7107             i,
7108             str,
7109             c;
7110     
7111         if (!tagType) {
7112             Roo.log('Invalid Exif data: Invalid tag type.');
7113             return;
7114         }
7115         
7116         tagSize = tagType.size * length;
7117         // Determine if the value is contained in the dataOffset bytes,
7118         // or if the value at the dataOffset is a pointer to the actual data:
7119         dataOffset = tagSize > 4 ?
7120                 tiffOffset + dataView.getUint32(offset + 8, littleEndian) : (offset + 8);
7121         if (dataOffset + tagSize > dataView.byteLength) {
7122             Roo.log('Invalid Exif data: Invalid data offset.');
7123             return;
7124         }
7125         if (length === 1) {
7126             return tagType.getValue(dataView, dataOffset, littleEndian);
7127         }
7128         values = [];
7129         for (i = 0; i < length; i += 1) {
7130             values[i] = tagType.getValue(dataView, dataOffset + i * tagType.size, littleEndian);
7131         }
7132         
7133         if (tagType.ascii) {
7134             str = '';
7135             // Concatenate the chars:
7136             for (i = 0; i < values.length; i += 1) {
7137                 c = values[i];
7138                 // Ignore the terminating NULL byte(s):
7139                 if (c === '\u0000') {
7140                     break;
7141                 }
7142                 str += c;
7143             }
7144             return str;
7145         }
7146         return values;
7147     }
7148     
7149 });
7150
7151 Roo.apply(Roo.panel.Cropbox, {
7152     tags : {
7153         'Orientation': 0x0112
7154     },
7155     
7156     Orientation: {
7157             1: 0, //'top-left',
7158 //            2: 'top-right',
7159             3: 180, //'bottom-right',
7160 //            4: 'bottom-left',
7161 //            5: 'left-top',
7162             6: 90, //'right-top',
7163 //            7: 'right-bottom',
7164             8: 270 //'left-bottom'
7165     },
7166     
7167     exifTagTypes : {
7168         // byte, 8-bit unsigned int:
7169         1: {
7170             getValue: function (dataView, dataOffset) {
7171                 return dataView.getUint8(dataOffset);
7172             },
7173             size: 1
7174         },
7175         // ascii, 8-bit byte:
7176         2: {
7177             getValue: function (dataView, dataOffset) {
7178                 return String.fromCharCode(dataView.getUint8(dataOffset));
7179             },
7180             size: 1,
7181             ascii: true
7182         },
7183         // short, 16 bit int:
7184         3: {
7185             getValue: function (dataView, dataOffset, littleEndian) {
7186                 return dataView.getUint16(dataOffset, littleEndian);
7187             },
7188             size: 2
7189         },
7190         // long, 32 bit int:
7191         4: {
7192             getValue: function (dataView, dataOffset, littleEndian) {
7193                 return dataView.getUint32(dataOffset, littleEndian);
7194             },
7195             size: 4
7196         },
7197         // rational = two long values, first is numerator, second is denominator:
7198         5: {
7199             getValue: function (dataView, dataOffset, littleEndian) {
7200                 return dataView.getUint32(dataOffset, littleEndian) /
7201                     dataView.getUint32(dataOffset + 4, littleEndian);
7202             },
7203             size: 8
7204         },
7205         // slong, 32 bit signed int:
7206         9: {
7207             getValue: function (dataView, dataOffset, littleEndian) {
7208                 return dataView.getInt32(dataOffset, littleEndian);
7209             },
7210             size: 4
7211         },
7212         // srational, two slongs, first is numerator, second is denominator:
7213         10: {
7214             getValue: function (dataView, dataOffset, littleEndian) {
7215                 return dataView.getInt32(dataOffset, littleEndian) /
7216                     dataView.getInt32(dataOffset + 4, littleEndian);
7217             },
7218             size: 8
7219         }
7220     },
7221     
7222     footer : {
7223         STANDARD : [
7224             {
7225                 tag : 'div',
7226                 cls : 'btn-group roo-upload-cropbox-rotate-left',
7227                 action : 'rotate-left',
7228                 cn : [
7229                     {
7230                         tag : 'button',
7231                         cls : 'btn btn-default',
7232                         html : '<i class="fa fa-undo"></i>'
7233                     }
7234                 ]
7235             },
7236             {
7237                 tag : 'div',
7238                 cls : 'btn-group roo-upload-cropbox-picture',
7239                 action : 'picture',
7240                 cn : [
7241                     {
7242                         tag : 'button',
7243                         cls : 'btn btn-default',
7244                         html : '<i class="fa fa-picture-o"></i>'
7245                     }
7246                 ]
7247             },
7248             {
7249                 tag : 'div',
7250                 cls : 'btn-group roo-upload-cropbox-rotate-right',
7251                 action : 'rotate-right',
7252                 cn : [
7253                     {
7254                         tag : 'button',
7255                         cls : 'btn btn-default',
7256                         html : '<i class="fa fa-repeat"></i>'
7257                     }
7258                 ]
7259             }
7260         ],
7261         DOCUMENT : [
7262             {
7263                 tag : 'div',
7264                 cls : 'btn-group roo-upload-cropbox-rotate-left',
7265                 action : 'rotate-left',
7266                 cn : [
7267                     {
7268                         tag : 'button',
7269                         cls : 'btn btn-default',
7270                         html : '<i class="fa fa-undo"></i>'
7271                     }
7272                 ]
7273             },
7274             {
7275                 tag : 'div',
7276                 cls : 'btn-group roo-upload-cropbox-download',
7277                 action : 'download',
7278                 cn : [
7279                     {
7280                         tag : 'button',
7281                         cls : 'btn btn-default',
7282                         html : '<i class="fa fa-download"></i>'
7283                     }
7284                 ]
7285             },
7286             {
7287                 tag : 'div',
7288                 cls : 'btn-group roo-upload-cropbox-crop',
7289                 action : 'crop',
7290                 cn : [
7291                     {
7292                         tag : 'button',
7293                         cls : 'btn btn-default',
7294                         html : '<i class="fa fa-crop"></i>'
7295                     }
7296                 ]
7297             },
7298             {
7299                 tag : 'div',
7300                 cls : 'btn-group roo-upload-cropbox-trash',
7301                 action : 'trash',
7302                 cn : [
7303                     {
7304                         tag : 'button',
7305                         cls : 'btn btn-default',
7306                         html : '<i class="fa fa-trash"></i>'
7307                     }
7308                 ]
7309             },
7310             {
7311                 tag : 'div',
7312                 cls : 'btn-group roo-upload-cropbox-rotate-right',
7313                 action : 'rotate-right',
7314                 cn : [
7315                     {
7316                         tag : 'button',
7317                         cls : 'btn btn-default',
7318                         html : '<i class="fa fa-repeat"></i>'
7319                     }
7320                 ]
7321             }
7322         ],
7323         ROTATOR : [
7324             {
7325                 tag : 'div',
7326                 cls : 'btn-group roo-upload-cropbox-rotate-left',
7327                 action : 'rotate-left',
7328                 cn : [
7329                     {
7330                         tag : 'button',
7331                         cls : 'btn btn-default',
7332                         html : '<i class="fa fa-undo"></i>'
7333                     }
7334                 ]
7335             },
7336             {
7337                 tag : 'div',
7338                 cls : 'btn-group roo-upload-cropbox-rotate-right',
7339                 action : 'rotate-right',
7340                 cn : [
7341                     {
7342                         tag : 'button',
7343                         cls : 'btn btn-default',
7344                         html : '<i class="fa fa-repeat"></i>'
7345                     }
7346                 ]
7347             }
7348         ],
7349         CENTER : [
7350             {
7351                 tag : 'div',
7352                 cls : 'btn-group roo-upload-cropbox-center',
7353                 action : 'center',
7354                 cn : [
7355                     {
7356                         tag : 'button',
7357                         cls : 'btn btn-default',
7358                         html : 'CENTER'
7359                     }
7360                 ]
7361             }
7362         ]
7363     }
7364 });
7365         /*
7366  * Based on:
7367  * Ext JS Library 1.1.1
7368  * Copyright(c) 2006-2007, Ext JS, LLC.
7369  *
7370  * Originally Released Under LGPL - original licence link has changed is not relivant.
7371  *
7372  * Fork - LGPL
7373  * <script type="text/javascript">
7374  */
7375 /**
7376  * @class Roo.panel.Tab
7377  * @extends Roo.util.Observable
7378  * A lightweight tab container.
7379  * <br><br>
7380  * Usage:
7381  * <pre><code>
7382 // basic tabs 1, built from existing content
7383 var tabs = new Roo.panel.Tab("tabs1");
7384 tabs.addTab("script", "View Script");
7385 tabs.addTab("markup", "View Markup");
7386 tabs.activate("script");
7387
7388 // more advanced tabs, built from javascript
7389 var jtabs = new Roo.panel.Tab("jtabs");
7390 jtabs.addTab("jtabs-1", "Normal Tab", "My content was added during construction.");
7391
7392 // set up the UpdateManager
7393 var tab2 = jtabs.addTab("jtabs-2", "Ajax Tab 1");
7394 var updater = tab2.getUpdateManager();
7395 updater.setDefaultUrl("ajax1.htm");
7396 tab2.on('activate', updater.refresh, updater, true);
7397
7398 // Use setUrl for Ajax loading
7399 var tab3 = jtabs.addTab("jtabs-3", "Ajax Tab 2");
7400 tab3.setUrl("ajax2.htm", null, true);
7401
7402 // Disabled tab
7403 var tab4 = jtabs.addTab("tabs1-5", "Disabled Tab", "Can't see me cause I'm disabled");
7404 tab4.disable();
7405
7406 jtabs.activate("jtabs-1");
7407  * </code></pre>
7408  * @constructor
7409  * Create a new TabPanel.
7410  * @param {String/HTMLElement/Roo.Element} container The id, DOM element or Roo.Element container where this TabPanel is to be rendered.
7411  * @param {Object/Boolean} config Config object to set any properties for this TabPanel, or true to render the tabs on the bottom.
7412  */
7413 Roo.panel.Tab = function(container, config){
7414     /**
7415     * The container element for this TabPanel.
7416     * @type Roo.Element
7417     */
7418     this.el = Roo.get(container, true);
7419     if(config){
7420         if(typeof config == "boolean"){
7421             this.tabPosition = config ? "bottom" : "top";
7422         }else{
7423             Roo.apply(this, config);
7424         }
7425     }
7426     if(this.tabPosition == "bottom"){
7427         this.bodyEl = Roo.get(this.createBody(this.el.dom));
7428         this.el.addClass("x-tabs-bottom");
7429     }
7430     this.stripWrap = Roo.get(this.createStrip(this.el.dom), true);
7431     this.stripEl = Roo.get(this.createStripList(this.stripWrap.dom), true);
7432     this.stripBody = Roo.get(this.stripWrap.dom.firstChild.firstChild, true);
7433     if(Roo.isIE){
7434         Roo.fly(this.stripWrap.dom.firstChild).setStyle("overflow-x", "hidden");
7435     }
7436     if(this.tabPosition != "bottom"){
7437         /** The body element that contains {@link Roo.panel.TabItem} bodies. +
7438          * @type Roo.Element
7439          */
7440         this.bodyEl = Roo.get(this.createBody(this.el.dom));
7441         this.el.addClass("x-tabs-top");
7442     }
7443     this.items = [];
7444
7445     this.bodyEl.setStyle("position", "relative");
7446
7447     this.active = null;
7448     this.activateDelegate = this.activate.createDelegate(this);
7449
7450     this.addEvents({
7451         /**
7452          * @event tabchange
7453          * Fires when the active tab changes
7454          * @param {Roo.panel.Tab} this
7455          * @param {Roo.panel.TabItem} activePanel The new active tab
7456          */
7457         "tabchange": true,
7458         /**
7459          * @event beforetabchange
7460          * Fires before the active tab changes, set cancel to true on the "e" parameter to cancel the change
7461          * @param {Roo.panel.Tab} this
7462          * @param {Object} e Set cancel to true on this object to cancel the tab change
7463          * @param {Roo.panel.TabItem} tab The tab being changed to
7464          */
7465         "beforetabchange" : true
7466     });
7467
7468     Roo.EventManager.onWindowResize(this.onResize, this);
7469     this.cpad = this.el.getPadding("lr");
7470     this.hiddenCount = 0;
7471
7472
7473     // toolbar on the tabbar support...
7474     if (this.toolbar) {
7475         var tcfg = this.toolbar;
7476         tcfg.container = this.stripEl.child('td.x-tab-strip-toolbar');  
7477         this.toolbar = new Roo.Toolbar(tcfg);
7478         if (Roo.isSafari) {
7479             var tbl = tcfg.container.child('table', true);
7480             tbl.setAttribute('width', '100%');
7481         }
7482         
7483     }
7484    
7485
7486
7487     Roo.panel.Tab.superclass.constructor.call(this);
7488 };
7489
7490 Roo.extend(Roo.panel.Tab, Roo.util.Observable, {
7491     /*
7492      *@cfg {String} tabPosition "top" or "bottom" (defaults to "top")
7493      */
7494     tabPosition : "top",
7495     /*
7496      *@cfg {Number} currentTabWidth The width of the current tab (defaults to 0)
7497      */
7498     currentTabWidth : 0,
7499     /*
7500      *@cfg {Number} minTabWidth The minimum width of a tab (defaults to 40) (ignored if {@link #resizeTabs} is not true)
7501      */
7502     minTabWidth : 40,
7503     /*
7504      *@cfg {Number} maxTabWidth The maximum width of a tab (defaults to 250) (ignored if {@link #resizeTabs} is not true)
7505      */
7506     maxTabWidth : 250,
7507     /*
7508      *@cfg {Number} preferredTabWidth The preferred (default) width of a tab (defaults to 175) (ignored if {@link #resizeTabs} is not true)
7509      */
7510     preferredTabWidth : 175,
7511     /*
7512      *@cfg {Boolean} resizeTabs True to enable dynamic tab resizing (defaults to false)
7513      */
7514     resizeTabs : false,
7515     /*
7516      *@cfg {Boolean} monitorResize Set this to true to turn on window resize monitoring (ignored if {@link #resizeTabs} is not true) (defaults to true)
7517      */
7518     monitorResize : true,
7519     /*
7520      *@cfg {Object} toolbar xtype description of toolbar to show at the right of the tab bar. 
7521      */
7522     toolbar : false,
7523
7524     /**
7525      * Creates a new {@link Roo.panel.TabItem} by looking for an existing element with the provided id -- if it's not found it creates one.
7526      * @param {String} id The id of the div to use <b>or create</b>
7527      * @param {String} text The text for the tab
7528      * @param {String} content (optional) Content to put in the TabPanelItem body
7529      * @param {Boolean} closable (optional) True to create a close icon on the tab
7530      * @return {Roo.panel.TabItem} The created TabPanelItem
7531      */
7532     addTab : function(id, text, content, closable){
7533         var item = new Roo.panel.TabItem(this, id, text, closable);
7534         this.addTabItem(item);
7535         if(content){
7536             item.setContent(content);
7537         }
7538         return item;
7539     },
7540
7541     /**
7542      * Returns the {@link Roo.panel.TabItem} with the specified id/index
7543      * @param {String/Number} id The id or index of the TabPanelItem to fetch.
7544      * @return {Roo.panel.TabItem}
7545      */
7546     getTab : function(id){
7547         return this.items[id];
7548     },
7549
7550     /**
7551      * Hides the {@link Roo.panel.TabItem} with the specified id/index
7552      * @param {String/Number} id The id or index of the TabPanelItem to hide.
7553      */
7554     hideTab : function(id){
7555         var t = this.items[id];
7556         if(!t.isHidden()){
7557            t.setHidden(true);
7558            this.hiddenCount++;
7559            this.autoSizeTabs();
7560         }
7561     },
7562
7563     /**
7564      * "Unhides" the {@link Roo.panel.TabItem} with the specified id/index.
7565      * @param {String/Number} id The id or index of the TabPanelItem to unhide.
7566      */
7567     unhideTab : function(id){
7568         var t = this.items[id];
7569         if(t.isHidden()){
7570            t.setHidden(false);
7571            this.hiddenCount--;
7572            this.autoSizeTabs();
7573         }
7574     },
7575
7576     /**
7577      * Adds an existing {@link Roo.panel.TabItem}.
7578      * @param {Roo.panel.TabItem} item The TabPanelItem to add
7579      */
7580     addTabItem : function(item){
7581         this.items[item.id] = item;
7582         this.items.push(item);
7583         if(this.resizeTabs){
7584            item.setWidth(this.currentTabWidth || this.preferredTabWidth);
7585            this.autoSizeTabs();
7586         }else{
7587             item.autoSize();
7588         }
7589     },
7590
7591     /**
7592      * Removes a {@link Roo.panel.TabItem}.
7593      * @param {String/Number} id The id or index of the TabPanelItem to remove.
7594      */
7595     removeTab : function(id){
7596         var items = this.items;
7597         var tab = items[id];
7598         if(!tab) { return; }
7599         var index = items.indexOf(tab);
7600         if(this.active == tab && items.length > 1){
7601             var newTab = this.getNextAvailable(index);
7602             if(newTab) {
7603                 newTab.activate();
7604             }
7605         }
7606         this.stripEl.dom.removeChild(tab.pnode.dom);
7607         if(tab.bodyEl.dom.parentNode == this.bodyEl.dom){ // if it was moved already prevent error
7608             this.bodyEl.dom.removeChild(tab.bodyEl.dom);
7609         }
7610         items.splice(index, 1);
7611         delete this.items[tab.id];
7612         tab.fireEvent("close", tab);
7613         tab.purgeListeners();
7614         this.autoSizeTabs();
7615     },
7616
7617     getNextAvailable : function(start){
7618         var items = this.items;
7619         var index = start;
7620         // look for a next tab that will slide over to
7621         // replace the one being removed
7622         while(index < items.length){
7623             var item = items[++index];
7624             if(item && !item.isHidden()){
7625                 return item;
7626             }
7627         }
7628         // if one isn't found select the previous tab (on the left)
7629         index = start;
7630         while(index >= 0){
7631             var item = items[--index];
7632             if(item && !item.isHidden()){
7633                 return item;
7634             }
7635         }
7636         return null;
7637     },
7638
7639     /**
7640      * Disables a {@link Roo.panel.TabItem}. It cannot be the active tab, if it is this call is ignored.
7641      * @param {String/Number} id The id or index of the TabPanelItem to disable.
7642      */
7643     disableTab : function(id){
7644         var tab = this.items[id];
7645         if(tab && this.active != tab){
7646             tab.disable();
7647         }
7648     },
7649
7650     /**
7651      * Enables a {@link Roo.panel.TabItem} that is disabled.
7652      * @param {String/Number} id The id or index of the TabPanelItem to enable.
7653      */
7654     enableTab : function(id){
7655         var tab = this.items[id];
7656         tab.enable();
7657     },
7658
7659     /**
7660      * Activates a {@link Roo.panel.TabItem}. The currently active one will be deactivated.
7661      * @param {String/Number} id The id or index of the TabPanelItem to activate.
7662      * @return {Roo.panel.TabItem} The TabPanelItem.
7663      */
7664     activate : function(id){
7665         var tab = this.items[id];
7666         if(!tab){
7667             return null;
7668         }
7669         if(tab == this.active || tab.disabled){
7670             return tab;
7671         }
7672         var e = {};
7673         this.fireEvent("beforetabchange", this, e, tab);
7674         if(e.cancel !== true && !tab.disabled){
7675             if(this.active){
7676                 this.active.hide();
7677             }
7678             this.active = this.items[id];
7679             this.active.show();
7680             this.fireEvent("tabchange", this, this.active);
7681         }
7682         return tab;
7683     },
7684
7685     /**
7686      * Gets the active {@link Roo.panel.TabItem}.
7687      * @return {Roo.panel.TabItem} The active TabPanelItem or null if none are active.
7688      */
7689     getActiveTab : function(){
7690         return this.active;
7691     },
7692
7693     /**
7694      * Updates the tab body element to fit the height of the container element
7695      * for overflow scrolling
7696      * @param {Number} targetHeight (optional) Override the starting height from the elements height
7697      */
7698     syncHeight : function(targetHeight){
7699         var height = (targetHeight || this.el.getHeight())-this.el.getBorderWidth("tb")-this.el.getPadding("tb");
7700         var bm = this.bodyEl.getMargins();
7701         var newHeight = height-(this.stripWrap.getHeight()||0)-(bm.top+bm.bottom);
7702         this.bodyEl.setHeight(newHeight);
7703         return newHeight;
7704     },
7705
7706     onResize : function(){
7707         if(this.monitorResize){
7708             this.autoSizeTabs();
7709         }
7710     },
7711
7712     /**
7713      * Disables tab resizing while tabs are being added (if {@link #resizeTabs} is false this does nothing)
7714      */
7715     beginUpdate : function(){
7716         this.updating = true;
7717     },
7718
7719     /**
7720      * Stops an update and resizes the tabs (if {@link #resizeTabs} is false this does nothing)
7721      */
7722     endUpdate : function(){
7723         this.updating = false;
7724         this.autoSizeTabs();
7725     },
7726
7727     /**
7728      * Manual call to resize the tabs (if {@link #resizeTabs} is false this does nothing)
7729      */
7730     autoSizeTabs : function(){
7731         var count = this.items.length;
7732         var vcount = count - this.hiddenCount;
7733         if(!this.resizeTabs || count < 1 || vcount < 1 || this.updating) {
7734             return;
7735         }
7736         var w = Math.max(this.el.getWidth() - this.cpad, 10);
7737         var availWidth = Math.floor(w / vcount);
7738         var b = this.stripBody;
7739         if(b.getWidth() > w){
7740             var tabs = this.items;
7741             this.setTabWidth(Math.max(availWidth, this.minTabWidth)-2);
7742             if(availWidth < this.minTabWidth){
7743                 /*if(!this.sleft){    // incomplete scrolling code
7744                     this.createScrollButtons();
7745                 }
7746                 this.showScroll();
7747                 this.stripClip.setWidth(w - (this.sleft.getWidth()+this.sright.getWidth()));*/
7748             }
7749         }else{
7750             if(this.currentTabWidth < this.preferredTabWidth){
7751                 this.setTabWidth(Math.min(availWidth, this.preferredTabWidth)-2);
7752             }
7753         }
7754     },
7755
7756     /**
7757      * Returns the number of tabs in this TabPanel.
7758      * @return {Number}
7759      */
7760      getCount : function(){
7761          return this.items.length;
7762      },
7763
7764     /**
7765      * Resizes all the tabs to the passed width
7766      * @param {Number} The new width
7767      */
7768     setTabWidth : function(width){
7769         this.currentTabWidth = width;
7770         for(var i = 0, len = this.items.length; i < len; i++) {
7771                 if(!this.items[i].isHidden()) {
7772                 this.items[i].setWidth(width);
7773             }
7774         }
7775     },
7776
7777     /**
7778      * Destroys this TabPanel
7779      * @param {Boolean} removeEl (optional) True to remove the element from the DOM as well (defaults to undefined)
7780      */
7781     destroy : function(removeEl){
7782         Roo.EventManager.removeResizeListener(this.onResize, this);
7783         for(var i = 0, len = this.items.length; i < len; i++){
7784             this.items[i].purgeListeners();
7785         }
7786         if(removeEl === true){
7787             this.el.update("");
7788             this.el.remove();
7789         }
7790     }
7791 });
7792
7793
7794 /** @private */
7795 Roo.panel.Tab.prototype.createStripList = function(strip){
7796     // div wrapper for retard IE
7797     // returns the "tr" element.
7798     strip.innerHTML = '<div class="x-tabs-strip-wrap">'+
7799         '<table class="x-tabs-strip" cellspacing="0" cellpadding="0" border="0"><tbody><tr>'+
7800         '<td class="x-tab-strip-toolbar"></td></tr></tbody></table></div>';
7801     return strip.firstChild.firstChild.firstChild.firstChild;
7802 };
7803 /** @private */
7804 Roo.panel.Tab.prototype.createBody = function(container){
7805     var body = document.createElement("div");
7806     Roo.id(body, "tab-body");
7807     Roo.fly(body).addClass("x-tabs-body");
7808     container.appendChild(body);
7809     return body;
7810 };
7811 /** @private */
7812 Roo.panel.Tab.prototype.createItemBody = function(bodyEl, id){
7813     var body = Roo.getDom(id);
7814     if(!body){
7815         body = document.createElement("div");
7816         body.id = id;
7817     }
7818     Roo.fly(body).addClass("x-tabs-item-body");
7819     bodyEl.insertBefore(body, bodyEl.firstChild);
7820     return body;
7821 };
7822 /** @private */
7823 Roo.panel.Tab.prototype.createStripElements = function(stripEl, text, closable){
7824     var td = document.createElement("td");
7825     stripEl.insertBefore(td, stripEl.childNodes[stripEl.childNodes.length-1]);
7826     //stripEl.appendChild(td);
7827     if(closable){
7828         td.className = "x-tabs-closable";
7829         if(!this.closeTpl){
7830             this.closeTpl = new Roo.Template(
7831                '<a href="#" class="x-tabs-right"><span class="x-tabs-left"><em class="x-tabs-inner">' +
7832                '<span unselectable="on"' + (this.disableTooltips ? '' : ' title="{text}"') +' class="x-tabs-text">{text}</span>' +
7833                '<div unselectable="on" class="close-icon">&#160;</div></em></span></a>'
7834             );
7835         }
7836         var el = this.closeTpl.overwrite(td, {"text": text});
7837         var close = el.getElementsByTagName("div")[0];
7838         var inner = el.getElementsByTagName("em")[0];
7839         return {"el": el, "close": close, "inner": inner};
7840     } else {
7841         if(!this.tabTpl){
7842             this.tabTpl = new Roo.Template(
7843                '<a href="#" class="x-tabs-right"><span class="x-tabs-left"><em class="x-tabs-inner">' +
7844                '<span unselectable="on"' + (this.disableTooltips ? '' : ' title="{text}"') +' class="x-tabs-text">{text}</span></em></span></a>'
7845             );
7846         }
7847         var el = this.tabTpl.overwrite(td, {"text": text});
7848         var inner = el.getElementsByTagName("em")[0];
7849         return {"el": el, "inner": inner};
7850     }
7851 };/**
7852  * @class Roo.panel.TabItem
7853  * @extends Roo.util.Observable
7854  * Represents an individual item (tab plus body) in a TabPanel.
7855  * @param {Roo.panel.Tab} tabPanel The {@link Roo.panel.Tab} this TabPanelItem belongs to
7856  * @param {String} id The id of this TabPanelItem
7857  * @param {String} text The text for the tab of this TabPanelItem
7858  * @param {Boolean} closable True to allow this TabPanelItem to be closable (defaults to false)
7859  */
7860  Roo.panel.TabItem = function(tabPanel, id, text, closable){
7861     /**
7862      * The {@link Roo.panel.Tab} this TabPanelItem belongs to
7863      * @type Roo.panel.Tab
7864      */
7865     this.tabPanel = tabPanel;
7866     /**
7867      * The id for this TabPanelItem
7868      * @type String
7869      */
7870     this.id = id;
7871     /** @private */
7872     this.disabled = false;
7873     /** @private */
7874     this.text = text;
7875     /** @private */
7876     this.loaded = false;
7877     this.closable = closable;
7878
7879     /**
7880      * The body element for this TabPanelItem.
7881      * @type Roo.Element
7882      */
7883     this.bodyEl = Roo.get(tabPanel.createItemBody(tabPanel.bodyEl.dom, id));
7884     this.bodyEl.setVisibilityMode(Roo.Element.VISIBILITY);
7885     this.bodyEl.setStyle("display", "block");
7886     this.bodyEl.setStyle("zoom", "1");
7887     this.hideAction();
7888
7889     var els = tabPanel.createStripElements(tabPanel.stripEl.dom, text, closable);
7890     /** @private */
7891     this.el = Roo.get(els.el, true);
7892     this.inner = Roo.get(els.inner, true);
7893     this.textEl = Roo.get(this.el.dom.firstChild.firstChild.firstChild, true);
7894     this.pnode = Roo.get(els.el.parentNode, true);
7895     this.el.on("mousedown", this.onTabMouseDown, this);
7896     this.el.on("click", this.onTabClick, this);
7897     /** @private */
7898     if(closable){
7899         var c = Roo.get(els.close, true);
7900         c.dom.title = this.closeText;
7901         c.addClassOnOver("close-over");
7902         c.on("click", this.closeClick, this);
7903      }
7904
7905     this.addEvents({
7906          /**
7907          * @event activate
7908          * Fires when this tab becomes the active tab.
7909          * @param {Roo.panel.Tab} tabPanel The parent TabPanel
7910          * @param {Roo.panel.TabItem} this
7911          */
7912         "activate": true,
7913         /**
7914          * @event beforeclose
7915          * Fires before this tab is closed. To cancel the close, set cancel to true on e (e.cancel = true).
7916          * @param {Roo.panel.TabItem} this
7917          * @param {Object} e Set cancel to true on this object to cancel the close.
7918          */
7919         "beforeclose": true,
7920         /**
7921          * @event close
7922          * Fires when this tab is closed.
7923          * @param {Roo.panel.TabItem} this
7924          */
7925          "close": true,
7926         /**
7927          * @event deactivate
7928          * Fires when this tab is no longer the active tab.
7929          * @param {Roo.panel.Tab} tabPanel The parent TabPanel
7930          * @param {Roo.panel.TabItem} this
7931          */
7932          "deactivate" : true
7933     });
7934     this.hidden = false;
7935
7936     Roo.panel.TabItem.superclass.constructor.call(this);
7937 };
7938
7939 Roo.extend(Roo.panel.TabItem, Roo.util.Observable, {
7940     purgeListeners : function(){
7941        Roo.util.Observable.prototype.purgeListeners.call(this);
7942        this.el.removeAllListeners();
7943     },
7944     /**
7945      * Shows this TabPanelItem -- this <b>does not</b> deactivate the currently active TabPanelItem.
7946      */
7947     show : function(){
7948         this.pnode.addClass("on");
7949         this.showAction();
7950         if(Roo.isOpera){
7951             this.tabPanel.stripWrap.repaint();
7952         }
7953         this.fireEvent("activate", this.tabPanel, this);
7954     },
7955
7956     /**
7957      * Returns true if this tab is the active tab.
7958      * @return {Boolean}
7959      */
7960     isActive : function(){
7961         return this.tabPanel.getActiveTab() == this;
7962     },
7963
7964     /**
7965      * Hides this TabPanelItem -- if you don't activate another TabPanelItem this could look odd.
7966      */
7967     hide : function(){
7968         this.pnode.removeClass("on");
7969         this.hideAction();
7970         this.fireEvent("deactivate", this.tabPanel, this);
7971     },
7972
7973     hideAction : function(){
7974         this.bodyEl.hide();
7975         this.bodyEl.setStyle("position", "absolute");
7976         this.bodyEl.setLeft("-20000px");
7977         this.bodyEl.setTop("-20000px");
7978     },
7979
7980     showAction : function(){
7981         this.bodyEl.setStyle("position", "relative");
7982         this.bodyEl.setTop("");
7983         this.bodyEl.setLeft("");
7984         this.bodyEl.show();
7985     },
7986
7987     /**
7988      * Set the tooltip for the tab.
7989      * @param {String} tooltip The tab's tooltip
7990      */
7991     setTooltip : function(text){
7992         if(Roo.QuickTips && Roo.QuickTips.isEnabled()){
7993             this.textEl.dom.qtip = text;
7994             this.textEl.dom.removeAttribute('title');
7995         }else{
7996             this.textEl.dom.title = text;
7997         }
7998     },
7999
8000     onTabClick : function(e){
8001         e.preventDefault();
8002         this.tabPanel.activate(this.id);
8003     },
8004
8005     onTabMouseDown : function(e){
8006         e.preventDefault();
8007         this.tabPanel.activate(this.id);
8008     },
8009
8010     getWidth : function(){
8011         return this.inner.getWidth();
8012     },
8013
8014     setWidth : function(width){
8015         var iwidth = width - this.pnode.getPadding("lr");
8016         this.inner.setWidth(iwidth);
8017         this.textEl.setWidth(iwidth-this.inner.getPadding("lr"));
8018         this.pnode.setWidth(width);
8019     },
8020
8021     /**
8022      * Show or hide the tab
8023      * @param {Boolean} hidden True to hide or false to show.
8024      */
8025     setHidden : function(hidden){
8026         this.hidden = hidden;
8027         this.pnode.setStyle("display", hidden ? "none" : "");
8028     },
8029
8030     /**
8031      * Returns true if this tab is "hidden"
8032      * @return {Boolean}
8033      */
8034     isHidden : function(){
8035         return this.hidden;
8036     },
8037
8038     /**
8039      * Returns the text for this tab
8040      * @return {String}
8041      */
8042     getText : function(){
8043         return this.text;
8044     },
8045
8046     autoSize : function(){
8047         //this.el.beginMeasure();
8048         this.textEl.setWidth(1);
8049         /*
8050          *  #2804 [new] Tabs in Roojs
8051          *  increase the width by 2-4 pixels to prevent the ellipssis showing in chrome
8052          */
8053         this.setWidth(this.textEl.dom.scrollWidth+this.pnode.getPadding("lr")+this.inner.getPadding("lr") + 2);
8054         //this.el.endMeasure();
8055     },
8056
8057     /**
8058      * Sets the text for the tab (Note: this also sets the tooltip text)
8059      * @param {String} text The tab's text and tooltip
8060      */
8061     setText : function(text){
8062         this.text = text;
8063         this.textEl.update(text);
8064         this.setTooltip(text);
8065         if(!this.tabPanel.resizeTabs){
8066             this.autoSize();
8067         }
8068     },
8069     /**
8070      * Activates this TabPanelItem -- this <b>does</b> deactivate the currently active TabPanelItem.
8071      */
8072     activate : function(){
8073         this.tabPanel.activate(this.id);
8074     },
8075
8076     /**
8077      * Disables this TabPanelItem -- this does nothing if this is the active TabPanelItem.
8078      */
8079     disable : function(){
8080         if(this.tabPanel.active != this){
8081             this.disabled = true;
8082             this.pnode.addClass("disabled");
8083         }
8084     },
8085
8086     /**
8087      * Enables this TabPanelItem if it was previously disabled.
8088      */
8089     enable : function(){
8090         this.disabled = false;
8091         this.pnode.removeClass("disabled");
8092     },
8093
8094     /**
8095      * Sets the content for this TabPanelItem.
8096      * @param {String} content The content
8097      * @param {Boolean} loadScripts true to look for and load scripts
8098      */
8099     setContent : function(content, loadScripts){
8100         this.bodyEl.update(content, loadScripts);
8101     },
8102
8103     /**
8104      * Gets the {@link Roo.UpdateManager} for the body of this TabPanelItem. Enables you to perform Ajax updates.
8105      * @return {Roo.UpdateManager} The UpdateManager
8106      */
8107     getUpdateManager : function(){
8108         return this.bodyEl.getUpdateManager();
8109     },
8110
8111     /**
8112      * Set a URL to be used to load the content for this TabPanelItem.
8113      * @param {String/Function} url The URL to load the content from, or a function to call to get the URL
8114      * @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)
8115      * @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)
8116      * @return {Roo.UpdateManager} The UpdateManager
8117      */
8118     setUrl : function(url, params, loadOnce){
8119         if(this.refreshDelegate){
8120             this.un('activate', this.refreshDelegate);
8121         }
8122         this.refreshDelegate = this._handleRefresh.createDelegate(this, [url, params, loadOnce]);
8123         this.on("activate", this.refreshDelegate);
8124         return this.bodyEl.getUpdateManager();
8125     },
8126
8127     /** @private */
8128     _handleRefresh : function(url, params, loadOnce){
8129         if(!loadOnce || !this.loaded){
8130             var updater = this.bodyEl.getUpdateManager();
8131             updater.update(url, params, this._setLoaded.createDelegate(this));
8132         }
8133     },
8134
8135     /**
8136      *   Forces a content refresh from the URL specified in the {@link #setUrl} method.
8137      *   Will fail silently if the setUrl method has not been called.
8138      *   This does not activate the panel, just updates its content.
8139      */
8140     refresh : function(){
8141         if(this.refreshDelegate){
8142            this.loaded = false;
8143            this.refreshDelegate();
8144         }
8145     },
8146
8147     /** @private */
8148     _setLoaded : function(){
8149         this.loaded = true;
8150     },
8151
8152     /** @private */
8153     closeClick : function(e){
8154         var o = {};
8155         e.stopEvent();
8156         this.fireEvent("beforeclose", this, o);
8157         if(o.cancel !== true){
8158             this.tabPanel.removeTab(this.id);
8159         }
8160     },
8161     /**
8162      * The text displayed in the tooltip for the close icon.
8163      * @type String
8164      */
8165     closeText : "Close this tab"
8166 });
8167
8168 /** @private */
8169 Roo.panel.Tab.prototype.createStrip = function(container){
8170     var strip = document.createElement("div");
8171     strip.className = "x-tabs-wrap";
8172     container.appendChild(strip);
8173     return strip;
8174 };/*
8175  * Based on:
8176  * Ext JS Library 1.1.1
8177  * Copyright(c) 2006-2007, Ext JS, LLC.
8178  *
8179  * Originally Released Under LGPL - original licence link has changed is not relivant.
8180  *
8181  * Fork - LGPL
8182  * <script type="text/javascript">
8183  */
8184
8185 /**
8186  * @class Roo.Button
8187  * @extends Roo.util.Observable
8188  * Simple Button class
8189  * @cfg {String} text The button text
8190  * @cfg {String} icon The path to an image to display in the button (the image will be set as the background-image
8191  * CSS property of the button by default, so if you want a mixed icon/text button, set cls:"x-btn-text-icon")
8192  * @cfg {Function} handler A function called when the button is clicked (can be used instead of click event)
8193  * @cfg {Object} scope The scope of the handler
8194  * @cfg {Number} minWidth The minimum width for this button (used to give a set of buttons a common width)
8195  * @cfg {String/Object} tooltip The tooltip for the button - can be a string or QuickTips config object
8196  * @cfg {Boolean} hidden True to start hidden (defaults to false)
8197  * @cfg {Boolean} disabled True to start disabled (defaults to false)
8198  * @cfg {Boolean} pressed True to start pressed (only if enableToggle = true)
8199  * @cfg {String} toggleGroup The group this toggle button is a member of (only 1 per group can be pressed, only
8200    applies if enableToggle = true)
8201  * @cfg {String/HTMLElement/Element} renderTo The element to append the button to
8202  * @cfg {Boolean/Object} repeat True to repeat fire the click event while the mouse is down. This can also be
8203   an {@link Roo.util.ClickRepeater} config object (defaults to false).
8204  * @constructor
8205  * Create a new button
8206  * @param {Object} config The config object
8207  */
8208 Roo.Button = function(renderTo, config)
8209 {
8210     if (!config) {
8211         config = renderTo;
8212         renderTo = config.renderTo || false;
8213     }
8214     
8215     Roo.apply(this, config);
8216     this.addEvents({
8217         /**
8218              * @event click
8219              * Fires when this button is clicked
8220              * @param {Button} this
8221              * @param {EventObject} e The click event
8222              */
8223             "click" : true,
8224         /**
8225              * @event toggle
8226              * Fires when the "pressed" state of this button changes (only if enableToggle = true)
8227              * @param {Button} this
8228              * @param {Boolean} pressed
8229              */
8230             "toggle" : true,
8231         /**
8232              * @event mouseover
8233              * Fires when the mouse hovers over the button
8234              * @param {Button} this
8235              * @param {Event} e The event object
8236              */
8237         'mouseover' : true,
8238         /**
8239              * @event mouseout
8240              * Fires when the mouse exits the button
8241              * @param {Button} this
8242              * @param {Event} e The event object
8243              */
8244         'mouseout': true,
8245          /**
8246              * @event render
8247              * Fires when the button is rendered
8248              * @param {Button} this
8249              */
8250         'render': true
8251     });
8252     if(this.menu){
8253         this.menu = Roo.menu.MenuMgr.get(this.menu);
8254     }
8255     // register listeners first!!  - so render can be captured..
8256     Roo.util.Observable.call(this);
8257     if(renderTo){
8258         this.render(renderTo);
8259     }
8260     
8261   
8262 };
8263
8264 Roo.extend(Roo.Button, Roo.util.Observable, {
8265     /**
8266      * 
8267      */
8268     
8269     /**
8270      * Read-only. True if this button is hidden
8271      * @type Boolean
8272      */
8273     hidden : false,
8274     /**
8275      * Read-only. True if this button is disabled
8276      * @type Boolean
8277      */
8278     disabled : false,
8279     /**
8280      * Read-only. True if this button is pressed (only if enableToggle = true)
8281      * @type Boolean
8282      */
8283     pressed : false,
8284
8285     /**
8286      * @cfg {Number} tabIndex 
8287      * The DOM tabIndex for this button (defaults to undefined)
8288      */
8289     tabIndex : undefined,
8290
8291     /**
8292      * @cfg {Boolean} enableToggle
8293      * True to enable pressed/not pressed toggling (defaults to false)
8294      */
8295     enableToggle: false,
8296     /**
8297      * @cfg {Roo.menu.Menu} menu
8298      * Standard menu attribute consisting of a reference to a menu object, a menu id or a menu config blob (defaults to undefined).
8299      */
8300     menu : undefined,
8301     /**
8302      * @cfg {String} menuAlign
8303      * The position to align the menu to (see {@link Roo.Element#alignTo} for more details, defaults to 'tl-bl?').
8304      */
8305     menuAlign : "tl-bl?",
8306
8307     /**
8308      * @cfg {String} iconCls
8309      * A css class which sets a background image to be used as the icon for this button (defaults to undefined).
8310      */
8311     iconCls : undefined,
8312     /**
8313      * @cfg {String} type
8314      * The button's type, corresponding to the DOM input element type attribute.  Either "submit," "reset" or "button" (default).
8315      */
8316     type : 'button',
8317
8318     // private
8319     menuClassTarget: 'tr',
8320
8321     /**
8322      * @cfg {String} clickEvent
8323      * The type of event to map to the button's event handler (defaults to 'click')
8324      */
8325     clickEvent : 'click',
8326
8327     /**
8328      * @cfg {Boolean} handleMouseEvents
8329      * False to disable visual cues on mouseover, mouseout and mousedown (defaults to true)
8330      */
8331     handleMouseEvents : true,
8332
8333     /**
8334      * @cfg {String} tooltipType
8335      * The type of tooltip to use. Either "qtip" (default) for QuickTips or "title" for title attribute.
8336      */
8337     tooltipType : 'qtip',
8338
8339     /**
8340      * @cfg {String} cls
8341      * A CSS class to apply to the button's main element.
8342      */
8343     
8344     /**
8345      * @cfg {Roo.Template} template (Optional)
8346      * An {@link Roo.Template} with which to create the Button's main element. This Template must
8347      * contain numeric substitution parameter 0 if it is to display the tRoo property. Changing the template could
8348      * require code modifications if required elements (e.g. a button) aren't present.
8349      */
8350
8351     // private
8352     render : function(renderTo){
8353         var btn;
8354         if(this.hideParent){
8355             this.parentEl = Roo.get(renderTo);
8356         }
8357         if(!this.dhconfig){
8358             if(!this.template){
8359                 if(!Roo.Button.buttonTemplate){
8360                     // hideous table template
8361                     Roo.Button.buttonTemplate = new Roo.Template(
8362                         '<table border="0" cellpadding="0" cellspacing="0" class="x-btn-wrap"><tbody><tr>',
8363                         '<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>',
8364                         "</tr></tbody></table>");
8365                 }
8366                 this.template = Roo.Button.buttonTemplate;
8367             }
8368             btn = this.template.append(renderTo, [this.text || '&#160;', this.type], true);
8369             var btnEl = btn.child("button:first");
8370             btnEl.on('focus', this.onFocus, this);
8371             btnEl.on('blur', this.onBlur, this);
8372             if(this.cls){
8373                 btn.addClass(this.cls);
8374             }
8375             if(this.icon){
8376                 btnEl.setStyle('background-image', 'url(' +this.icon +')');
8377             }
8378             if(this.iconCls){
8379                 btnEl.addClass(this.iconCls);
8380                 if(!this.cls){
8381                     btn.addClass(this.text ? 'x-btn-text-icon' : 'x-btn-icon');
8382                 }
8383             }
8384             if(this.tabIndex !== undefined){
8385                 btnEl.dom.tabIndex = this.tabIndex;
8386             }
8387             if(this.tooltip){
8388                 if(typeof this.tooltip == 'object'){
8389                     Roo.QuickTips.tips(Roo.apply({
8390                           target: btnEl.id
8391                     }, this.tooltip));
8392                 } else {
8393                     btnEl.dom[this.tooltipType] = this.tooltip;
8394                 }
8395             }
8396         }else{
8397             btn = Roo.DomHelper.append(Roo.get(renderTo).dom, this.dhconfig, true);
8398         }
8399         this.el = btn;
8400         if(this.id){
8401             this.el.dom.id = this.el.id = this.id;
8402         }
8403         if(this.menu){
8404             this.el.child(this.menuClassTarget).addClass("x-btn-with-menu");
8405             this.menu.on("show", this.onMenuShow, this);
8406             this.menu.on("hide", this.onMenuHide, this);
8407         }
8408         btn.addClass("x-btn");
8409         if(Roo.isIE && !Roo.isIE7){
8410             this.autoWidth.defer(1, this);
8411         }else{
8412             this.autoWidth();
8413         }
8414         if(this.handleMouseEvents){
8415             btn.on("mouseover", this.onMouseOver, this);
8416             btn.on("mouseout", this.onMouseOut, this);
8417             btn.on("mousedown", this.onMouseDown, this);
8418         }
8419         btn.on(this.clickEvent, this.onClick, this);
8420         //btn.on("mouseup", this.onMouseUp, this);
8421         if(this.hidden){
8422             this.hide();
8423         }
8424         if(this.disabled){
8425             this.disable();
8426         }
8427         Roo.ButtonToggleMgr.register(this);
8428         if(this.pressed){
8429             this.el.addClass("x-btn-pressed");
8430         }
8431         if(this.repeat){
8432             var repeater = new Roo.util.ClickRepeater(btn,
8433                 typeof this.repeat == "object" ? this.repeat : {}
8434             );
8435             repeater.on("click", this.onClick,  this);
8436         }
8437         
8438         this.fireEvent('render', this);
8439         
8440     },
8441     /**
8442      * Returns the button's underlying element
8443      * @return {Roo.Element} The element
8444      */
8445     getEl : function(){
8446         return this.el;  
8447     },
8448     
8449     /**
8450      * Destroys this Button and removes any listeners.
8451      */
8452     destroy : function(){
8453         Roo.ButtonToggleMgr.unregister(this);
8454         this.el.removeAllListeners();
8455         this.purgeListeners();
8456         this.el.remove();
8457     },
8458
8459     // private
8460     autoWidth : function(){
8461         if(this.el){
8462             this.el.setWidth("auto");
8463             if(Roo.isIE7 && Roo.isStrict){
8464                 var ib = this.el.child('button');
8465                 if(ib && ib.getWidth() > 20){
8466                     ib.clip();
8467                     ib.setWidth(Roo.util.TextMetrics.measure(ib, this.text).width+ib.getFrameWidth('lr'));
8468                 }
8469             }
8470             if(this.minWidth){
8471                 if(this.hidden){
8472                     this.el.beginMeasure();
8473                 }
8474                 if(this.el.getWidth() < this.minWidth){
8475                     this.el.setWidth(this.minWidth);
8476                 }
8477                 if(this.hidden){
8478                     this.el.endMeasure();
8479                 }
8480             }
8481         }
8482     },
8483
8484     /**
8485      * Assigns this button's click handler
8486      * @param {Function} handler The function to call when the button is clicked
8487      * @param {Object} scope (optional) Scope for the function passed in
8488      */
8489     setHandler : function(handler, scope){
8490         this.handler = handler;
8491         this.scope = scope;  
8492     },
8493     
8494     /**
8495      * Sets this button's text
8496      * @param {String} text The button text
8497      */
8498     setText : function(text){
8499         this.text = text;
8500         if(this.el){
8501             this.el.child("td.x-btn-center button.x-btn-text").update(text);
8502         }
8503         this.autoWidth();
8504     },
8505     
8506     /**
8507      * Gets the text for this button
8508      * @return {String} The button text
8509      */
8510     getText : function(){
8511         return this.text;  
8512     },
8513     
8514     /**
8515      * Show this button
8516      */
8517     show: function(){
8518         this.hidden = false;
8519         if(this.el){
8520             this[this.hideParent? 'parentEl' : 'el'].setStyle("display", "");
8521         }
8522     },
8523     
8524     /**
8525      * Hide this button
8526      */
8527     hide: function(){
8528         this.hidden = true;
8529         if(this.el){
8530             this[this.hideParent? 'parentEl' : 'el'].setStyle("display", "none");
8531         }
8532     },
8533     
8534     /**
8535      * Convenience function for boolean show/hide
8536      * @param {Boolean} visible True to show, false to hide
8537      */
8538     setVisible: function(visible){
8539         if(visible) {
8540             this.show();
8541         }else{
8542             this.hide();
8543         }
8544     },
8545     /**
8546          * Similar to toggle, but does not trigger event.
8547          * @param {Boolean} state [required] Force a particular state
8548          */
8549         setPressed : function(state)
8550         {
8551             if(state != this.pressed){
8552             if(state){
8553                 this.el.addClass("x-btn-pressed");
8554                 this.pressed = true;
8555             }else{
8556                 this.el.removeClass("x-btn-pressed");
8557                 this.pressed = false;
8558             }
8559         }
8560         },
8561         
8562     /**
8563      * If a state it passed, it becomes the pressed state otherwise the current state is toggled.
8564      * @param {Boolean} state (optional) Force a particular state
8565      */
8566     toggle : function(state){
8567         state = state === undefined ? !this.pressed : state;
8568         if(state != this.pressed){
8569             if(state){
8570                 this.el.addClass("x-btn-pressed");
8571                 this.pressed = true;
8572                 this.fireEvent("toggle", this, true);
8573             }else{
8574                 this.el.removeClass("x-btn-pressed");
8575                 this.pressed = false;
8576                 this.fireEvent("toggle", this, false);
8577             }
8578             if(this.toggleHandler){
8579                 this.toggleHandler.call(this.scope || this, this, state);
8580             }
8581         }
8582     },
8583     
8584         
8585         
8586     /**
8587      * Focus the button
8588      */
8589     focus : function(){
8590         this.el.child('button:first').focus();
8591     },
8592     
8593     /**
8594      * Disable this button
8595      */
8596     disable : function(){
8597         if(this.el){
8598             this.el.addClass("x-btn-disabled");
8599         }
8600         this.disabled = true;
8601     },
8602     
8603     /**
8604      * Enable this button
8605      */
8606     enable : function(){
8607         if(this.el){
8608             this.el.removeClass("x-btn-disabled");
8609         }
8610         this.disabled = false;
8611     },
8612
8613     /**
8614      * Convenience function for boolean enable/disable
8615      * @param {Boolean} enabled True to enable, false to disable
8616      */
8617     setDisabled : function(v){
8618         this[v !== true ? "enable" : "disable"]();
8619     },
8620
8621     // private
8622     onClick : function(e)
8623     {
8624         if(e){
8625             e.preventDefault();
8626         }
8627         if(e.button != 0){
8628             return;
8629         }
8630         if(!this.disabled){
8631             if(this.enableToggle){
8632                 this.toggle();
8633             }
8634             if(this.menu && !this.menu.isVisible()){
8635                 this.menu.show(this.el, this.menuAlign);
8636             }
8637             this.fireEvent("click", this, e);
8638             if(this.handler){
8639                 this.el.removeClass("x-btn-over");
8640                 this.handler.call(this.scope || this, this, e);
8641             }
8642         }
8643     },
8644     // private
8645     onMouseOver : function(e){
8646         if(!this.disabled){
8647             this.el.addClass("x-btn-over");
8648             this.fireEvent('mouseover', this, e);
8649         }
8650     },
8651     // private
8652     onMouseOut : function(e){
8653         if(!e.within(this.el,  true)){
8654             this.el.removeClass("x-btn-over");
8655             this.fireEvent('mouseout', this, e);
8656         }
8657     },
8658     // private
8659     onFocus : function(e){
8660         if(!this.disabled){
8661             this.el.addClass("x-btn-focus");
8662         }
8663     },
8664     // private
8665     onBlur : function(e){
8666         this.el.removeClass("x-btn-focus");
8667     },
8668     // private
8669     onMouseDown : function(e){
8670         if(!this.disabled && e.button == 0){
8671             this.el.addClass("x-btn-click");
8672             Roo.get(document).on('mouseup', this.onMouseUp, this);
8673         }
8674     },
8675     // private
8676     onMouseUp : function(e){
8677         if(e.button == 0){
8678             this.el.removeClass("x-btn-click");
8679             Roo.get(document).un('mouseup', this.onMouseUp, this);
8680         }
8681     },
8682     // private
8683     onMenuShow : function(e){
8684         this.el.addClass("x-btn-menu-active");
8685     },
8686     // private
8687     onMenuHide : function(e){
8688         this.el.removeClass("x-btn-menu-active");
8689     }   
8690 });
8691
8692 // Private utility class used by Button
8693 Roo.ButtonToggleMgr = function(){
8694    var groups = {};
8695    
8696    function toggleGroup(btn, state){
8697        if(state){
8698            var g = groups[btn.toggleGroup];
8699            for(var i = 0, l = g.length; i < l; i++){
8700                if(g[i] != btn){
8701                    g[i].toggle(false);
8702                }
8703            }
8704        }
8705    }
8706    
8707    return {
8708        register : function(btn){
8709            if(!btn.toggleGroup){
8710                return;
8711            }
8712            var g = groups[btn.toggleGroup];
8713            if(!g){
8714                g = groups[btn.toggleGroup] = [];
8715            }
8716            g.push(btn);
8717            btn.on("toggle", toggleGroup);
8718        },
8719        
8720        unregister : function(btn){
8721            if(!btn.toggleGroup){
8722                return;
8723            }
8724            var g = groups[btn.toggleGroup];
8725            if(g){
8726                g.remove(btn);
8727                btn.un("toggle", toggleGroup);
8728            }
8729        }
8730    };
8731 }();/*
8732  * Based on:
8733  * Ext JS Library 1.1.1
8734  * Copyright(c) 2006-2007, Ext JS, LLC.
8735  *
8736  * Originally Released Under LGPL - original licence link has changed is not relivant.
8737  *
8738  * Fork - LGPL
8739  * <script type="text/javascript">
8740  */
8741  
8742 /**
8743  * @class Roo.SplitButton
8744  * @extends Roo.Button
8745  * A split button that provides a built-in dropdown arrow that can fire an event separately from the default
8746  * click event of the button.  Typically this would be used to display a dropdown menu that provides additional
8747  * options to the primary button action, but any custom handler can provide the arrowclick implementation.
8748  * @cfg {Function} arrowHandler A function called when the arrow button is clicked (can be used instead of click event)
8749  * @cfg {String} arrowTooltip The title attribute of the arrow
8750  * @constructor
8751  * Create a new menu button
8752  * @param {String/HTMLElement/Element} renderTo The element to append the button to
8753  * @param {Object} config The config object
8754  */
8755 Roo.SplitButton = function(renderTo, config){
8756     Roo.SplitButton.superclass.constructor.call(this, renderTo, config);
8757     /**
8758      * @event arrowclick
8759      * Fires when this button's arrow is clicked
8760      * @param {SplitButton} this
8761      * @param {EventObject} e The click event
8762      */
8763     this.addEvents({"arrowclick":true});
8764 };
8765
8766 Roo.extend(Roo.SplitButton, Roo.Button, {
8767     render : function(renderTo){
8768         // this is one sweet looking template!
8769         var tpl = new Roo.Template(
8770             '<table cellspacing="0" class="x-btn-menu-wrap x-btn"><tr><td>',
8771             '<table cellspacing="0" class="x-btn-wrap x-btn-menu-text-wrap"><tbody>',
8772             '<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>',
8773             "</tbody></table></td><td>",
8774             '<table cellspacing="0" class="x-btn-wrap x-btn-menu-arrow-wrap"><tbody>',
8775             '<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>',
8776             "</tbody></table></td></tr></table>"
8777         );
8778         var btn = tpl.append(renderTo, [this.text, this.type], true);
8779         var btnEl = btn.child("button");
8780         if(this.cls){
8781             btn.addClass(this.cls);
8782         }
8783         if(this.icon){
8784             btnEl.setStyle('background-image', 'url(' +this.icon +')');
8785         }
8786         if(this.iconCls){
8787             btnEl.addClass(this.iconCls);
8788             if(!this.cls){
8789                 btn.addClass(this.text ? 'x-btn-text-icon' : 'x-btn-icon');
8790             }
8791         }
8792         this.el = btn;
8793         if(this.handleMouseEvents){
8794             btn.on("mouseover", this.onMouseOver, this);
8795             btn.on("mouseout", this.onMouseOut, this);
8796             btn.on("mousedown", this.onMouseDown, this);
8797             btn.on("mouseup", this.onMouseUp, this);
8798         }
8799         btn.on(this.clickEvent, this.onClick, this);
8800         if(this.tooltip){
8801             if(typeof this.tooltip == 'object'){
8802                 Roo.QuickTips.tips(Roo.apply({
8803                       target: btnEl.id
8804                 }, this.tooltip));
8805             } else {
8806                 btnEl.dom[this.tooltipType] = this.tooltip;
8807             }
8808         }
8809         if(this.arrowTooltip){
8810             btn.child("button:nth(2)").dom[this.tooltipType] = this.arrowTooltip;
8811         }
8812         if(this.hidden){
8813             this.hide();
8814         }
8815         if(this.disabled){
8816             this.disable();
8817         }
8818         if(this.pressed){
8819             this.el.addClass("x-btn-pressed");
8820         }
8821         if(Roo.isIE && !Roo.isIE7){
8822             this.autoWidth.defer(1, this);
8823         }else{
8824             this.autoWidth();
8825         }
8826         if(this.menu){
8827             this.menu.on("show", this.onMenuShow, this);
8828             this.menu.on("hide", this.onMenuHide, this);
8829         }
8830         this.fireEvent('render', this);
8831     },
8832
8833     // private
8834     autoWidth : function(){
8835         if(this.el){
8836             var tbl = this.el.child("table:first");
8837             var tbl2 = this.el.child("table:last");
8838             this.el.setWidth("auto");
8839             tbl.setWidth("auto");
8840             if(Roo.isIE7 && Roo.isStrict){
8841                 var ib = this.el.child('button:first');
8842                 if(ib && ib.getWidth() > 20){
8843                     ib.clip();
8844                     ib.setWidth(Roo.util.TextMetrics.measure(ib, this.text).width+ib.getFrameWidth('lr'));
8845                 }
8846             }
8847             if(this.minWidth){
8848                 if(this.hidden){
8849                     this.el.beginMeasure();
8850                 }
8851                 if((tbl.getWidth()+tbl2.getWidth()) < this.minWidth){
8852                     tbl.setWidth(this.minWidth-tbl2.getWidth());
8853                 }
8854                 if(this.hidden){
8855                     this.el.endMeasure();
8856                 }
8857             }
8858             this.el.setWidth(tbl.getWidth()+tbl2.getWidth());
8859         } 
8860     },
8861     /**
8862      * Sets this button's click handler
8863      * @param {Function} handler The function to call when the button is clicked
8864      * @param {Object} scope (optional) Scope for the function passed above
8865      */
8866     setHandler : function(handler, scope){
8867         this.handler = handler;
8868         this.scope = scope;  
8869     },
8870     
8871     /**
8872      * Sets this button's arrow click handler
8873      * @param {Function} handler The function to call when the arrow is clicked
8874      * @param {Object} scope (optional) Scope for the function passed above
8875      */
8876     setArrowHandler : function(handler, scope){
8877         this.arrowHandler = handler;
8878         this.scope = scope;  
8879     },
8880     
8881     /**
8882      * Focus the button
8883      */
8884     focus : function(){
8885         if(this.el){
8886             this.el.child("button:first").focus();
8887         }
8888     },
8889
8890     // private
8891     onClick : function(e){
8892         e.preventDefault();
8893         if(!this.disabled){
8894             if(e.getTarget(".x-btn-menu-arrow-wrap")){
8895                 if(this.menu && !this.menu.isVisible()){
8896                     this.menu.show(this.el, this.menuAlign);
8897                 }
8898                 this.fireEvent("arrowclick", this, e);
8899                 if(this.arrowHandler){
8900                     this.arrowHandler.call(this.scope || this, this, e);
8901                 }
8902             }else{
8903                 this.fireEvent("click", this, e);
8904                 if(this.handler){
8905                     this.handler.call(this.scope || this, this, e);
8906                 }
8907             }
8908         }
8909     },
8910     // private
8911     onMouseDown : function(e){
8912         if(!this.disabled){
8913             Roo.fly(e.getTarget("table")).addClass("x-btn-click");
8914         }
8915     },
8916     // private
8917     onMouseUp : function(e){
8918         Roo.fly(e.getTarget("table")).removeClass("x-btn-click");
8919     }   
8920 });
8921
8922
8923 // backwards compat
8924 Roo.MenuButton = Roo.SplitButton;/*
8925  * Based on:
8926  * Ext JS Library 1.1.1
8927  * Copyright(c) 2006-2007, Ext JS, LLC.
8928  *
8929  * Originally Released Under LGPL - original licence link has changed is not relivant.
8930  *
8931  * Fork - LGPL
8932  * <script type="text/javascript">
8933  */
8934
8935 /**
8936  * @class Roo.Toolbar
8937  * @children   Roo.Toolbar.Item Roo.Toolbar.Button Roo.Toolbar.SplitButton Roo.form.Field 
8938  * Basic Toolbar class.
8939  * @constructor
8940  * Creates a new Toolbar
8941  * @param {Object} container The config object
8942  */ 
8943 Roo.Toolbar = function(container, buttons, config)
8944 {
8945     /// old consturctor format still supported..
8946     if(container instanceof Array){ // omit the container for later rendering
8947         buttons = container;
8948         config = buttons;
8949         container = null;
8950     }
8951     if (typeof(container) == 'object' && container.xtype) {
8952         config = container;
8953         container = config.container;
8954         buttons = config.buttons || []; // not really - use items!!
8955     }
8956     var xitems = [];
8957     if (config && config.items) {
8958         xitems = config.items;
8959         delete config.items;
8960     }
8961     Roo.apply(this, config);
8962     this.buttons = buttons;
8963     
8964     if(container){
8965         this.render(container);
8966     }
8967     this.xitems = xitems;
8968     Roo.each(xitems, function(b) {
8969         this.add(b);
8970     }, this);
8971     
8972 };
8973
8974 Roo.Toolbar.prototype = {
8975     /**
8976      * @cfg {Array} items
8977      * array of button configs or elements to add (will be converted to a MixedCollection)
8978      */
8979     items: false,
8980     /**
8981      * @cfg {String/HTMLElement/Element} container
8982      * The id or element that will contain the toolbar
8983      */
8984     // private
8985     render : function(ct){
8986         this.el = Roo.get(ct);
8987         if(this.cls){
8988             this.el.addClass(this.cls);
8989         }
8990         // using a table allows for vertical alignment
8991         // 100% width is needed by Safari...
8992         this.el.update('<div class="x-toolbar x-small-editor"><table cellspacing="0"><tr></tr></table></div>');
8993         this.tr = this.el.child("tr", true);
8994         var autoId = 0;
8995         this.items = new Roo.util.MixedCollection(false, function(o){
8996             return o.id || ("item" + (++autoId));
8997         });
8998         if(this.buttons){
8999             this.add.apply(this, this.buttons);
9000             delete this.buttons;
9001         }
9002     },
9003
9004     /**
9005      * Adds element(s) to the toolbar -- this function takes a variable number of 
9006      * arguments of mixed type and adds them to the toolbar.
9007      * @param {Mixed} arg1 The following types of arguments are all valid:<br />
9008      * <ul>
9009      * <li>{@link Roo.Toolbar.Button} config: A valid button config object (equivalent to {@link #addButton})</li>
9010      * <li>HtmlElement: Any standard HTML element (equivalent to {@link #addElement})</li>
9011      * <li>Field: Any form field (equivalent to {@link #addField})</li>
9012      * <li>Item: Any subclass of {@link Roo.Toolbar.Item} (equivalent to {@link #addItem})</li>
9013      * <li>String: Any generic string (gets wrapped in a {@link Roo.Toolbar.TextItem}, equivalent to {@link #addText}).
9014      * Note that there are a few special strings that are treated differently as explained nRoo.</li>
9015      * <li>'separator' or '-': Creates a separator element (equivalent to {@link #addSeparator})</li>
9016      * <li>' ': Creates a spacer element (equivalent to {@link #addSpacer})</li>
9017      * <li>'->': Creates a fill element (equivalent to {@link #addFill})</li>
9018      * </ul>
9019      * @param {Mixed} arg2
9020      * @param {Mixed} etc.
9021      */
9022     add : function(){
9023         var a = arguments, l = a.length;
9024         for(var i = 0; i < l; i++){
9025             this._add(a[i]);
9026         }
9027     },
9028     // private..
9029     _add : function(el) {
9030         
9031         if (el.xtype) {
9032             el = Roo.factory(el, typeof(Roo.Toolbar[el.xtype]) == 'undefined' ? Roo.form : Roo.Toolbar);
9033         }
9034         
9035         if (el.applyTo){ // some kind of form field
9036             return this.addField(el);
9037         } 
9038         if (el.render){ // some kind of Toolbar.Item
9039             return this.addItem(el);
9040         }
9041         if (typeof el == "string"){ // string
9042             if(el == "separator" || el == "-"){
9043                 return this.addSeparator();
9044             }
9045             if (el == " "){
9046                 return this.addSpacer();
9047             }
9048             if(el == "->"){
9049                 return this.addFill();
9050             }
9051             return this.addText(el);
9052             
9053         }
9054         if(el.tagName){ // element
9055             return this.addElement(el);
9056         }
9057         if(typeof el == "object"){ // must be button config?
9058             return this.addButton(el);
9059         }
9060         // and now what?!?!
9061         return false;
9062         
9063     },
9064     
9065     /**
9066      * Add an Xtype element
9067      * @param {Object} xtype Xtype Object
9068      * @return {Object} created Object
9069      */
9070     addxtype : function(e){
9071         return this.add(e);  
9072     },
9073     
9074     /**
9075      * Returns the Element for this toolbar.
9076      * @return {Roo.Element}
9077      */
9078     getEl : function(){
9079         return this.el;  
9080     },
9081     
9082     /**
9083      * Adds a separator
9084      * @return {Roo.Toolbar.Item} The separator item
9085      */
9086     addSeparator : function(){
9087         return this.addItem(new Roo.Toolbar.Separator());
9088     },
9089
9090     /**
9091      * Adds a spacer element
9092      * @return {Roo.Toolbar.Spacer} The spacer item
9093      */
9094     addSpacer : function(){
9095         return this.addItem(new Roo.Toolbar.Spacer());
9096     },
9097
9098     /**
9099      * Adds a fill element that forces subsequent additions to the right side of the toolbar
9100      * @return {Roo.Toolbar.Fill} The fill item
9101      */
9102     addFill : function(){
9103         return this.addItem(new Roo.Toolbar.Fill());
9104     },
9105
9106     /**
9107      * Adds any standard HTML element to the toolbar
9108      * @param {String/HTMLElement/Element} el The element or id of the element to add
9109      * @return {Roo.Toolbar.Item} The element's item
9110      */
9111     addElement : function(el){
9112         return this.addItem(new Roo.Toolbar.Item(el));
9113     },
9114     /**
9115      * Collection of items on the toolbar.. (only Toolbar Items, so use fields to retrieve fields)
9116      * @type Roo.util.MixedCollection  
9117      */
9118     items : false,
9119      
9120     /**
9121      * Adds any Toolbar.Item or subclass
9122      * @param {Roo.Toolbar.Item} item
9123      * @return {Roo.Toolbar.Item} The item
9124      */
9125     addItem : function(item){
9126         var td = this.nextBlock();
9127         item.render(td);
9128         this.items.add(item);
9129         return item;
9130     },
9131     
9132     /**
9133      * Adds a button (or buttons). See {@link Roo.Toolbar.Button} for more info on the config.
9134      * @param {Object/Array} config A button config or array of configs
9135      * @return {Roo.Toolbar.Button/Array}
9136      */
9137     addButton : function(config){
9138         if(config instanceof Array){
9139             var buttons = [];
9140             for(var i = 0, len = config.length; i < len; i++) {
9141                 buttons.push(this.addButton(config[i]));
9142             }
9143             return buttons;
9144         }
9145         var b = config;
9146         if(!(config instanceof Roo.Toolbar.Button)){
9147             b = config.split ?
9148                 new Roo.Toolbar.SplitButton(config) :
9149                 new Roo.Toolbar.Button(config);
9150         }
9151         var td = this.nextBlock();
9152         b.render(td);
9153         this.items.add(b);
9154         return b;
9155     },
9156     
9157     /**
9158      * Adds text to the toolbar
9159      * @param {String} text The text to add
9160      * @return {Roo.Toolbar.Item} The element's item
9161      */
9162     addText : function(text){
9163         return this.addItem(new Roo.Toolbar.TextItem(text));
9164     },
9165     
9166     /**
9167      * Inserts any {@link Roo.Toolbar.Item}/{@link Roo.Toolbar.Button} at the specified index.
9168      * @param {Number} index The index where the item is to be inserted
9169      * @param {Object/Roo.Toolbar.Item/Roo.Toolbar.Button (may be Array)} item The button, or button config object to be inserted.
9170      * @return {Roo.Toolbar.Button/Item}
9171      */
9172     insertButton : function(index, item){
9173         if(item instanceof Array){
9174             var buttons = [];
9175             for(var i = 0, len = item.length; i < len; i++) {
9176                buttons.push(this.insertButton(index + i, item[i]));
9177             }
9178             return buttons;
9179         }
9180         if (!(item instanceof Roo.Toolbar.Button)){
9181            item = new Roo.Toolbar.Button(item);
9182         }
9183         var td = document.createElement("td");
9184         this.tr.insertBefore(td, this.tr.childNodes[index]);
9185         item.render(td);
9186         this.items.insert(index, item);
9187         return item;
9188     },
9189     
9190     /**
9191      * Adds a new element to the toolbar from the passed {@link Roo.DomHelper} config.
9192      * @param {Object} config
9193      * @return {Roo.Toolbar.Item} The element's item
9194      */
9195     addDom : function(config, returnEl){
9196         var td = this.nextBlock();
9197         Roo.DomHelper.overwrite(td, config);
9198         var ti = new Roo.Toolbar.Item(td.firstChild);
9199         ti.render(td);
9200         this.items.add(ti);
9201         return ti;
9202     },
9203
9204     /**
9205      * Collection of fields on the toolbar.. usefull for quering (value is false if there are no fields)
9206      * @type Roo.util.MixedCollection  
9207      */
9208     fields : false,
9209     
9210     /**
9211      * Adds a dynamically rendered Roo.form field (TextField, ComboBox, etc).
9212      * Note: the field should not have been rendered yet. For a field that has already been
9213      * rendered, use {@link #addElement}.
9214      * @param {Roo.form.Field} field
9215      * @return {Roo.ToolbarItem}
9216      */
9217      
9218       
9219     addField : function(field) {
9220         if (!this.fields) {
9221             var autoId = 0;
9222             this.fields = new Roo.util.MixedCollection(false, function(o){
9223                 return o.id || ("item" + (++autoId));
9224             });
9225
9226         }
9227         
9228         var td = this.nextBlock();
9229         field.render(td);
9230         var ti = new Roo.Toolbar.Item(td.firstChild);
9231         ti.render(td);
9232         this.items.add(ti);
9233         this.fields.add(field);
9234         return ti;
9235     },
9236     /**
9237      * Hide the toolbar
9238      * @method hide
9239      */
9240      
9241       
9242     hide : function()
9243     {
9244         this.el.child('div').setVisibilityMode(Roo.Element.DISPLAY);
9245         this.el.child('div').hide();
9246     },
9247     /**
9248      * Show the toolbar
9249      * @method show
9250      */
9251     show : function()
9252     {
9253         this.el.child('div').show();
9254     },
9255       
9256     // private
9257     nextBlock : function(){
9258         var td = document.createElement("td");
9259         this.tr.appendChild(td);
9260         return td;
9261     },
9262
9263     // private
9264     destroy : function(){
9265         if(this.items){ // rendered?
9266             Roo.destroy.apply(Roo, this.items.items);
9267         }
9268         if(this.fields){ // rendered?
9269             Roo.destroy.apply(Roo, this.fields.items);
9270         }
9271         Roo.Element.uncache(this.el, this.tr);
9272     }
9273 };
9274
9275 /**
9276  * @class Roo.Toolbar.Item
9277  * The base class that other classes should extend in order to get some basic common toolbar item functionality.
9278  * @constructor
9279  * Creates a new Item
9280  * @param {HTMLElement} el 
9281  */
9282 Roo.Toolbar.Item = function(el){
9283     var cfg = {};
9284     if (typeof (el.xtype) != 'undefined') {
9285         cfg = el;
9286         el = cfg.el;
9287     }
9288     
9289     this.el = Roo.getDom(el);
9290     this.id = Roo.id(this.el);
9291     this.hidden = false;
9292     
9293     this.addEvents({
9294          /**
9295              * @event render
9296              * Fires when the button is rendered
9297              * @param {Button} this
9298              */
9299         'render': true
9300     });
9301     Roo.Toolbar.Item.superclass.constructor.call(this,cfg);
9302 };
9303 Roo.extend(Roo.Toolbar.Item, Roo.util.Observable, {
9304 //Roo.Toolbar.Item.prototype = {
9305     
9306     /**
9307      * Get this item's HTML Element
9308      * @return {HTMLElement}
9309      */
9310     getEl : function(){
9311        return this.el;  
9312     },
9313
9314     // private
9315     render : function(td){
9316         
9317          this.td = td;
9318         td.appendChild(this.el);
9319         
9320         this.fireEvent('render', this);
9321     },
9322     
9323     /**
9324      * Removes and destroys this item.
9325      */
9326     destroy : function(){
9327         this.td.parentNode.removeChild(this.td);
9328     },
9329     
9330     /**
9331      * Shows this item.
9332      */
9333     show: function(){
9334         this.hidden = false;
9335         this.td.style.display = "";
9336     },
9337     
9338     /**
9339      * Hides this item.
9340      */
9341     hide: function(){
9342         this.hidden = true;
9343         this.td.style.display = "none";
9344     },
9345     
9346     /**
9347      * Convenience function for boolean show/hide.
9348      * @param {Boolean} visible true to show/false to hide
9349      */
9350     setVisible: function(visible){
9351         if(visible) {
9352             this.show();
9353         }else{
9354             this.hide();
9355         }
9356     },
9357     
9358     /**
9359      * Try to focus this item.
9360      */
9361     focus : function(){
9362         Roo.fly(this.el).focus();
9363     },
9364     
9365     /**
9366      * Disables this item.
9367      */
9368     disable : function(){
9369         Roo.fly(this.td).addClass("x-item-disabled");
9370         this.disabled = true;
9371         this.el.disabled = true;
9372     },
9373     
9374     /**
9375      * Enables this item.
9376      */
9377     enable : function(){
9378         Roo.fly(this.td).removeClass("x-item-disabled");
9379         this.disabled = false;
9380         this.el.disabled = false;
9381     }
9382 });
9383
9384
9385 /**
9386  * @class Roo.Toolbar.Separator
9387  * @extends Roo.Toolbar.Item
9388  * A simple toolbar separator class
9389  * @constructor
9390  * Creates a new Separator
9391  */
9392 Roo.Toolbar.Separator = function(cfg){
9393     
9394     var s = document.createElement("span");
9395     s.className = "ytb-sep";
9396     if (cfg) {
9397         cfg.el = s;
9398     }
9399     
9400     Roo.Toolbar.Separator.superclass.constructor.call(this, cfg || s);
9401 };
9402 Roo.extend(Roo.Toolbar.Separator, Roo.Toolbar.Item, {
9403     enable:Roo.emptyFn,
9404     disable:Roo.emptyFn,
9405     focus:Roo.emptyFn
9406 });
9407
9408 /**
9409  * @class Roo.Toolbar.Spacer
9410  * @extends Roo.Toolbar.Item
9411  * A simple element that adds extra horizontal space to a toolbar.
9412  * @constructor
9413  * Creates a new Spacer
9414  */
9415 Roo.Toolbar.Spacer = function(cfg){
9416     var s = document.createElement("div");
9417     s.className = "ytb-spacer";
9418     if (cfg) {
9419         cfg.el = s;
9420     }
9421     Roo.Toolbar.Spacer.superclass.constructor.call(this, cfg || s);
9422 };
9423 Roo.extend(Roo.Toolbar.Spacer, Roo.Toolbar.Item, {
9424     enable:Roo.emptyFn,
9425     disable:Roo.emptyFn,
9426     focus:Roo.emptyFn
9427 });
9428
9429 /**
9430  * @class Roo.Toolbar.Fill
9431  * @extends Roo.Toolbar.Spacer
9432  * A simple element that adds a greedy (100% width) horizontal space to a toolbar.
9433  * @constructor
9434  * Creates a new Spacer
9435  */
9436 Roo.Toolbar.Fill = Roo.extend(Roo.Toolbar.Spacer, {
9437     // private
9438     render : function(td){
9439         td.style.width = '100%';
9440         Roo.Toolbar.Fill.superclass.render.call(this, td);
9441     }
9442 });
9443
9444 /**
9445  * @class Roo.Toolbar.TextItem
9446  * @extends Roo.Toolbar.Item
9447  * A simple class that renders text directly into a toolbar.
9448  * @constructor
9449  * Creates a new TextItem
9450  * @cfg {string} text 
9451  */
9452 Roo.Toolbar.TextItem = function(cfg){
9453     var  text = cfg || "";
9454     if (typeof(cfg) == 'object') {
9455         text = cfg.text || "";
9456     }  else {
9457         cfg = null;
9458     }
9459     var s = document.createElement("span");
9460     s.className = "ytb-text";
9461     s.innerHTML = text;
9462     if (cfg) {
9463         cfg.el  = s;
9464     }
9465     
9466     Roo.Toolbar.TextItem.superclass.constructor.call(this, cfg ||  s);
9467 };
9468 Roo.extend(Roo.Toolbar.TextItem, Roo.Toolbar.Item, {
9469     
9470      
9471     enable:Roo.emptyFn,
9472     disable:Roo.emptyFn,
9473     focus:Roo.emptyFn,
9474      /**
9475      * Shows this button
9476      */
9477     show: function(){
9478         this.hidden = false;
9479         this.el.style.display = "";
9480     },
9481     
9482     /**
9483      * Hides this button
9484      */
9485     hide: function(){
9486         this.hidden = true;
9487         this.el.style.display = "none";
9488     }
9489     
9490 });
9491
9492 /**
9493  * @class Roo.Toolbar.Button
9494  * @extends Roo.Button
9495  * A button that renders into a toolbar.
9496  * @constructor
9497  * Creates a new Button
9498  * @param {Object} config A standard {@link Roo.Button} config object
9499  */
9500 Roo.Toolbar.Button = function(config){
9501     Roo.Toolbar.Button.superclass.constructor.call(this, null, config);
9502 };
9503 Roo.extend(Roo.Toolbar.Button, Roo.Button,
9504 {
9505     
9506     
9507     render : function(td){
9508         this.td = td;
9509         Roo.Toolbar.Button.superclass.render.call(this, td);
9510     },
9511     
9512     /**
9513      * Removes and destroys this button
9514      */
9515     destroy : function(){
9516         Roo.Toolbar.Button.superclass.destroy.call(this);
9517         this.td.parentNode.removeChild(this.td);
9518     },
9519     
9520     /**
9521      * Shows this button
9522      */
9523     show: function(){
9524         this.hidden = false;
9525         this.td.style.display = "";
9526     },
9527     
9528     /**
9529      * Hides this button
9530      */
9531     hide: function(){
9532         this.hidden = true;
9533         this.td.style.display = "none";
9534     },
9535
9536     /**
9537      * Disables this item
9538      */
9539     disable : function(){
9540         Roo.fly(this.td).addClass("x-item-disabled");
9541         this.disabled = true;
9542     },
9543
9544     /**
9545      * Enables this item
9546      */
9547     enable : function(){
9548         Roo.fly(this.td).removeClass("x-item-disabled");
9549         this.disabled = false;
9550     }
9551 });
9552 // backwards compat
9553 Roo.ToolbarButton = Roo.Toolbar.Button;
9554
9555 /**
9556  * @class Roo.Toolbar.SplitButton
9557  * @extends Roo.SplitButton
9558  * A menu button that renders into a toolbar.
9559  * @constructor
9560  * Creates a new SplitButton
9561  * @param {Object} config A standard {@link Roo.SplitButton} config object
9562  */
9563 Roo.Toolbar.SplitButton = function(config){
9564     Roo.Toolbar.SplitButton.superclass.constructor.call(this, null, config);
9565 };
9566 Roo.extend(Roo.Toolbar.SplitButton, Roo.SplitButton, {
9567     render : function(td){
9568         this.td = td;
9569         Roo.Toolbar.SplitButton.superclass.render.call(this, td);
9570     },
9571     
9572     /**
9573      * Removes and destroys this button
9574      */
9575     destroy : function(){
9576         Roo.Toolbar.SplitButton.superclass.destroy.call(this);
9577         this.td.parentNode.removeChild(this.td);
9578     },
9579     
9580     /**
9581      * Shows this button
9582      */
9583     show: function(){
9584         this.hidden = false;
9585         this.td.style.display = "";
9586     },
9587     
9588     /**
9589      * Hides this button
9590      */
9591     hide: function(){
9592         this.hidden = true;
9593         this.td.style.display = "none";
9594     }
9595 });
9596
9597 // backwards compat
9598 Roo.Toolbar.MenuButton = Roo.Toolbar.SplitButton;/*
9599  * Based on:
9600  * Ext JS Library 1.1.1
9601  * Copyright(c) 2006-2007, Ext JS, LLC.
9602  *
9603  * Originally Released Under LGPL - original licence link has changed is not relivant.
9604  *
9605  * Fork - LGPL
9606  * <script type="text/javascript">
9607  */
9608  
9609 /**
9610  * @class Roo.PagingToolbar
9611  * @extends Roo.Toolbar
9612  * @children   Roo.Toolbar.Item Roo.Toolbar.Button Roo.Toolbar.SplitButton Roo.form.Field
9613  * A specialized toolbar that is bound to a {@link Roo.data.Store} and provides automatic paging controls.
9614  * @constructor
9615  * Create a new PagingToolbar
9616  * @param {Object} config The config object
9617  */
9618 Roo.PagingToolbar = function(el, ds, config)
9619 {
9620     // old args format still supported... - xtype is prefered..
9621     if (typeof(el) == 'object' && el.xtype) {
9622         // created from xtype...
9623         config = el;
9624         ds = el.dataSource;
9625         el = config.container;
9626     }
9627     var items = [];
9628     if (config.items) {
9629         items = config.items;
9630         config.items = [];
9631     }
9632     
9633     Roo.PagingToolbar.superclass.constructor.call(this, el, null, config);
9634     this.ds = ds;
9635     this.cursor = 0;
9636     this.renderButtons(this.el);
9637     this.bind(ds);
9638     
9639     // supprot items array.
9640    
9641     Roo.each(items, function(e) {
9642         this.add(Roo.factory(e));
9643     },this);
9644     
9645 };
9646
9647 Roo.extend(Roo.PagingToolbar, Roo.Toolbar, {
9648    
9649     /**
9650      * @cfg {String/HTMLElement/Element} container
9651      * container The id or element that will contain the toolbar
9652      */
9653     /**
9654      * @cfg {Boolean} displayInfo
9655      * True to display the displayMsg (defaults to false)
9656      */
9657     
9658     
9659     /**
9660      * @cfg {Number} pageSize
9661      * The number of records to display per page (defaults to 20)
9662      */
9663     pageSize: 20,
9664     /**
9665      * @cfg {String} displayMsg
9666      * The paging status message to display (defaults to "Displaying {start} - {end} of {total}")
9667      */
9668     displayMsg : 'Displaying {0} - {1} of {2}',
9669     /**
9670      * @cfg {String} emptyMsg
9671      * The message to display when no records are found (defaults to "No data to display")
9672      */
9673     emptyMsg : 'No data to display',
9674     /**
9675      * Customizable piece of the default paging text (defaults to "Page")
9676      * @type String
9677      */
9678     beforePageText : "Page",
9679     /**
9680      * Customizable piece of the default paging text (defaults to "of %0")
9681      * @type String
9682      */
9683     afterPageText : "of {0}",
9684     /**
9685      * Customizable piece of the default paging text (defaults to "First Page")
9686      * @type String
9687      */
9688     firstText : "First Page",
9689     /**
9690      * Customizable piece of the default paging text (defaults to "Previous Page")
9691      * @type String
9692      */
9693     prevText : "Previous Page",
9694     /**
9695      * Customizable piece of the default paging text (defaults to "Next Page")
9696      * @type String
9697      */
9698     nextText : "Next Page",
9699     /**
9700      * Customizable piece of the default paging text (defaults to "Last Page")
9701      * @type String
9702      */
9703     lastText : "Last Page",
9704     /**
9705      * Customizable piece of the default paging text (defaults to "Refresh")
9706      * @type String
9707      */
9708     refreshText : "Refresh",
9709
9710     // private
9711     renderButtons : function(el){
9712         Roo.PagingToolbar.superclass.render.call(this, el);
9713         this.first = this.addButton({
9714             tooltip: this.firstText,
9715             cls: "x-btn-icon x-grid-page-first",
9716             disabled: true,
9717             handler: this.onClick.createDelegate(this, ["first"])
9718         });
9719         this.prev = this.addButton({
9720             tooltip: this.prevText,
9721             cls: "x-btn-icon x-grid-page-prev",
9722             disabled: true,
9723             handler: this.onClick.createDelegate(this, ["prev"])
9724         });
9725         //this.addSeparator();
9726         this.add(this.beforePageText);
9727         this.field = Roo.get(this.addDom({
9728            tag: "input",
9729            type: "text",
9730            size: "3",
9731            value: "1",
9732            cls: "x-grid-page-number"
9733         }).el);
9734         this.field.on("keydown", this.onPagingKeydown, this);
9735         this.field.on("focus", function(){this.dom.select();});
9736         this.afterTextEl = this.addText(String.format(this.afterPageText, 1));
9737         this.field.setHeight(18);
9738         //this.addSeparator();
9739         this.next = this.addButton({
9740             tooltip: this.nextText,
9741             cls: "x-btn-icon x-grid-page-next",
9742             disabled: true,
9743             handler: this.onClick.createDelegate(this, ["next"])
9744         });
9745         this.last = this.addButton({
9746             tooltip: this.lastText,
9747             cls: "x-btn-icon x-grid-page-last",
9748             disabled: true,
9749             handler: this.onClick.createDelegate(this, ["last"])
9750         });
9751         //this.addSeparator();
9752         this.loading = this.addButton({
9753             tooltip: this.refreshText,
9754             cls: "x-btn-icon x-grid-loading",
9755             handler: this.onClick.createDelegate(this, ["refresh"])
9756         });
9757
9758         if(this.displayInfo){
9759             this.displayEl = Roo.fly(this.el.dom.firstChild).createChild({cls:'x-paging-info'});
9760         }
9761     },
9762
9763     // private
9764     updateInfo : function(){
9765         if(this.displayEl){
9766             var count = this.ds.getCount();
9767             var msg = count == 0 ?
9768                 this.emptyMsg :
9769                 String.format(
9770                     this.displayMsg,
9771                     this.cursor+1, this.cursor+count, this.ds.getTotalCount()    
9772                 );
9773             this.displayEl.update(msg);
9774         }
9775     },
9776
9777     // private
9778     onLoad : function(ds, r, o){
9779        this.cursor = o.params ? o.params.start : 0;
9780        var d = this.getPageData(), ap = d.activePage, ps = d.pages;
9781
9782        this.afterTextEl.el.innerHTML = String.format(this.afterPageText, d.pages);
9783        this.field.dom.value = ap;
9784        this.first.setDisabled(ap == 1);
9785        this.prev.setDisabled(ap == 1);
9786        this.next.setDisabled(ap == ps);
9787        this.last.setDisabled(ap == ps);
9788        this.loading.enable();
9789        this.updateInfo();
9790     },
9791
9792     // private
9793     getPageData : function(){
9794         var total = this.ds.getTotalCount();
9795         return {
9796             total : total,
9797             activePage : Math.ceil((this.cursor+this.pageSize)/this.pageSize),
9798             pages :  total < this.pageSize ? 1 : Math.ceil(total/this.pageSize)
9799         };
9800     },
9801
9802     // private
9803     onLoadError : function(){
9804         this.loading.enable();
9805     },
9806
9807     // private
9808     onPagingKeydown : function(e){
9809         var k = e.getKey();
9810         var d = this.getPageData();
9811         if(k == e.RETURN){
9812             var v = this.field.dom.value, pageNum;
9813             if(!v || isNaN(pageNum = parseInt(v, 10))){
9814                 this.field.dom.value = d.activePage;
9815                 return;
9816             }
9817             pageNum = Math.min(Math.max(1, pageNum), d.pages) - 1;
9818             this.ds.load({params:{start: pageNum * this.pageSize, limit: this.pageSize}});
9819             e.stopEvent();
9820         }
9821         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))
9822         {
9823           var pageNum = (k == e.HOME || (k == e.DOWN && e.ctrlKey) || (k == e.LEFT && e.ctrlKey) || (k == e.PAGEDOWN && e.ctrlKey)) ? 1 : d.pages;
9824           this.field.dom.value = pageNum;
9825           this.ds.load({params:{start: (pageNum - 1) * this.pageSize, limit: this.pageSize}});
9826           e.stopEvent();
9827         }
9828         else if(k == e.UP || k == e.RIGHT || k == e.PAGEUP || k == e.DOWN || k == e.LEFT || k == e.PAGEDOWN)
9829         {
9830           var v = this.field.dom.value, pageNum; 
9831           var increment = (e.shiftKey) ? 10 : 1;
9832           if(k == e.DOWN || k == e.LEFT || k == e.PAGEDOWN) {
9833             increment *= -1;
9834           }
9835           if(!v || isNaN(pageNum = parseInt(v, 10))) {
9836             this.field.dom.value = d.activePage;
9837             return;
9838           }
9839           else if(parseInt(v, 10) + increment >= 1 & parseInt(v, 10) + increment <= d.pages)
9840           {
9841             this.field.dom.value = parseInt(v, 10) + increment;
9842             pageNum = Math.min(Math.max(1, pageNum + increment), d.pages) - 1;
9843             this.ds.load({params:{start: pageNum * this.pageSize, limit: this.pageSize}});
9844           }
9845           e.stopEvent();
9846         }
9847     },
9848
9849     // private
9850     beforeLoad : function(){
9851         if(this.loading){
9852             this.loading.disable();
9853         }
9854     },
9855     /**
9856      * event that occurs when you click on the navigation buttons - can be used to trigger load of a grid.
9857      * @param {String} which (first|prev|next|last|refresh)  which button to press.
9858      *
9859      */
9860     // private
9861     onClick : function(which){
9862         var ds = this.ds;
9863         switch(which){
9864             case "first":
9865                 ds.load({params:{start: 0, limit: this.pageSize}});
9866             break;
9867             case "prev":
9868                 ds.load({params:{start: Math.max(0, this.cursor-this.pageSize), limit: this.pageSize}});
9869             break;
9870             case "next":
9871                 ds.load({params:{start: this.cursor+this.pageSize, limit: this.pageSize}});
9872             break;
9873             case "last":
9874                 var total = ds.getTotalCount();
9875                 var extra = total % this.pageSize;
9876                 var lastStart = extra ? (total - extra) : total-this.pageSize;
9877                 ds.load({params:{start: lastStart, limit: this.pageSize}});
9878             break;
9879             case "refresh":
9880                 ds.load({params:{start: this.cursor, limit: this.pageSize}});
9881             break;
9882         }
9883     },
9884
9885     /**
9886      * Unbinds the paging toolbar from the specified {@link Roo.data.Store}
9887      * @param {Roo.data.Store} store The data store to unbind
9888      */
9889     unbind : function(ds){
9890         ds.un("beforeload", this.beforeLoad, this);
9891         ds.un("load", this.onLoad, this);
9892         ds.un("loadexception", this.onLoadError, this);
9893         ds.un("remove", this.updateInfo, this);
9894         ds.un("add", this.updateInfo, this);
9895         this.ds = undefined;
9896     },
9897
9898     /**
9899      * Binds the paging toolbar to the specified {@link Roo.data.Store}
9900      * @param {Roo.data.Store} store The data store to bind
9901      */
9902     bind : function(ds){
9903         ds.on("beforeload", this.beforeLoad, this);
9904         ds.on("load", this.onLoad, this);
9905         ds.on("loadexception", this.onLoadError, this);
9906         ds.on("remove", this.updateInfo, this);
9907         ds.on("add", this.updateInfo, this);
9908         this.ds = ds;
9909     }
9910 });/*
9911  * Based on:
9912  * Ext JS Library 1.1.1
9913  * Copyright(c) 2006-2007, Ext JS, LLC.
9914  *
9915  * Originally Released Under LGPL - original licence link has changed is not relivant.
9916  *
9917  * Fork - LGPL
9918  * <script type="text/javascript">
9919  */
9920
9921 /**
9922  * @class Roo.Resizable
9923  * @extends Roo.util.Observable
9924  * <p>Applies drag handles to an element to make it resizable. The drag handles are inserted into the element
9925  * and positioned absolute. Some elements, such as a textarea or image, don't support this. To overcome that, you can wrap
9926  * 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
9927  * the element will be wrapped for you automatically.</p>
9928  * <p>Here is the list of valid resize handles:</p>
9929  * <pre>
9930 Value   Description
9931 ------  -------------------
9932  'n'     north
9933  's'     south
9934  'e'     east
9935  'w'     west
9936  'nw'    northwest
9937  'sw'    southwest
9938  'se'    southeast
9939  'ne'    northeast
9940  'hd'    horizontal drag
9941  'all'   all
9942 </pre>
9943  * <p>Here's an example showing the creation of a typical Resizable:</p>
9944  * <pre><code>
9945 var resizer = new Roo.Resizable("element-id", {
9946     handles: 'all',
9947     minWidth: 200,
9948     minHeight: 100,
9949     maxWidth: 500,
9950     maxHeight: 400,
9951     pinned: true
9952 });
9953 resizer.on("resize", myHandler);
9954 </code></pre>
9955  * <p>To hide a particular handle, set its display to none in CSS, or through script:<br>
9956  * resizer.east.setDisplayed(false);</p>
9957  * @cfg {Boolean/String/Element} resizeChild True to resize the first child, or id/element to resize (defaults to false)
9958  * @cfg {Array/String} adjustments String "auto" or an array [width, height] with values to be <b>added</b> to the
9959  * resize operation's new size (defaults to [0, 0])
9960  * @cfg {Number} minWidth The minimum width for the element (defaults to 5)
9961  * @cfg {Number} minHeight The minimum height for the element (defaults to 5)
9962  * @cfg {Number} maxWidth The maximum width for the element (defaults to 10000)
9963  * @cfg {Number} maxHeight The maximum height for the element (defaults to 10000)
9964  * @cfg {Boolean} enabled False to disable resizing (defaults to true)
9965  * @cfg {Boolean} wrap True to wrap an element with a div if needed (required for textareas and images, defaults to false)
9966  * @cfg {Number} width The width of the element in pixels (defaults to null)
9967  * @cfg {Number} height The height of the element in pixels (defaults to null)
9968  * @cfg {Boolean} animate True to animate the resize (not compatible with dynamic sizing, defaults to false)
9969  * @cfg {Number} duration Animation duration if animate = true (defaults to .35)
9970  * @cfg {Boolean} dynamic True to resize the element while dragging instead of using a proxy (defaults to false)
9971  * @cfg {String} handles String consisting of the resize handles to display (defaults to undefined)
9972  * @cfg {Boolean} multiDirectional <b>Deprecated</b>.  The old style of adding multi-direction resize handles, deprecated
9973  * in favor of the handles config option (defaults to false)
9974  * @cfg {Boolean} disableTrackOver True to disable mouse tracking. This is only applied at config time. (defaults to false)
9975  * @cfg {String} easing Animation easing if animate = true (defaults to 'easingOutStrong')
9976  * @cfg {Number} widthIncrement The increment to snap the width resize in pixels (dynamic must be true, defaults to 0)
9977  * @cfg {Number} heightIncrement The increment to snap the height resize in pixels (dynamic must be true, defaults to 0)
9978  * @cfg {Boolean} pinned True to ensure that the resize handles are always visible, false to display them only when the
9979  * user mouses over the resizable borders. This is only applied at config time. (defaults to false)
9980  * @cfg {Boolean} preserveRatio True to preserve the original ratio between height and width during resize (defaults to false)
9981  * @cfg {Boolean} transparent True for transparent handles. This is only applied at config time. (defaults to false)
9982  * @cfg {Number} minX The minimum allowed page X for the element (only used for west resizing, defaults to 0)
9983  * @cfg {Number} minY The minimum allowed page Y for the element (only used for north resizing, defaults to 0)
9984  * @cfg {Boolean} draggable Convenience to initialize drag drop (defaults to false)
9985  * @constructor
9986  * Create a new resizable component
9987  * @param {String/HTMLElement/Roo.Element} el The id or element to resize
9988  * @param {Object} config configuration options
9989   */
9990 Roo.Resizable = function(el, config)
9991 {
9992     this.el = Roo.get(el);
9993
9994     if(config && config.wrap){
9995         config.resizeChild = this.el;
9996         this.el = this.el.wrap(typeof config.wrap == "object" ? config.wrap : {cls:"xresizable-wrap"});
9997         this.el.id = this.el.dom.id = config.resizeChild.id + "-rzwrap";
9998         this.el.setStyle("overflow", "hidden");
9999         this.el.setPositioning(config.resizeChild.getPositioning());
10000         config.resizeChild.clearPositioning();
10001         if(!config.width || !config.height){
10002             var csize = config.resizeChild.getSize();
10003             this.el.setSize(csize.width, csize.height);
10004         }
10005         if(config.pinned && !config.adjustments){
10006             config.adjustments = "auto";
10007         }
10008     }
10009
10010     this.proxy = this.el.createProxy({tag: "div", cls: "x-resizable-proxy", id: this.el.id + "-rzproxy"});
10011     this.proxy.unselectable();
10012     this.proxy.enableDisplayMode('block');
10013
10014     Roo.apply(this, config);
10015
10016     if(this.pinned){
10017         this.disableTrackOver = true;
10018         this.el.addClass("x-resizable-pinned");
10019     }
10020     // if the element isn't positioned, make it relative
10021     var position = this.el.getStyle("position");
10022     if(position != "absolute" && position != "fixed"){
10023         this.el.setStyle("position", "relative");
10024     }
10025     if(!this.handles){ // no handles passed, must be legacy style
10026         this.handles = 's,e,se';
10027         if(this.multiDirectional){
10028             this.handles += ',n,w';
10029         }
10030     }
10031     if(this.handles == "all"){
10032         this.handles = "n s e w ne nw se sw";
10033     }
10034     var hs = this.handles.split(/\s*?[,;]\s*?| /);
10035     var ps = Roo.Resizable.positions;
10036     for(var i = 0, len = hs.length; i < len; i++){
10037         if(hs[i] && ps[hs[i]]){
10038             var pos = ps[hs[i]];
10039             this[pos] = new Roo.Resizable.Handle(this, pos, this.disableTrackOver, this.transparent);
10040         }
10041     }
10042     // legacy
10043     this.corner = this.southeast;
10044     
10045     // updateBox = the box can move..
10046     if(this.handles.indexOf("n") != -1 || this.handles.indexOf("w") != -1 || this.handles.indexOf("hd") != -1) {
10047         this.updateBox = true;
10048     }
10049
10050     this.activeHandle = null;
10051
10052     if(this.resizeChild){
10053         if(typeof this.resizeChild == "boolean"){
10054             this.resizeChild = Roo.get(this.el.dom.firstChild, true);
10055         }else{
10056             this.resizeChild = Roo.get(this.resizeChild, true);
10057         }
10058     }
10059     
10060     if(this.adjustments == "auto"){
10061         var rc = this.resizeChild;
10062         var hw = this.west, he = this.east, hn = this.north, hs = this.south;
10063         if(rc && (hw || hn)){
10064             rc.position("relative");
10065             rc.setLeft(hw ? hw.el.getWidth() : 0);
10066             rc.setTop(hn ? hn.el.getHeight() : 0);
10067         }
10068         this.adjustments = [
10069             (he ? -he.el.getWidth() : 0) + (hw ? -hw.el.getWidth() : 0),
10070             (hn ? -hn.el.getHeight() : 0) + (hs ? -hs.el.getHeight() : 0) -1
10071         ];
10072     }
10073
10074     if(this.draggable){
10075         this.dd = this.dynamic ?
10076             this.el.initDD(null) : this.el.initDDProxy(null, {dragElId: this.proxy.id});
10077         this.dd.setHandleElId(this.resizeChild ? this.resizeChild.id : this.el.id);
10078     }
10079
10080     // public events
10081     this.addEvents({
10082         /**
10083          * @event beforeresize
10084          * Fired before resize is allowed. Set enabled to false to cancel resize.
10085          * @param {Roo.Resizable} this
10086          * @param {Roo.EventObject} e The mousedown event
10087          */
10088         "beforeresize" : true,
10089         /**
10090          * @event resizing
10091          * Fired a resizing.
10092          * @param {Roo.Resizable} this
10093          * @param {Number} x The new x position
10094          * @param {Number} y The new y position
10095          * @param {Number} w The new w width
10096          * @param {Number} h The new h hight
10097          * @param {Roo.EventObject} e The mouseup event
10098          */
10099         "resizing" : true,
10100         /**
10101          * @event resize
10102          * Fired after a resize.
10103          * @param {Roo.Resizable} this
10104          * @param {Number} width The new width
10105          * @param {Number} height The new height
10106          * @param {Roo.EventObject} e The mouseup event
10107          */
10108         "resize" : true
10109     });
10110
10111     if(this.width !== null && this.height !== null){
10112         this.resizeTo(this.width, this.height);
10113     }else{
10114         this.updateChildSize();
10115     }
10116     if(Roo.isIE){
10117         this.el.dom.style.zoom = 1;
10118     }
10119     Roo.Resizable.superclass.constructor.call(this);
10120 };
10121
10122 Roo.extend(Roo.Resizable, Roo.util.Observable, {
10123         resizeChild : false,
10124         adjustments : [0, 0],
10125         minWidth : 5,
10126         minHeight : 5,
10127         maxWidth : 10000,
10128         maxHeight : 10000,
10129         enabled : true,
10130         animate : false,
10131         duration : .35,
10132         dynamic : false,
10133         handles : false,
10134         multiDirectional : false,
10135         disableTrackOver : false,
10136         easing : 'easeOutStrong',
10137         widthIncrement : 0,
10138         heightIncrement : 0,
10139         pinned : false,
10140         width : null,
10141         height : null,
10142         preserveRatio : false,
10143         transparent: false,
10144         minX: 0,
10145         minY: 0,
10146         draggable: false,
10147
10148         /**
10149          * @cfg {String/HTMLElement/Element} constrainTo Constrain the resize to a particular element
10150          */
10151         constrainTo: undefined,
10152         /**
10153          * @cfg {Roo.lib.Region} resizeRegion Constrain the resize to a particular region
10154          */
10155         resizeRegion: undefined,
10156
10157
10158     /**
10159      * Perform a manual resize
10160      * @param {Number} width
10161      * @param {Number} height
10162      */
10163     resizeTo : function(width, height){
10164         this.el.setSize(width, height);
10165         this.updateChildSize();
10166         this.fireEvent("resize", this, width, height, null);
10167     },
10168
10169     // private
10170     startSizing : function(e, handle){
10171         this.fireEvent("beforeresize", this, e);
10172         if(this.enabled){ // 2nd enabled check in case disabled before beforeresize handler
10173
10174             if(!this.overlay){
10175                 this.overlay = this.el.createProxy({tag: "div", cls: "x-resizable-overlay", html: "&#160;"});
10176                 this.overlay.unselectable();
10177                 this.overlay.enableDisplayMode("block");
10178                 this.overlay.on("mousemove", this.onMouseMove, this);
10179                 this.overlay.on("mouseup", this.onMouseUp, this);
10180             }
10181             this.overlay.setStyle("cursor", handle.el.getStyle("cursor"));
10182
10183             this.resizing = true;
10184             this.startBox = this.el.getBox();
10185             this.startPoint = e.getXY();
10186             this.offsets = [(this.startBox.x + this.startBox.width) - this.startPoint[0],
10187                             (this.startBox.y + this.startBox.height) - this.startPoint[1]];
10188
10189             this.overlay.setSize(Roo.lib.Dom.getViewWidth(true), Roo.lib.Dom.getViewHeight(true));
10190             this.overlay.show();
10191
10192             if(this.constrainTo) {
10193                 var ct = Roo.get(this.constrainTo);
10194                 this.resizeRegion = ct.getRegion().adjust(
10195                     ct.getFrameWidth('t'),
10196                     ct.getFrameWidth('l'),
10197                     -ct.getFrameWidth('b'),
10198                     -ct.getFrameWidth('r')
10199                 );
10200             }
10201
10202             this.proxy.setStyle('visibility', 'hidden'); // workaround display none
10203             this.proxy.show();
10204             this.proxy.setBox(this.startBox);
10205             if(!this.dynamic){
10206                 this.proxy.setStyle('visibility', 'visible');
10207             }
10208         }
10209     },
10210
10211     // private
10212     onMouseDown : function(handle, e){
10213         if(this.enabled){
10214             e.stopEvent();
10215             this.activeHandle = handle;
10216             this.startSizing(e, handle);
10217         }
10218     },
10219
10220     // private
10221     onMouseUp : function(e){
10222         var size = this.resizeElement();
10223         this.resizing = false;
10224         this.handleOut();
10225         this.overlay.hide();
10226         this.proxy.hide();
10227         this.fireEvent("resize", this, size.width, size.height, e);
10228     },
10229
10230     // private
10231     updateChildSize : function(){
10232         
10233         if(this.resizeChild){
10234             var el = this.el;
10235             var child = this.resizeChild;
10236             var adj = this.adjustments;
10237             if(el.dom.offsetWidth){
10238                 var b = el.getSize(true);
10239                 child.setSize(b.width+adj[0], b.height+adj[1]);
10240             }
10241             // Second call here for IE
10242             // The first call enables instant resizing and
10243             // the second call corrects scroll bars if they
10244             // exist
10245             if(Roo.isIE){
10246                 setTimeout(function(){
10247                     if(el.dom.offsetWidth){
10248                         var b = el.getSize(true);
10249                         child.setSize(b.width+adj[0], b.height+adj[1]);
10250                     }
10251                 }, 10);
10252             }
10253         }
10254     },
10255
10256     // private
10257     snap : function(value, inc, min){
10258         if(!inc || !value) {
10259             return value;
10260         }
10261         var newValue = value;
10262         var m = value % inc;
10263         if(m > 0){
10264             if(m > (inc/2)){
10265                 newValue = value + (inc-m);
10266             }else{
10267                 newValue = value - m;
10268             }
10269         }
10270         return Math.max(min, newValue);
10271     },
10272
10273     // private
10274     resizeElement : function(){
10275         var box = this.proxy.getBox();
10276         if(this.updateBox){
10277             this.el.setBox(box, false, this.animate, this.duration, null, this.easing);
10278         }else{
10279             this.el.setSize(box.width, box.height, this.animate, this.duration, null, this.easing);
10280         }
10281         this.updateChildSize();
10282         if(!this.dynamic){
10283             this.proxy.hide();
10284         }
10285         return box;
10286     },
10287
10288     // private
10289     constrain : function(v, diff, m, mx){
10290         if(v - diff < m){
10291             diff = v - m;
10292         }else if(v - diff > mx){
10293             diff = mx - v;
10294         }
10295         return diff;
10296     },
10297
10298     // private
10299     onMouseMove : function(e){
10300         
10301         if(this.enabled){
10302             try{// try catch so if something goes wrong the user doesn't get hung
10303
10304             if(this.resizeRegion && !this.resizeRegion.contains(e.getPoint())) {
10305                 return;
10306             }
10307
10308             //var curXY = this.startPoint;
10309             var curSize = this.curSize || this.startBox;
10310             var x = this.startBox.x, y = this.startBox.y;
10311             var ox = x, oy = y;
10312             var w = curSize.width, h = curSize.height;
10313             var ow = w, oh = h;
10314             var mw = this.minWidth, mh = this.minHeight;
10315             var mxw = this.maxWidth, mxh = this.maxHeight;
10316             var wi = this.widthIncrement;
10317             var hi = this.heightIncrement;
10318
10319             var eventXY = e.getXY();
10320             var diffX = -(this.startPoint[0] - Math.max(this.minX, eventXY[0]));
10321             var diffY = -(this.startPoint[1] - Math.max(this.minY, eventXY[1]));
10322
10323             var pos = this.activeHandle.position;
10324
10325             switch(pos){
10326                 case "east":
10327                     w += diffX;
10328                     w = Math.min(Math.max(mw, w), mxw);
10329                     break;
10330              
10331                 case "south":
10332                     h += diffY;
10333                     h = Math.min(Math.max(mh, h), mxh);
10334                     break;
10335                 case "southeast":
10336                     w += diffX;
10337                     h += diffY;
10338                     w = Math.min(Math.max(mw, w), mxw);
10339                     h = Math.min(Math.max(mh, h), mxh);
10340                     break;
10341                 case "north":
10342                     diffY = this.constrain(h, diffY, mh, mxh);
10343                     y += diffY;
10344                     h -= diffY;
10345                     break;
10346                 case "hdrag":
10347                     
10348                     if (wi) {
10349                         var adiffX = Math.abs(diffX);
10350                         var sub = (adiffX % wi); // how much 
10351                         if (sub > (wi/2)) { // far enough to snap
10352                             diffX = (diffX > 0) ? diffX-sub + wi : diffX+sub - wi;
10353                         } else {
10354                             // remove difference.. 
10355                             diffX = (diffX > 0) ? diffX-sub : diffX+sub;
10356                         }
10357                     }
10358                     x += diffX;
10359                     x = Math.max(this.minX, x);
10360                     break;
10361                 case "west":
10362                     diffX = this.constrain(w, diffX, mw, mxw);
10363                     x += diffX;
10364                     w -= diffX;
10365                     break;
10366                 case "northeast":
10367                     w += diffX;
10368                     w = Math.min(Math.max(mw, w), mxw);
10369                     diffY = this.constrain(h, diffY, mh, mxh);
10370                     y += diffY;
10371                     h -= diffY;
10372                     break;
10373                 case "northwest":
10374                     diffX = this.constrain(w, diffX, mw, mxw);
10375                     diffY = this.constrain(h, diffY, mh, mxh);
10376                     y += diffY;
10377                     h -= diffY;
10378                     x += diffX;
10379                     w -= diffX;
10380                     break;
10381                case "southwest":
10382                     diffX = this.constrain(w, diffX, mw, mxw);
10383                     h += diffY;
10384                     h = Math.min(Math.max(mh, h), mxh);
10385                     x += diffX;
10386                     w -= diffX;
10387                     break;
10388             }
10389
10390             var sw = this.snap(w, wi, mw);
10391             var sh = this.snap(h, hi, mh);
10392             if(sw != w || sh != h){
10393                 switch(pos){
10394                     case "northeast":
10395                         y -= sh - h;
10396                     break;
10397                     case "north":
10398                         y -= sh - h;
10399                         break;
10400                     case "southwest":
10401                         x -= sw - w;
10402                     break;
10403                     case "west":
10404                         x -= sw - w;
10405                         break;
10406                     case "northwest":
10407                         x -= sw - w;
10408                         y -= sh - h;
10409                     break;
10410                 }
10411                 w = sw;
10412                 h = sh;
10413             }
10414
10415             if(this.preserveRatio){
10416                 switch(pos){
10417                     case "southeast":
10418                     case "east":
10419                         h = oh * (w/ow);
10420                         h = Math.min(Math.max(mh, h), mxh);
10421                         w = ow * (h/oh);
10422                        break;
10423                     case "south":
10424                         w = ow * (h/oh);
10425                         w = Math.min(Math.max(mw, w), mxw);
10426                         h = oh * (w/ow);
10427                         break;
10428                     case "northeast":
10429                         w = ow * (h/oh);
10430                         w = Math.min(Math.max(mw, w), mxw);
10431                         h = oh * (w/ow);
10432                     break;
10433                     case "north":
10434                         var tw = w;
10435                         w = ow * (h/oh);
10436                         w = Math.min(Math.max(mw, w), mxw);
10437                         h = oh * (w/ow);
10438                         x += (tw - w) / 2;
10439                         break;
10440                     case "southwest":
10441                         h = oh * (w/ow);
10442                         h = Math.min(Math.max(mh, h), mxh);
10443                         var tw = w;
10444                         w = ow * (h/oh);
10445                         x += tw - w;
10446                         break;
10447                     case "west":
10448                         var th = h;
10449                         h = oh * (w/ow);
10450                         h = Math.min(Math.max(mh, h), mxh);
10451                         y += (th - h) / 2;
10452                         var tw = w;
10453                         w = ow * (h/oh);
10454                         x += tw - w;
10455                        break;
10456                     case "northwest":
10457                         var tw = w;
10458                         var th = h;
10459                         h = oh * (w/ow);
10460                         h = Math.min(Math.max(mh, h), mxh);
10461                         w = ow * (h/oh);
10462                         y += th - h;
10463                         x += tw - w;
10464                        break;
10465
10466                 }
10467             }
10468             if (pos == 'hdrag') {
10469                 w = ow;
10470             }
10471             this.proxy.setBounds(x, y, w, h);
10472             if(this.dynamic){
10473                 this.resizeElement();
10474             }
10475             }catch(e){}
10476         }
10477         this.fireEvent("resizing", this, x, y, w, h, e);
10478     },
10479
10480     // private
10481     handleOver : function(){
10482         if(this.enabled){
10483             this.el.addClass("x-resizable-over");
10484         }
10485     },
10486
10487     // private
10488     handleOut : function(){
10489         if(!this.resizing){
10490             this.el.removeClass("x-resizable-over");
10491         }
10492     },
10493
10494     /**
10495      * Returns the element this component is bound to.
10496      * @return {Roo.Element}
10497      */
10498     getEl : function(){
10499         return this.el;
10500     },
10501
10502     /**
10503      * Returns the resizeChild element (or null).
10504      * @return {Roo.Element}
10505      */
10506     getResizeChild : function(){
10507         return this.resizeChild;
10508     },
10509     groupHandler : function()
10510     {
10511         
10512     },
10513     /**
10514      * Destroys this resizable. If the element was wrapped and
10515      * removeEl is not true then the element remains.
10516      * @param {Boolean} removeEl (optional) true to remove the element from the DOM
10517      */
10518     destroy : function(removeEl){
10519         this.proxy.remove();
10520         if(this.overlay){
10521             this.overlay.removeAllListeners();
10522             this.overlay.remove();
10523         }
10524         var ps = Roo.Resizable.positions;
10525         for(var k in ps){
10526             if(typeof ps[k] != "function" && this[ps[k]]){
10527                 var h = this[ps[k]];
10528                 h.el.removeAllListeners();
10529                 h.el.remove();
10530             }
10531         }
10532         if(removeEl){
10533             this.el.update("");
10534             this.el.remove();
10535         }
10536     }
10537 });
10538
10539 // private
10540 // hash to map config positions to true positions
10541 Roo.Resizable.positions = {
10542     n: "north", s: "south", e: "east", w: "west", se: "southeast", sw: "southwest", nw: "northwest", ne: "northeast", 
10543     hd: "hdrag"
10544 };
10545
10546 // private
10547 Roo.Resizable.Handle = function(rz, pos, disableTrackOver, transparent){
10548     if(!this.tpl){
10549         // only initialize the template if resizable is used
10550         var tpl = Roo.DomHelper.createTemplate(
10551             {tag: "div", cls: "x-resizable-handle x-resizable-handle-{0}"}
10552         );
10553         tpl.compile();
10554         Roo.Resizable.Handle.prototype.tpl = tpl;
10555     }
10556     this.position = pos;
10557     this.rz = rz;
10558     // show north drag fro topdra
10559     var handlepos = pos == 'hdrag' ? 'north' : pos;
10560     
10561     this.el = this.tpl.append(rz.el.dom, [handlepos], true);
10562     if (pos == 'hdrag') {
10563         this.el.setStyle('cursor', 'pointer');
10564     }
10565     this.el.unselectable();
10566     if(transparent){
10567         this.el.setOpacity(0);
10568     }
10569     this.el.on("mousedown", this.onMouseDown, this);
10570     if(!disableTrackOver){
10571         this.el.on("mouseover", this.onMouseOver, this);
10572         this.el.on("mouseout", this.onMouseOut, this);
10573     }
10574 };
10575
10576 // private
10577 Roo.Resizable.Handle.prototype = {
10578     afterResize : function(rz){
10579         Roo.log('after?');
10580         // do nothing
10581     },
10582     // private
10583     onMouseDown : function(e){
10584         this.rz.onMouseDown(this, e);
10585     },
10586     // private
10587     onMouseOver : function(e){
10588         this.rz.handleOver(this, e);
10589     },
10590     // private
10591     onMouseOut : function(e){
10592         this.rz.handleOut(this, e);
10593     }
10594 };/*
10595  * Based on:
10596  * Ext JS Library 1.1.1
10597  * Copyright(c) 2006-2007, Ext JS, LLC.
10598  *
10599  * Originally Released Under LGPL - original licence link has changed is not relivant.
10600  *
10601  * Fork - LGPL
10602  * <script type="text/javascript">
10603  */
10604
10605 /**
10606  * @class Roo.Editor
10607  * @extends Roo.Component
10608  * A base editor field that handles displaying/hiding on demand and has some built-in sizing and event handling logic.
10609  * @constructor
10610  * Create a new Editor
10611  * @param {Roo.form.Field} field The Field object (or descendant)
10612  * @param {Object} config The config object
10613  */
10614 Roo.Editor = function(field, config){
10615     Roo.Editor.superclass.constructor.call(this, config);
10616     this.field = field;
10617     this.addEvents({
10618         /**
10619              * @event beforestartedit
10620              * Fires when editing is initiated, but before the value changes.  Editing can be canceled by returning
10621              * false from the handler of this event.
10622              * @param {Editor} this
10623              * @param {Roo.Element} boundEl The underlying element bound to this editor
10624              * @param {Mixed} value The field value being set
10625              */
10626         "beforestartedit" : true,
10627         /**
10628              * @event startedit
10629              * Fires when this editor is displayed
10630              * @param {Roo.Element} boundEl The underlying element bound to this editor
10631              * @param {Mixed} value The starting field value
10632              */
10633         "startedit" : true,
10634         /**
10635              * @event beforecomplete
10636              * Fires after a change has been made to the field, but before the change is reflected in the underlying
10637              * field.  Saving the change to the field can be canceled by returning false from the handler of this event.
10638              * Note that if the value has not changed and ignoreNoChange = true, the editing will still end but this
10639              * event will not fire since no edit actually occurred.
10640              * @param {Editor} this
10641              * @param {Mixed} value The current field value
10642              * @param {Mixed} startValue The original field value
10643              */
10644         "beforecomplete" : true,
10645         /**
10646              * @event complete
10647              * Fires after editing is complete and any changed value has been written to the underlying field.
10648              * @param {Editor} this
10649              * @param {Mixed} value The current field value
10650              * @param {Mixed} startValue The original field value
10651              */
10652         "complete" : true,
10653         /**
10654          * @event specialkey
10655          * Fires when any key related to navigation (arrows, tab, enter, esc, etc.) is pressed.  You can check
10656          * {@link Roo.EventObject#getKey} to determine which key was pressed.
10657          * @param {Roo.form.Field} this
10658          * @param {Roo.EventObject} e The event object
10659          */
10660         "specialkey" : true
10661     });
10662 };
10663
10664 Roo.extend(Roo.Editor, Roo.Component, {
10665     /**
10666      * @cfg {Boolean/String} autosize
10667      * True for the editor to automatically adopt the size of the underlying field, "width" to adopt the width only,
10668      * or "height" to adopt the height only (defaults to false)
10669      */
10670     /**
10671      * @cfg {Boolean} revertInvalid
10672      * True to automatically revert the field value and cancel the edit when the user completes an edit and the field
10673      * validation fails (defaults to true)
10674      */
10675     /**
10676      * @cfg {Boolean} ignoreNoChange
10677      * True to skip the the edit completion process (no save, no events fired) if the user completes an edit and
10678      * the value has not changed (defaults to false).  Applies only to string values - edits for other data types
10679      * will never be ignored.
10680      */
10681     /**
10682      * @cfg {Boolean} hideEl
10683      * False to keep the bound element visible while the editor is displayed (defaults to true)
10684      */
10685     /**
10686      * @cfg {Mixed} value
10687      * The data value of the underlying field (defaults to "")
10688      */
10689     value : "",
10690     /**
10691      * @cfg {String} alignment
10692      * The position to align to (see {@link Roo.Element#alignTo} for more details, defaults to "c-c?").
10693      */
10694     alignment: "c-c?",
10695     /**
10696      * @cfg {Boolean/String} shadow "sides" for sides/bottom only, "frame" for 4-way shadow, and "drop"
10697      * for bottom-right shadow (defaults to "frame")
10698      */
10699     shadow : "frame",
10700     /**
10701      * @cfg {Boolean} constrain True to constrain the editor to the viewport
10702      */
10703     constrain : false,
10704     /**
10705      * @cfg {Boolean} completeOnEnter True to complete the edit when the enter key is pressed (defaults to false)
10706      */
10707     completeOnEnter : false,
10708     /**
10709      * @cfg {Boolean} cancelOnEsc True to cancel the edit when the escape key is pressed (defaults to false)
10710      */
10711     cancelOnEsc : false,
10712     /**
10713      * @cfg {Boolean} updateEl True to update the innerHTML of the bound element when the update completes (defaults to false)
10714      */
10715     updateEl : false,
10716
10717     // private
10718     onRender : function(ct, position){
10719         this.el = new Roo.Layer({
10720             shadow: this.shadow,
10721             cls: "x-editor",
10722             parentEl : ct,
10723             shim : this.shim,
10724             shadowOffset:4,
10725             id: this.id,
10726             constrain: this.constrain
10727         });
10728         this.el.setStyle("overflow", Roo.isGecko ? "auto" : "hidden");
10729         if(this.field.msgTarget != 'title'){
10730             this.field.msgTarget = 'qtip';
10731         }
10732         this.field.render(this.el);
10733         if(Roo.isGecko){
10734             this.field.el.dom.setAttribute('autocomplete', 'off');
10735         }
10736         this.field.on("specialkey", this.onSpecialKey, this);
10737         if(this.swallowKeys){
10738             this.field.el.swallowEvent(['keydown','keypress']);
10739         }
10740         this.field.show();
10741         this.field.on("blur", this.onBlur, this);
10742         if(this.field.grow){
10743             this.field.on("autosize", this.el.sync,  this.el, {delay:1});
10744         }
10745     },
10746
10747     onSpecialKey : function(field, e)
10748     {
10749         //Roo.log('editor onSpecialKey');
10750         if(this.completeOnEnter && e.getKey() == e.ENTER){
10751             e.stopEvent();
10752             this.completeEdit();
10753             return;
10754         }
10755         // do not fire special key otherwise it might hide close the editor...
10756         if(e.getKey() == e.ENTER){    
10757             return;
10758         }
10759         if(this.cancelOnEsc && e.getKey() == e.ESC){
10760             this.cancelEdit();
10761             return;
10762         } 
10763         this.fireEvent('specialkey', field, e);
10764     
10765     },
10766
10767     /**
10768      * Starts the editing process and shows the editor.
10769      * @param {String/HTMLElement/Element} el The element to edit
10770      * @param {String} value (optional) A value to initialize the editor with. If a value is not provided, it defaults
10771       * to the innerHTML of el.
10772      */
10773     startEdit : function(el, value){
10774         if(this.editing){
10775             this.completeEdit();
10776         }
10777         this.boundEl = Roo.get(el);
10778         var v = value !== undefined ? value : this.boundEl.dom.innerHTML;
10779         if(!this.rendered){
10780             this.render(this.parentEl || document.body);
10781         }
10782         if(this.fireEvent("beforestartedit", this, this.boundEl, v) === false){
10783             return;
10784         }
10785         this.startValue = v;
10786         this.field.setValue(v);
10787         if(this.autoSize){
10788             var sz = this.boundEl.getSize();
10789             switch(this.autoSize){
10790                 case "width":
10791                 this.setSize(sz.width,  "");
10792                 break;
10793                 case "height":
10794                 this.setSize("",  sz.height);
10795                 break;
10796                 default:
10797                 this.setSize(sz.width,  sz.height);
10798             }
10799         }
10800         this.el.alignTo(this.boundEl, this.alignment);
10801         this.editing = true;
10802         if(Roo.QuickTips){
10803             Roo.QuickTips.disable();
10804         }
10805         this.show();
10806     },
10807
10808     /**
10809      * Sets the height and width of this editor.
10810      * @param {Number} width The new width
10811      * @param {Number} height The new height
10812      */
10813     setSize : function(w, h){
10814         this.field.setSize(w, h);
10815         if(this.el){
10816             this.el.sync();
10817         }
10818     },
10819
10820     /**
10821      * Realigns the editor to the bound field based on the current alignment config value.
10822      */
10823     realign : function(){
10824         this.el.alignTo(this.boundEl, this.alignment);
10825     },
10826
10827     /**
10828      * Ends the editing process, persists the changed value to the underlying field, and hides the editor.
10829      * @param {Boolean} remainVisible Override the default behavior and keep the editor visible after edit (defaults to false)
10830      */
10831     completeEdit : function(remainVisible){
10832         if(!this.editing){
10833             return;
10834         }
10835         var v = this.getValue();
10836         if(this.revertInvalid !== false && !this.field.isValid()){
10837             v = this.startValue;
10838             this.cancelEdit(true);
10839         }
10840         if(String(v) === String(this.startValue) && this.ignoreNoChange){
10841             this.editing = false;
10842             this.hide();
10843             return;
10844         }
10845         if(this.fireEvent("beforecomplete", this, v, this.startValue) !== false){
10846             this.editing = false;
10847             if(this.updateEl && this.boundEl){
10848                 this.boundEl.update(v);
10849             }
10850             if(remainVisible !== true){
10851                 this.hide();
10852             }
10853             this.fireEvent("complete", this, v, this.startValue);
10854         }
10855     },
10856
10857     // private
10858     onShow : function(){
10859         this.el.show();
10860         if(this.hideEl !== false){
10861             this.boundEl.hide();
10862         }
10863         this.field.show();
10864         if(Roo.isIE && !this.fixIEFocus){ // IE has problems with focusing the first time
10865             this.fixIEFocus = true;
10866             this.deferredFocus.defer(50, this);
10867         }else{
10868             this.field.focus();
10869         }
10870         this.fireEvent("startedit", this.boundEl, this.startValue);
10871     },
10872
10873     deferredFocus : function(){
10874         if(this.editing){
10875             this.field.focus();
10876         }
10877     },
10878
10879     /**
10880      * Cancels the editing process and hides the editor without persisting any changes.  The field value will be
10881      * reverted to the original starting value.
10882      * @param {Boolean} remainVisible Override the default behavior and keep the editor visible after
10883      * cancel (defaults to false)
10884      */
10885     cancelEdit : function(remainVisible){
10886         if(this.editing){
10887             this.setValue(this.startValue);
10888             if(remainVisible !== true){
10889                 this.hide();
10890             }
10891         }
10892     },
10893
10894     // private
10895     onBlur : function(){
10896         if(this.allowBlur !== true && this.editing){
10897             this.completeEdit();
10898         }
10899     },
10900
10901     // private
10902     onHide : function(){
10903         if(this.editing){
10904             this.completeEdit();
10905             return;
10906         }
10907         this.field.blur();
10908         if(this.field.collapse){
10909             this.field.collapse();
10910         }
10911         this.el.hide();
10912         if(this.hideEl !== false){
10913             this.boundEl.show();
10914         }
10915         if(Roo.QuickTips){
10916             Roo.QuickTips.enable();
10917         }
10918     },
10919
10920     /**
10921      * Sets the data value of the editor
10922      * @param {Mixed} value Any valid value supported by the underlying field
10923      */
10924     setValue : function(v){
10925         this.field.setValue(v);
10926     },
10927
10928     /**
10929      * Gets the data value of the editor
10930      * @return {Mixed} The data value
10931      */
10932     getValue : function(){
10933         return this.field.getValue();
10934     }
10935 });/*
10936  * Based on:
10937  * Ext JS Library 1.1.1
10938  * Copyright(c) 2006-2007, Ext JS, LLC.
10939  *
10940  * Originally Released Under LGPL - original licence link has changed is not relivant.
10941  *
10942  * Fork - LGPL
10943  * <script type="text/javascript">
10944  */
10945  
10946 /**
10947  * @class Roo.BasicDialog
10948  * @extends Roo.util.Observable
10949  * @parent none builder
10950  * Lightweight Dialog Class.  The code below shows the creation of a typical dialog using existing HTML markup:
10951  * <pre><code>
10952 var dlg = new Roo.BasicDialog("my-dlg", {
10953     height: 200,
10954     width: 300,
10955     minHeight: 100,
10956     minWidth: 150,
10957     modal: true,
10958     proxyDrag: true,
10959     shadow: true
10960 });
10961 dlg.addKeyListener(27, dlg.hide, dlg); // ESC can also close the dialog
10962 dlg.addButton('OK', dlg.hide, dlg);    // Could call a save function instead of hiding
10963 dlg.addButton('Cancel', dlg.hide, dlg);
10964 dlg.show();
10965 </code></pre>
10966   <b>A Dialog should always be a direct child of the body element.</b>
10967  * @cfg {Boolean/DomHelper} autoCreate True to auto create from scratch, or using a DomHelper Object (defaults to false)
10968  * @cfg {String} title Default text to display in the title bar (defaults to null)
10969  * @cfg {Number} width Width of the dialog in pixels (can also be set via CSS).  Determined by browser if unspecified.
10970  * @cfg {Number} height Height of the dialog in pixels (can also be set via CSS).  Determined by browser if unspecified.
10971  * @cfg {Number} x The default left page coordinate of the dialog (defaults to center screen)
10972  * @cfg {Number} y The default top page coordinate of the dialog (defaults to center screen)
10973  * @cfg {String/Element} animateTarget Id or element from which the dialog should animate while opening
10974  * (defaults to null with no animation)
10975  * @cfg {Boolean} resizable False to disable manual dialog resizing (defaults to true)
10976  * @cfg {String} resizeHandles Which resize handles to display - see the {@link Roo.Resizable} handles config
10977  * property for valid values (defaults to 'all')
10978  * @cfg {Number} minHeight The minimum allowable height for a resizable dialog (defaults to 80)
10979  * @cfg {Number} minWidth The minimum allowable width for a resizable dialog (defaults to 200)
10980  * @cfg {Boolean} modal True to show the dialog modally, preventing user interaction with the rest of the page (defaults to false)
10981  * @cfg {Boolean} autoScroll True to allow the dialog body contents to overflow and display scrollbars (defaults to false)
10982  * @cfg {Boolean} closable False to remove the built-in top-right corner close button (defaults to true)
10983  * @cfg {Boolean} collapsible False to remove the built-in top-right corner collapse button (defaults to true)
10984  * @cfg {Boolean} constraintoviewport True to keep the dialog constrained within the visible viewport boundaries (defaults to true)
10985  * @cfg {Boolean} syncHeightBeforeShow True to cause the dimensions to be recalculated before the dialog is shown (defaults to false)
10986  * @cfg {Boolean} draggable False to disable dragging of the dialog within the viewport (defaults to true)
10987  * @cfg {Boolean} autoTabs If true, all elements with class 'x-dlg-tab' will get automatically converted to tabs (defaults to false)
10988  * @cfg {String} tabTag The tag name of tab elements, used when autoTabs = true (defaults to 'div')
10989  * @cfg {Boolean} proxyDrag True to drag a lightweight proxy element rather than the dialog itself, used when
10990  * draggable = true (defaults to false)
10991  * @cfg {Boolean} fixedcenter True to ensure that anytime the dialog is shown or resized it gets centered (defaults to false)
10992  * @cfg {Boolean/String} shadow True or "sides" for the default effect, "frame" for 4-way shadow, and "drop" for bottom-right
10993  * shadow (defaults to false)
10994  * @cfg {Number} shadowOffset The number of pixels to offset the shadow if displayed (defaults to 5)
10995  * @cfg {String} buttonAlign Valid values are "left," "center" and "right" (defaults to "right")
10996  * @cfg {Number} minButtonWidth Minimum width of all dialog buttons (defaults to 75)
10997  * @cfg {Array} buttons Array of buttons
10998  * @cfg {Boolean} shim True to create an iframe shim that prevents selects from showing through (defaults to false)
10999  * @constructor
11000  * Create a new BasicDialog.
11001  * @param {String/HTMLElement/Roo.Element} el The container element or DOM node, or its id
11002  * @param {Object} config Configuration options
11003  */
11004 Roo.BasicDialog = function(el, config){
11005     this.el = Roo.get(el);
11006     var dh = Roo.DomHelper;
11007     if(!this.el && config && config.autoCreate){
11008         if(typeof config.autoCreate == "object"){
11009             if(!config.autoCreate.id){
11010                 config.autoCreate.id = el;
11011             }
11012             this.el = dh.append(document.body,
11013                         config.autoCreate, true);
11014         }else{
11015             this.el = dh.append(document.body,
11016                         {tag: "div", id: el, style:'visibility:hidden;'}, true);
11017         }
11018     }
11019     el = this.el;
11020     el.setDisplayed(true);
11021     el.hide = this.hideAction;
11022     this.id = el.id;
11023     el.addClass("x-dlg");
11024
11025     Roo.apply(this, config);
11026
11027     this.proxy = el.createProxy("x-dlg-proxy");
11028     this.proxy.hide = this.hideAction;
11029     this.proxy.setOpacity(.5);
11030     this.proxy.hide();
11031
11032     if(config.width){
11033         el.setWidth(config.width);
11034     }
11035     if(config.height){
11036         el.setHeight(config.height);
11037     }
11038     this.size = el.getSize();
11039     if(typeof config.x != "undefined" && typeof config.y != "undefined"){
11040         this.xy = [config.x,config.y];
11041     }else{
11042         this.xy = el.getCenterXY(true);
11043     }
11044     /** The header element @type Roo.Element */
11045     this.header = el.child("> .x-dlg-hd");
11046     /** The body element @type Roo.Element */
11047     this.body = el.child("> .x-dlg-bd");
11048     /** The footer element @type Roo.Element */
11049     this.footer = el.child("> .x-dlg-ft");
11050
11051     if(!this.header){
11052         this.header = el.createChild({tag: "div", cls:"x-dlg-hd", html: "&#160;"}, this.body ? this.body.dom : null);
11053     }
11054     if(!this.body){
11055         this.body = el.createChild({tag: "div", cls:"x-dlg-bd"});
11056     }
11057
11058     this.header.unselectable();
11059     if(this.title){
11060         this.header.update(this.title);
11061     }
11062     // this element allows the dialog to be focused for keyboard event
11063     this.focusEl = el.createChild({tag: "a", href:"#", cls:"x-dlg-focus", tabIndex:"-1"});
11064     this.focusEl.swallowEvent("click", true);
11065
11066     this.header.wrap({cls:"x-dlg-hd-right"}).wrap({cls:"x-dlg-hd-left"}, true);
11067
11068     // wrap the body and footer for special rendering
11069     this.bwrap = this.body.wrap({tag: "div", cls:"x-dlg-dlg-body"});
11070     if(this.footer){
11071         this.bwrap.dom.appendChild(this.footer.dom);
11072     }
11073
11074     this.bg = this.el.createChild({
11075         tag: "div", cls:"x-dlg-bg",
11076         html: '<div class="x-dlg-bg-left"><div class="x-dlg-bg-right"><div class="x-dlg-bg-center">&#160;</div></div></div>'
11077     });
11078     this.centerBg = this.bg.child("div.x-dlg-bg-center");
11079
11080
11081     if(this.autoScroll !== false && !this.autoTabs){
11082         this.body.setStyle("overflow", "auto");
11083     }
11084
11085     this.toolbox = this.el.createChild({cls: "x-dlg-toolbox"});
11086
11087     if(this.closable !== false){
11088         this.el.addClass("x-dlg-closable");
11089         this.close = this.toolbox.createChild({cls:"x-dlg-close"});
11090         this.close.on("click", this.closeClick, this);
11091         this.close.addClassOnOver("x-dlg-close-over");
11092     }
11093     if(this.collapsible !== false){
11094         this.collapseBtn = this.toolbox.createChild({cls:"x-dlg-collapse"});
11095         this.collapseBtn.on("click", this.collapseClick, this);
11096         this.collapseBtn.addClassOnOver("x-dlg-collapse-over");
11097         this.header.on("dblclick", this.collapseClick, this);
11098     }
11099     if(this.resizable !== false){
11100         this.el.addClass("x-dlg-resizable");
11101         this.resizer = new Roo.Resizable(el, {
11102             minWidth: this.minWidth || 80,
11103             minHeight:this.minHeight || 80,
11104             handles: this.resizeHandles || "all",
11105             pinned: true
11106         });
11107         this.resizer.on("beforeresize", this.beforeResize, this);
11108         this.resizer.on("resize", this.onResize, this);
11109     }
11110     if(this.draggable !== false){
11111         el.addClass("x-dlg-draggable");
11112         if (!this.proxyDrag) {
11113             var dd = new Roo.dd.DD(el.dom.id, "WindowDrag");
11114         }
11115         else {
11116             var dd = new Roo.dd.DDProxy(el.dom.id, "WindowDrag", {dragElId: this.proxy.id});
11117         }
11118         dd.setHandleElId(this.header.id);
11119         dd.endDrag = this.endMove.createDelegate(this);
11120         dd.startDrag = this.startMove.createDelegate(this);
11121         dd.onDrag = this.onDrag.createDelegate(this);
11122         dd.scroll = false;
11123         this.dd = dd;
11124     }
11125     if(this.modal){
11126         this.mask = dh.append(document.body, {tag: "div", cls:"x-dlg-mask"}, true);
11127         this.mask.enableDisplayMode("block");
11128         this.mask.hide();
11129         this.el.addClass("x-dlg-modal");
11130     }
11131     if(this.shadow){
11132         this.shadow = new Roo.Shadow({
11133             mode : typeof this.shadow == "string" ? this.shadow : "sides",
11134             offset : this.shadowOffset
11135         });
11136     }else{
11137         this.shadowOffset = 0;
11138     }
11139     if(Roo.useShims && this.shim !== false){
11140         this.shim = this.el.createShim();
11141         this.shim.hide = this.hideAction;
11142         this.shim.hide();
11143     }else{
11144         this.shim = false;
11145     }
11146     if(this.autoTabs){
11147         this.initTabs();
11148     }
11149     if (this.buttons) { 
11150         var bts= this.buttons;
11151         this.buttons = [];
11152         Roo.each(bts, function(b) {
11153             this.addButton(b);
11154         }, this);
11155     }
11156     
11157     
11158     this.addEvents({
11159         /**
11160          * @event keydown
11161          * Fires when a key is pressed
11162          * @param {Roo.BasicDialog} this
11163          * @param {Roo.EventObject} e
11164          */
11165         "keydown" : true,
11166         /**
11167          * @event move
11168          * Fires when this dialog is moved by the user.
11169          * @param {Roo.BasicDialog} this
11170          * @param {Number} x The new page X
11171          * @param {Number} y The new page Y
11172          */
11173         "move" : true,
11174         /**
11175          * @event resize
11176          * Fires when this dialog is resized by the user.
11177          * @param {Roo.BasicDialog} this
11178          * @param {Number} width The new width
11179          * @param {Number} height The new height
11180          */
11181         "resize" : true,
11182         /**
11183          * @event beforehide
11184          * Fires before this dialog is hidden.
11185          * @param {Roo.BasicDialog} this
11186          */
11187         "beforehide" : true,
11188         /**
11189          * @event hide
11190          * Fires when this dialog is hidden.
11191          * @param {Roo.BasicDialog} this
11192          */
11193         "hide" : true,
11194         /**
11195          * @event beforeshow
11196          * Fires before this dialog is shown.
11197          * @param {Roo.BasicDialog} this
11198          */
11199         "beforeshow" : true,
11200         /**
11201          * @event show
11202          * Fires when this dialog is shown.
11203          * @param {Roo.BasicDialog} this
11204          */
11205         "show" : true
11206     });
11207     el.on("keydown", this.onKeyDown, this);
11208     el.on("mousedown", this.toFront, this);
11209     Roo.EventManager.onWindowResize(this.adjustViewport, this, true);
11210     this.el.hide();
11211     Roo.DialogManager.register(this);
11212     Roo.BasicDialog.superclass.constructor.call(this);
11213 };
11214
11215 Roo.extend(Roo.BasicDialog, Roo.util.Observable, {
11216     shadowOffset: Roo.isIE ? 6 : 5,
11217     minHeight: 80,
11218     minWidth: 200,
11219     minButtonWidth: 75,
11220     defaultButton: null,
11221     buttonAlign: "right",
11222     tabTag: 'div',
11223     firstShow: true,
11224
11225     /**
11226      * Sets the dialog title text
11227      * @param {String} text The title text to display
11228      * @return {Roo.BasicDialog} this
11229      */
11230     setTitle : function(text){
11231         this.header.update(text);
11232         return this;
11233     },
11234
11235     // private
11236     closeClick : function(){
11237         this.hide();
11238     },
11239
11240     // private
11241     collapseClick : function(){
11242         this[this.collapsed ? "expand" : "collapse"]();
11243     },
11244
11245     /**
11246      * Collapses the dialog to its minimized state (only the title bar is visible).
11247      * Equivalent to the user clicking the collapse dialog button.
11248      */
11249     collapse : function(){
11250         if(!this.collapsed){
11251             this.collapsed = true;
11252             this.el.addClass("x-dlg-collapsed");
11253             this.restoreHeight = this.el.getHeight();
11254             this.resizeTo(this.el.getWidth(), this.header.getHeight());
11255         }
11256     },
11257
11258     /**
11259      * Expands a collapsed dialog back to its normal state.  Equivalent to the user
11260      * clicking the expand dialog button.
11261      */
11262     expand : function(){
11263         if(this.collapsed){
11264             this.collapsed = false;
11265             this.el.removeClass("x-dlg-collapsed");
11266             this.resizeTo(this.el.getWidth(), this.restoreHeight);
11267         }
11268     },
11269
11270     /**
11271      * Reinitializes the tabs component, clearing out old tabs and finding new ones.
11272      * @return {Roo.panel.Tab} The tabs component
11273      */
11274     initTabs : function(){
11275         var tabs = this.getTabs();
11276         while(tabs.getTab(0)){
11277             tabs.removeTab(0);
11278         }
11279         this.el.select(this.tabTag+'.x-dlg-tab').each(function(el){
11280             var dom = el.dom;
11281             tabs.addTab(Roo.id(dom), dom.title);
11282             dom.title = "";
11283         });
11284         tabs.activate(0);
11285         return tabs;
11286     },
11287
11288     // private
11289     beforeResize : function(){
11290         this.resizer.minHeight = Math.max(this.minHeight, this.getHeaderFooterHeight(true)+40);
11291     },
11292
11293     // private
11294     onResize : function(){
11295         this.refreshSize();
11296         this.syncBodyHeight();
11297         this.adjustAssets();
11298         this.focus();
11299         this.fireEvent("resize", this, this.size.width, this.size.height);
11300     },
11301
11302     // private
11303     onKeyDown : function(e){
11304         if(this.isVisible()){
11305             this.fireEvent("keydown", this, e);
11306         }
11307     },
11308
11309     /**
11310      * Resizes the dialog.
11311      * @param {Number} width
11312      * @param {Number} height
11313      * @return {Roo.BasicDialog} this
11314      */
11315     resizeTo : function(width, height){
11316         this.el.setSize(width, height);
11317         this.size = {width: width, height: height};
11318         this.syncBodyHeight();
11319         if(this.fixedcenter){
11320             this.center();
11321         }
11322         if(this.isVisible()){
11323             this.constrainXY();
11324             this.adjustAssets();
11325         }
11326         this.fireEvent("resize", this, width, height);
11327         return this;
11328     },
11329
11330
11331     /**
11332      * Resizes the dialog to fit the specified content size.
11333      * @param {Number} width
11334      * @param {Number} height
11335      * @return {Roo.BasicDialog} this
11336      */
11337     setContentSize : function(w, h){
11338         h += this.getHeaderFooterHeight() + this.body.getMargins("tb");
11339         w += this.body.getMargins("lr") + this.bwrap.getMargins("lr") + this.centerBg.getPadding("lr");
11340         //if(!this.el.isBorderBox()){
11341             h +=  this.body.getPadding("tb") + this.bwrap.getBorderWidth("tb") + this.body.getBorderWidth("tb") + this.el.getBorderWidth("tb");
11342             w += this.body.getPadding("lr") + this.bwrap.getBorderWidth("lr") + this.body.getBorderWidth("lr") + this.bwrap.getPadding("lr") + this.el.getBorderWidth("lr");
11343         //}
11344         if(this.tabs){
11345             h += this.tabs.stripWrap.getHeight() + this.tabs.bodyEl.getMargins("tb") + this.tabs.bodyEl.getPadding("tb");
11346             w += this.tabs.bodyEl.getMargins("lr") + this.tabs.bodyEl.getPadding("lr");
11347         }
11348         this.resizeTo(w, h);
11349         return this;
11350     },
11351
11352     /**
11353      * Adds a key listener for when this dialog is displayed.  This allows you to hook in a function that will be
11354      * executed in response to a particular key being pressed while the dialog is active.
11355      * @param {Number/Array/Object} key Either the numeric key code, array of key codes or an object with the following options:
11356      *                                  {key: (number or array), shift: (true/false), ctrl: (true/false), alt: (true/false)}
11357      * @param {Function} fn The function to call
11358      * @param {Object} scope (optional) The scope of the function
11359      * @return {Roo.BasicDialog} this
11360      */
11361     addKeyListener : function(key, fn, scope){
11362         var keyCode, shift, ctrl, alt;
11363         if(typeof key == "object" && !(key instanceof Array)){
11364             keyCode = key["key"];
11365             shift = key["shift"];
11366             ctrl = key["ctrl"];
11367             alt = key["alt"];
11368         }else{
11369             keyCode = key;
11370         }
11371         var handler = function(dlg, e){
11372             if((!shift || e.shiftKey) && (!ctrl || e.ctrlKey) &&  (!alt || e.altKey)){
11373                 var k = e.getKey();
11374                 if(keyCode instanceof Array){
11375                     for(var i = 0, len = keyCode.length; i < len; i++){
11376                         if(keyCode[i] == k){
11377                           fn.call(scope || window, dlg, k, e);
11378                           return;
11379                         }
11380                     }
11381                 }else{
11382                     if(k == keyCode){
11383                         fn.call(scope || window, dlg, k, e);
11384                     }
11385                 }
11386             }
11387         };
11388         this.on("keydown", handler);
11389         return this;
11390     },
11391
11392     /**
11393      * Returns the panel.Tab component (creates it if it doesn't exist).
11394      * Note: If you wish to simply check for the existence of tabs without creating them,
11395      * check for a null 'tabs' property.
11396      * @return {Roo.panel.Tab} The tabs component
11397      */
11398     getTabs : function(){
11399         if(!this.tabs){
11400             this.el.addClass("x-dlg-auto-tabs");
11401             this.body.addClass(this.tabPosition == "bottom" ? "x-tabs-bottom" : "x-tabs-top");
11402             this.tabs = new Roo.panel.Tab(this.body.dom, this.tabPosition == "bottom");
11403         }
11404         return this.tabs;
11405     },
11406
11407     /**
11408      * Adds a button to the footer section of the dialog.
11409      * @param {String/Object} config A string becomes the button text, an object can either be a Button config
11410      * object or a valid Roo.DomHelper element config
11411      * @param {Function} handler The function called when the button is clicked
11412      * @param {Object} scope (optional) The scope of the handler function (accepts position as a property)
11413      * @return {Roo.Button} The new button
11414      */
11415     addButton : function(config, handler, scope){
11416         var dh = Roo.DomHelper;
11417         if(!this.footer){
11418             this.footer = dh.append(this.bwrap, {tag: "div", cls:"x-dlg-ft"}, true);
11419         }
11420         if(!this.btnContainer){
11421             var tb = this.footer.createChild({
11422
11423                 cls:"x-dlg-btns x-dlg-btns-"+this.buttonAlign,
11424                 html:'<table cellspacing="0"><tbody><tr></tr></tbody></table><div class="x-clear"></div>'
11425             }, null, true);
11426             this.btnContainer = tb.firstChild.firstChild.firstChild;
11427         }
11428         var bconfig = {
11429             handler: handler,
11430             scope: scope,
11431             minWidth: this.minButtonWidth,
11432             hideParent:true
11433         };
11434         if(typeof config == "string"){
11435             bconfig.text = config;
11436         }else{
11437             if(config.tag){
11438                 bconfig.dhconfig = config;
11439             }else{
11440                 Roo.apply(bconfig, config);
11441             }
11442         }
11443         var fc = false;
11444         if ((typeof(bconfig.position) != 'undefined') && bconfig.position < this.btnContainer.childNodes.length-1) {
11445             bconfig.position = Math.max(0, bconfig.position);
11446             fc = this.btnContainer.childNodes[bconfig.position];
11447         }
11448          
11449         var btn = new Roo.Button(
11450             fc ? 
11451                 this.btnContainer.insertBefore(document.createElement("td"),fc)
11452                 : this.btnContainer.appendChild(document.createElement("td")),
11453             //Roo.get(this.btnContainer).createChild( { tag: 'td'},  fc ),
11454             bconfig
11455         );
11456         this.syncBodyHeight();
11457         if(!this.buttons){
11458             /**
11459              * Array of all the buttons that have been added to this dialog via addButton
11460              * @type Array
11461              */
11462             this.buttons = [];
11463         }
11464         this.buttons.push(btn);
11465         return btn;
11466     },
11467
11468     /**
11469      * Sets the default button to be focused when the dialog is displayed.
11470      * @param {Roo.BasicDialog.Button} btn The button object returned by {@link #addButton}
11471      * @return {Roo.BasicDialog} this
11472      */
11473     setDefaultButton : function(btn){
11474         this.defaultButton = btn;
11475         return this;
11476     },
11477
11478     // private
11479     getHeaderFooterHeight : function(safe){
11480         var height = 0;
11481         if(this.header){
11482            height += this.header.getHeight();
11483         }
11484         if(this.footer){
11485            var fm = this.footer.getMargins();
11486             height += (this.footer.getHeight()+fm.top+fm.bottom);
11487         }
11488         height += this.bwrap.getPadding("tb")+this.bwrap.getBorderWidth("tb");
11489         height += this.centerBg.getPadding("tb");
11490         return height;
11491     },
11492
11493     // private
11494     syncBodyHeight : function()
11495     {
11496         var bd = this.body, // the text
11497             cb = this.centerBg, // wrapper around bottom.. but does not seem to be used..
11498             bw = this.bwrap;
11499         var height = this.size.height - this.getHeaderFooterHeight(false);
11500         bd.setHeight(height-bd.getMargins("tb"));
11501         var hh = this.header.getHeight();
11502         var h = this.size.height-hh;
11503         cb.setHeight(h);
11504         
11505         bw.setLeftTop(cb.getPadding("l"), hh+cb.getPadding("t"));
11506         bw.setHeight(h-cb.getPadding("tb"));
11507         
11508         bw.setWidth(this.el.getWidth(true)-cb.getPadding("lr"));
11509         bd.setWidth(bw.getWidth(true));
11510         if(this.tabs){
11511             this.tabs.syncHeight();
11512             if(Roo.isIE){
11513                 this.tabs.el.repaint();
11514             }
11515         }
11516     },
11517
11518     /**
11519      * Restores the previous state of the dialog if Roo.state is configured.
11520      * @return {Roo.BasicDialog} this
11521      */
11522     restoreState : function(){
11523         var box = Roo.state.Manager.get(this.stateId || (this.el.id + "-state"));
11524         if(box && box.width){
11525             this.xy = [box.x, box.y];
11526             this.resizeTo(box.width, box.height);
11527         }
11528         return this;
11529     },
11530
11531     // private
11532     beforeShow : function(){
11533         this.expand();
11534         if(this.fixedcenter){
11535             this.xy = this.el.getCenterXY(true);
11536         }
11537         if(this.modal){
11538             Roo.get(document.body).addClass("x-body-masked");
11539             this.mask.setSize(Roo.lib.Dom.getViewWidth(true), Roo.lib.Dom.getViewHeight(true));
11540             this.mask.show();
11541         }
11542         this.constrainXY();
11543     },
11544
11545     // private
11546     animShow : function(){
11547         var b = Roo.get(this.animateTarget).getBox();
11548         this.proxy.setSize(b.width, b.height);
11549         this.proxy.setLocation(b.x, b.y);
11550         this.proxy.show();
11551         this.proxy.setBounds(this.xy[0], this.xy[1], this.size.width, this.size.height,
11552                     true, .35, this.showEl.createDelegate(this));
11553     },
11554
11555     /**
11556      * Shows the dialog.
11557      * @param {String/HTMLElement/Roo.Element} animateTarget (optional) Reset the animation target
11558      * @return {Roo.BasicDialog} this
11559      */
11560     show : function(animateTarget){
11561         if (this.fireEvent("beforeshow", this) === false){
11562             return;
11563         }
11564         if(this.syncHeightBeforeShow){
11565             this.syncBodyHeight();
11566         }else if(this.firstShow){
11567             this.firstShow = false;
11568             this.syncBodyHeight(); // sync the height on the first show instead of in the constructor
11569         }
11570         this.animateTarget = animateTarget || this.animateTarget;
11571         if(!this.el.isVisible()){
11572             this.beforeShow();
11573             if(this.animateTarget && Roo.get(this.animateTarget)){
11574                 this.animShow();
11575             }else{
11576                 this.showEl();
11577             }
11578         }
11579         return this;
11580     },
11581
11582     // private
11583     showEl : function(){
11584         this.proxy.hide();
11585         this.el.setXY(this.xy);
11586         this.el.show();
11587         this.adjustAssets(true);
11588         this.toFront();
11589         this.focus();
11590         // IE peekaboo bug - fix found by Dave Fenwick
11591         if(Roo.isIE){
11592             this.el.repaint();
11593         }
11594         this.fireEvent("show", this);
11595     },
11596
11597     /**
11598      * Focuses the dialog.  If a defaultButton is set, it will receive focus, otherwise the
11599      * dialog itself will receive focus.
11600      */
11601     focus : function(){
11602         if(this.defaultButton){
11603             this.defaultButton.focus();
11604         }else{
11605             this.focusEl.focus();
11606         }
11607     },
11608
11609     // private
11610     constrainXY : function(){
11611         if(this.constraintoviewport !== false){
11612             if(!this.viewSize){
11613                 if(this.container){
11614                     var s = this.container.getSize();
11615                     this.viewSize = [s.width, s.height];
11616                 }else{
11617                     this.viewSize = [Roo.lib.Dom.getViewWidth(),Roo.lib.Dom.getViewHeight()];
11618                 }
11619             }
11620             var s = Roo.get(this.container||document).getScroll();
11621
11622             var x = this.xy[0], y = this.xy[1];
11623             var w = this.size.width, h = this.size.height;
11624             var vw = this.viewSize[0], vh = this.viewSize[1];
11625             // only move it if it needs it
11626             var moved = false;
11627             // first validate right/bottom
11628             if(x + w > vw+s.left){
11629                 x = vw - w;
11630                 moved = true;
11631             }
11632             if(y + h > vh+s.top){
11633                 y = vh - h;
11634                 moved = true;
11635             }
11636             // then make sure top/left isn't negative
11637             if(x < s.left){
11638                 x = s.left;
11639                 moved = true;
11640             }
11641             if(y < s.top){
11642                 y = s.top;
11643                 moved = true;
11644             }
11645             if(moved){
11646                 // cache xy
11647                 this.xy = [x, y];
11648                 if(this.isVisible()){
11649                     this.el.setLocation(x, y);
11650                     this.adjustAssets();
11651                 }
11652             }
11653         }
11654     },
11655
11656     // private
11657     onDrag : function(){
11658         if(!this.proxyDrag){
11659             this.xy = this.el.getXY();
11660             this.adjustAssets();
11661         }
11662     },
11663
11664     // private
11665     adjustAssets : function(doShow){
11666         var x = this.xy[0], y = this.xy[1];
11667         var w = this.size.width, h = this.size.height;
11668         if(doShow === true){
11669             if(this.shadow){
11670                 this.shadow.show(this.el);
11671             }
11672             if(this.shim){
11673                 this.shim.show();
11674             }
11675         }
11676         if(this.shadow && this.shadow.isVisible()){
11677             this.shadow.show(this.el);
11678         }
11679         if(this.shim && this.shim.isVisible()){
11680             this.shim.setBounds(x, y, w, h);
11681         }
11682     },
11683
11684     // private
11685     adjustViewport : function(w, h){
11686         if(!w || !h){
11687             w = Roo.lib.Dom.getViewWidth();
11688             h = Roo.lib.Dom.getViewHeight();
11689         }
11690         // cache the size
11691         this.viewSize = [w, h];
11692         if(this.modal && this.mask.isVisible()){
11693             this.mask.setSize(w, h); // first make sure the mask isn't causing overflow
11694             this.mask.setSize(Roo.lib.Dom.getViewWidth(true), Roo.lib.Dom.getViewHeight(true));
11695         }
11696         if(this.isVisible()){
11697             this.constrainXY();
11698         }
11699     },
11700
11701     /**
11702      * Destroys this dialog and all its supporting elements (including any tabs, shim,
11703      * shadow, proxy, mask, etc.)  Also removes all event listeners.
11704      * @param {Boolean} removeEl (optional) true to remove the element from the DOM
11705      */
11706     destroy : function(removeEl){
11707         if(this.isVisible()){
11708             this.animateTarget = null;
11709             this.hide();
11710         }
11711         Roo.EventManager.removeResizeListener(this.adjustViewport, this);
11712         if(this.tabs){
11713             this.tabs.destroy(removeEl);
11714         }
11715         Roo.destroy(
11716              this.shim,
11717              this.proxy,
11718              this.resizer,
11719              this.close,
11720              this.mask
11721         );
11722         if(this.dd){
11723             this.dd.unreg();
11724         }
11725         if(this.buttons){
11726            for(var i = 0, len = this.buttons.length; i < len; i++){
11727                this.buttons[i].destroy();
11728            }
11729         }
11730         this.el.removeAllListeners();
11731         if(removeEl === true){
11732             this.el.update("");
11733             this.el.remove();
11734         }
11735         Roo.DialogManager.unregister(this);
11736     },
11737
11738     // private
11739     startMove : function(){
11740         if(this.proxyDrag){
11741             this.proxy.show();
11742         }
11743         if(this.constraintoviewport !== false){
11744             this.dd.constrainTo(document.body, {right: this.shadowOffset, bottom: this.shadowOffset});
11745         }
11746     },
11747
11748     // private
11749     endMove : function(){
11750         if(!this.proxyDrag){
11751             Roo.dd.DD.prototype.endDrag.apply(this.dd, arguments);
11752         }else{
11753             Roo.dd.DDProxy.prototype.endDrag.apply(this.dd, arguments);
11754             this.proxy.hide();
11755         }
11756         this.refreshSize();
11757         this.adjustAssets();
11758         this.focus();
11759         this.fireEvent("move", this, this.xy[0], this.xy[1]);
11760     },
11761
11762     /**
11763      * Brings this dialog to the front of any other visible dialogs
11764      * @return {Roo.BasicDialog} this
11765      */
11766     toFront : function(){
11767         Roo.DialogManager.bringToFront(this);
11768         return this;
11769     },
11770
11771     /**
11772      * Sends this dialog to the back (under) of any other visible dialogs
11773      * @return {Roo.BasicDialog} this
11774      */
11775     toBack : function(){
11776         Roo.DialogManager.sendToBack(this);
11777         return this;
11778     },
11779
11780     /**
11781      * Centers this dialog in the viewport
11782      * @return {Roo.BasicDialog} this
11783      */
11784     center : function(){
11785         var xy = this.el.getCenterXY(true);
11786         this.moveTo(xy[0], xy[1]);
11787         return this;
11788     },
11789
11790     /**
11791      * Moves the dialog's top-left corner to the specified point
11792      * @param {Number} x
11793      * @param {Number} y
11794      * @return {Roo.BasicDialog} this
11795      */
11796     moveTo : function(x, y){
11797         this.xy = [x,y];
11798         if(this.isVisible()){
11799             this.el.setXY(this.xy);
11800             this.adjustAssets();
11801         }
11802         return this;
11803     },
11804
11805     /**
11806      * Aligns the dialog to the specified element
11807      * @param {String/HTMLElement/Roo.Element} element The element to align to.
11808      * @param {String} position The position to align to (see {@link Roo.Element#alignTo} for more details).
11809      * @param {Array} offsets (optional) Offset the positioning by [x, y]
11810      * @return {Roo.BasicDialog} this
11811      */
11812     alignTo : function(element, position, offsets){
11813         this.xy = this.el.getAlignToXY(element, position, offsets);
11814         if(this.isVisible()){
11815             this.el.setXY(this.xy);
11816             this.adjustAssets();
11817         }
11818         return this;
11819     },
11820
11821     /**
11822      * Anchors an element to another element and realigns it when the window is resized.
11823      * @param {String/HTMLElement/Roo.Element} element The element to align to.
11824      * @param {String} position The position to align to (see {@link Roo.Element#alignTo} for more details)
11825      * @param {Array} offsets (optional) Offset the positioning by [x, y]
11826      * @param {Boolean/Number} monitorScroll (optional) true to monitor body scroll and reposition. If this parameter
11827      * is a number, it is used as the buffer delay (defaults to 50ms).
11828      * @return {Roo.BasicDialog} this
11829      */
11830     anchorTo : function(el, alignment, offsets, monitorScroll){
11831         var action = function(){
11832             this.alignTo(el, alignment, offsets);
11833         };
11834         Roo.EventManager.onWindowResize(action, this);
11835         var tm = typeof monitorScroll;
11836         if(tm != 'undefined'){
11837             Roo.EventManager.on(window, 'scroll', action, this,
11838                 {buffer: tm == 'number' ? monitorScroll : 50});
11839         }
11840         action.call(this);
11841         return this;
11842     },
11843
11844     /**
11845      * Returns true if the dialog is visible
11846      * @return {Boolean}
11847      */
11848     isVisible : function(){
11849         return this.el.isVisible();
11850     },
11851
11852     // private
11853     animHide : function(callback){
11854         var b = Roo.get(this.animateTarget).getBox();
11855         this.proxy.show();
11856         this.proxy.setBounds(this.xy[0], this.xy[1], this.size.width, this.size.height);
11857         this.el.hide();
11858         this.proxy.setBounds(b.x, b.y, b.width, b.height, true, .35,
11859                     this.hideEl.createDelegate(this, [callback]));
11860     },
11861
11862     /**
11863      * Hides the dialog.
11864      * @param {Function} callback (optional) Function to call when the dialog is hidden
11865      * @return {Roo.BasicDialog} this
11866      */
11867     hide : function(callback){
11868         if (this.fireEvent("beforehide", this) === false){
11869             return;
11870         }
11871         if(this.shadow){
11872             this.shadow.hide();
11873         }
11874         if(this.shim) {
11875           this.shim.hide();
11876         }
11877         // sometimes animateTarget seems to get set.. causing problems...
11878         // this just double checks..
11879         if(this.animateTarget && Roo.get(this.animateTarget)) {
11880            this.animHide(callback);
11881         }else{
11882             this.el.hide();
11883             this.hideEl(callback);
11884         }
11885         return this;
11886     },
11887
11888     // private
11889     hideEl : function(callback){
11890         this.proxy.hide();
11891         if(this.modal){
11892             this.mask.hide();
11893             Roo.get(document.body).removeClass("x-body-masked");
11894         }
11895         this.fireEvent("hide", this);
11896         if(typeof callback == "function"){
11897             callback();
11898         }
11899     },
11900
11901     // private
11902     hideAction : function(){
11903         this.setLeft("-10000px");
11904         this.setTop("-10000px");
11905         this.setStyle("visibility", "hidden");
11906     },
11907
11908     // private
11909     refreshSize : function(){
11910         this.size = this.el.getSize();
11911         this.xy = this.el.getXY();
11912         Roo.state.Manager.set(this.stateId || this.el.id + "-state", this.el.getBox());
11913     },
11914
11915     // private
11916     // z-index is managed by the DialogManager and may be overwritten at any time
11917     setZIndex : function(index){
11918         if(this.modal){
11919             this.mask.setStyle("z-index", index);
11920         }
11921         if(this.shim){
11922             this.shim.setStyle("z-index", ++index);
11923         }
11924         if(this.shadow){
11925             this.shadow.setZIndex(++index);
11926         }
11927         this.el.setStyle("z-index", ++index);
11928         if(this.proxy){
11929             this.proxy.setStyle("z-index", ++index);
11930         }
11931         if(this.resizer){
11932             this.resizer.proxy.setStyle("z-index", ++index);
11933         }
11934
11935         this.lastZIndex = index;
11936     },
11937
11938     /**
11939      * Returns the element for this dialog
11940      * @return {Roo.Element} The underlying dialog Element
11941      */
11942     getEl : function(){
11943         return this.el;
11944     }
11945 });
11946
11947 /**
11948  * @class Roo.DialogManager
11949  * Provides global access to BasicDialogs that have been created and
11950  * support for z-indexing (layering) multiple open dialogs.
11951  */
11952 Roo.DialogManager = function(){
11953     var list = {};
11954     var accessList = [];
11955     var front = null;
11956
11957     // private
11958     var sortDialogs = function(d1, d2){
11959         return (!d1._lastAccess || d1._lastAccess < d2._lastAccess) ? -1 : 1;
11960     };
11961
11962     // private
11963     var orderDialogs = function(){
11964         accessList.sort(sortDialogs);
11965         var seed = Roo.DialogManager.zseed;
11966         for(var i = 0, len = accessList.length; i < len; i++){
11967             var dlg = accessList[i];
11968             if(dlg){
11969                 dlg.setZIndex(seed + (i*10));
11970             }
11971         }
11972     };
11973
11974     return {
11975         /**
11976          * The starting z-index for BasicDialogs (defaults to 9000)
11977          * @type Number The z-index value
11978          */
11979         zseed : 9000,
11980
11981         // private
11982         register : function(dlg){
11983             list[dlg.id] = dlg;
11984             accessList.push(dlg);
11985         },
11986
11987         // private
11988         unregister : function(dlg){
11989             delete list[dlg.id];
11990             var i=0;
11991             var len=0;
11992             if(!accessList.indexOf){
11993                 for(  i = 0, len = accessList.length; i < len; i++){
11994                     if(accessList[i] == dlg){
11995                         accessList.splice(i, 1);
11996                         return;
11997                     }
11998                 }
11999             }else{
12000                  i = accessList.indexOf(dlg);
12001                 if(i != -1){
12002                     accessList.splice(i, 1);
12003                 }
12004             }
12005         },
12006
12007         /**
12008          * Gets a registered dialog by id
12009          * @param {String/Object} id The id of the dialog or a dialog
12010          * @return {Roo.BasicDialog} this
12011          */
12012         get : function(id){
12013             return typeof id == "object" ? id : list[id];
12014         },
12015
12016         /**
12017          * Brings the specified dialog to the front
12018          * @param {String/Object} dlg The id of the dialog or a dialog
12019          * @return {Roo.BasicDialog} this
12020          */
12021         bringToFront : function(dlg){
12022             dlg = this.get(dlg);
12023             if(dlg != front){
12024                 front = dlg;
12025                 dlg._lastAccess = new Date().getTime();
12026                 orderDialogs();
12027             }
12028             return dlg;
12029         },
12030
12031         /**
12032          * Sends the specified dialog to the back
12033          * @param {String/Object} dlg The id of the dialog or a dialog
12034          * @return {Roo.BasicDialog} this
12035          */
12036         sendToBack : function(dlg){
12037             dlg = this.get(dlg);
12038             dlg._lastAccess = -(new Date().getTime());
12039             orderDialogs();
12040             return dlg;
12041         },
12042
12043         /**
12044          * Hides all dialogs
12045          */
12046         hideAll : function(){
12047             for(var id in list){
12048                 if(list[id] && typeof list[id] != "function" && list[id].isVisible()){
12049                     list[id].hide();
12050                 }
12051             }
12052         }
12053     };
12054 }();
12055
12056 /**
12057  * @class Roo.LayoutDialog
12058  * @extends Roo.BasicDialog
12059  * @children Roo.panel.Content
12060  * @parent builder none
12061  * Dialog which provides adjustments for working with a layout in a Dialog.
12062  * Add your necessary layout config options to the dialog's config.<br>
12063  * Example usage (including a nested layout):
12064  * <pre><code>
12065 if(!dialog){
12066     dialog = new Roo.LayoutDialog("download-dlg", {
12067         modal: true,
12068         width:600,
12069         height:450,
12070         shadow:true,
12071         minWidth:500,
12072         minHeight:350,
12073         autoTabs:true,
12074         proxyDrag:true,
12075         // layout config merges with the dialog config
12076         center:{
12077             tabPosition: "top",
12078             alwaysShowTabs: true
12079         }
12080     });
12081     dialog.addKeyListener(27, dialog.hide, dialog);
12082     dialog.setDefaultButton(dialog.addButton("Close", dialog.hide, dialog));
12083     dialog.addButton("Build It!", this.getDownload, this);
12084
12085     // we can even add nested layouts
12086     var innerLayout = new Roo.layout.Border("dl-inner", {
12087         east: {
12088             initialSize: 200,
12089             autoScroll:true,
12090             split:true
12091         },
12092         center: {
12093             autoScroll:true
12094         }
12095     });
12096     innerLayout.beginUpdate();
12097     innerLayout.add("east", new Roo.panel.Content("dl-details"));
12098     innerLayout.add("center", new Roo.panel.Content("selection-panel"));
12099     innerLayout.endUpdate(true);
12100
12101     var layout = dialog.getLayout();
12102     layout.beginUpdate();
12103     layout.add("center", new Roo.panel.Content("standard-panel",
12104                         {title: "Download the Source", fitToFrame:true}));
12105     layout.add("center", new Roo.panel.NestedLayout(innerLayout,
12106                {title: "Build your own roo.js"}));
12107     layout.getRegion("center").showPanel(sp);
12108     layout.endUpdate();
12109 }
12110 </code></pre>
12111     * @constructor
12112     * @param {String/HTMLElement/Roo.Element} el The id of or container element, or config
12113     * @param {Object} config configuration options
12114   */
12115 Roo.LayoutDialog = function(el, cfg){
12116     
12117     var config=  cfg;
12118     if (typeof(cfg) == 'undefined') {
12119         config = Roo.apply({}, el);
12120         // not sure why we use documentElement here.. - it should always be body.
12121         // IE7 borks horribly if we use documentElement.
12122         // webkit also does not like documentElement - it creates a body element...
12123         el = Roo.get( document.body || document.documentElement ).createChild();
12124         //config.autoCreate = true;
12125     }
12126     
12127     
12128     config.autoTabs = false;
12129     Roo.LayoutDialog.superclass.constructor.call(this, el, config);
12130     this.body.setStyle({overflow:"hidden", position:"relative"});
12131     this.layout = new Roo.layout.Border(this.body.dom, config);
12132     this.layout.monitorWindowResize = false;
12133     this.el.addClass("x-dlg-auto-layout");
12134     // fix case when center region overwrites center function
12135     this.center = Roo.BasicDialog.prototype.center;
12136     this.on("show", this.layout.layout, this.layout, true);
12137     if (config.items) {
12138         var xitems = config.items;
12139         delete config.items;
12140         Roo.each(xitems, this.addxtype, this);
12141     }
12142     
12143     
12144 };
12145 Roo.extend(Roo.LayoutDialog, Roo.BasicDialog, {
12146     
12147     
12148     /**
12149      * @cfg {Roo.layout.Region} east  
12150      */
12151     /**
12152      * @cfg {Roo.layout.Region} west
12153      */
12154     /**
12155      * @cfg {Roo.layout.Region} south
12156      */
12157     /**
12158      * @cfg {Roo.layout.Region} north
12159      */
12160     /**
12161      * @cfg {Roo.layout.Region} center
12162      */
12163     /**
12164      * @cfg {Roo.Button} buttons[]  Bottom buttons..
12165      */
12166     
12167     
12168     /**
12169      * Ends update of the layout <strike>and resets display to none</strike>. Use standard beginUpdate/endUpdate on the layout.
12170      * @deprecated
12171      */
12172     endUpdate : function(){
12173         this.layout.endUpdate();
12174     },
12175
12176     /**
12177      * Begins an update of the layout <strike>and sets display to block and visibility to hidden</strike>. Use standard beginUpdate/endUpdate on the layout.
12178      *  @deprecated
12179      */
12180     beginUpdate : function(){
12181         this.layout.beginUpdate();
12182     },
12183
12184     /**
12185      * Get the BorderLayout for this dialog
12186      * @return {Roo.layout.Border}
12187      */
12188     getLayout : function(){
12189         return this.layout;
12190     },
12191
12192     showEl : function(){
12193         Roo.LayoutDialog.superclass.showEl.apply(this, arguments);
12194         if(Roo.isIE7){
12195             this.layout.layout();
12196         }
12197     },
12198
12199     // private
12200     // Use the syncHeightBeforeShow config option to control this automatically
12201     syncBodyHeight : function(){
12202         Roo.LayoutDialog.superclass.syncBodyHeight.call(this);
12203         if(this.layout){this.layout.layout();}
12204     },
12205     
12206       /**
12207      * Add an xtype element (actually adds to the layout.)
12208      * @return {Object} xdata xtype object data.
12209      */
12210     
12211     addxtype : function(c) {
12212         return this.layout.addxtype(c);
12213     }
12214 });/*
12215  * Based on:
12216  * Ext JS Library 1.1.1
12217  * Copyright(c) 2006-2007, Ext JS, LLC.
12218  *
12219  * Originally Released Under LGPL - original licence link has changed is not relivant.
12220  *
12221  * Fork - LGPL
12222  * <script type="text/javascript">
12223  */
12224  
12225 /**
12226  * @class Roo.MessageBox
12227  * @static
12228  * Utility class for generating different styles of message boxes.  The alias Roo.Msg can also be used.
12229  * Example usage:
12230  *<pre><code>
12231 // Basic alert:
12232 Roo.Msg.alert('Status', 'Changes saved successfully.');
12233
12234 // Prompt for user data:
12235 Roo.Msg.prompt('Name', 'Please enter your name:', function(btn, text){
12236     if (btn == 'ok'){
12237         // process text value...
12238     }
12239 });
12240
12241 // Show a dialog using config options:
12242 Roo.Msg.show({
12243    title:'Save Changes?',
12244    msg: 'Your are closing a tab that has unsaved changes. Would you like to save your changes?',
12245    buttons: Roo.Msg.YESNOCANCEL,
12246    fn: processResult,
12247    animEl: 'elId'
12248 });
12249 </code></pre>
12250  * @static
12251  */
12252 Roo.MessageBox = function(){
12253     var dlg, opt, mask, waitTimer;
12254     var bodyEl, msgEl, textboxEl, textareaEl, progressEl, pp;
12255     var buttons, activeTextEl, bwidth;
12256
12257     // private
12258     var handleButton = function(button){
12259         dlg.hide();
12260         Roo.callback(opt.fn, opt.scope||window, [button, activeTextEl.dom.value], 1);
12261     };
12262
12263     // private
12264     var handleHide = function(){
12265         if(opt && opt.cls){
12266             dlg.el.removeClass(opt.cls);
12267         }
12268         if(waitTimer){
12269             Roo.TaskMgr.stop(waitTimer);
12270             waitTimer = null;
12271         }
12272     };
12273
12274     // private
12275     var updateButtons = function(b){
12276         var width = 0;
12277         if(!b){
12278             buttons["ok"].hide();
12279             buttons["cancel"].hide();
12280             buttons["yes"].hide();
12281             buttons["no"].hide();
12282             dlg.footer.dom.style.display = 'none';
12283             return width;
12284         }
12285         dlg.footer.dom.style.display = '';
12286         for(var k in buttons){
12287             if(typeof buttons[k] != "function"){
12288                 if(b[k]){
12289                     buttons[k].show();
12290                     buttons[k].setText(typeof b[k] == "string" ? b[k] : Roo.MessageBox.buttonText[k]);
12291                     width += buttons[k].el.getWidth()+15;
12292                 }else{
12293                     buttons[k].hide();
12294                 }
12295             }
12296         }
12297         return width;
12298     };
12299
12300     // private
12301     var handleEsc = function(d, k, e){
12302         if(opt && opt.closable !== false){
12303             dlg.hide();
12304         }
12305         if(e){
12306             e.stopEvent();
12307         }
12308     };
12309
12310     return {
12311         /**
12312          * Returns a reference to the underlying {@link Roo.BasicDialog} element
12313          * @return {Roo.BasicDialog} The BasicDialog element
12314          */
12315         getDialog : function(){
12316            if(!dlg){
12317                 dlg = new Roo.BasicDialog("x-msg-box", {
12318                     autoCreate : true,
12319                     shadow: true,
12320                     draggable: true,
12321                     resizable:false,
12322                     constraintoviewport:false,
12323                     fixedcenter:true,
12324                     collapsible : false,
12325                     shim:true,
12326                     modal: true,
12327                     width:400, height:100,
12328                     buttonAlign:"center",
12329                     closeClick : function(){
12330                         if(opt && opt.buttons && opt.buttons.no && !opt.buttons.cancel){
12331                             handleButton("no");
12332                         }else{
12333                             handleButton("cancel");
12334                         }
12335                     }
12336                 });
12337               
12338                 dlg.on("hide", handleHide);
12339                 mask = dlg.mask;
12340                 dlg.addKeyListener(27, handleEsc);
12341                 buttons = {};
12342                 var bt = this.buttonText;
12343                 buttons["ok"] = dlg.addButton(bt["ok"], handleButton.createCallback("ok"));
12344                 buttons["yes"] = dlg.addButton(bt["yes"], handleButton.createCallback("yes"));
12345                 buttons["no"] = dlg.addButton(bt["no"], handleButton.createCallback("no"));
12346                 buttons["cancel"] = dlg.addButton(bt["cancel"], handleButton.createCallback("cancel"));
12347                 bodyEl = dlg.body.createChild({
12348
12349                     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>'
12350                 });
12351                 msgEl = bodyEl.dom.firstChild;
12352                 textboxEl = Roo.get(bodyEl.dom.childNodes[2]);
12353                 textboxEl.enableDisplayMode();
12354                 textboxEl.addKeyListener([10,13], function(){
12355                     if(dlg.isVisible() && opt && opt.buttons){
12356                         if(opt.buttons.ok){
12357                             handleButton("ok");
12358                         }else if(opt.buttons.yes){
12359                             handleButton("yes");
12360                         }
12361                     }
12362                 });
12363                 textareaEl = Roo.get(bodyEl.dom.childNodes[3]);
12364                 textareaEl.enableDisplayMode();
12365                 progressEl = Roo.get(bodyEl.dom.childNodes[4]);
12366                 progressEl.enableDisplayMode();
12367                 var pf = progressEl.dom.firstChild;
12368                 if (pf) {
12369                     pp = Roo.get(pf.firstChild);
12370                     pp.setHeight(pf.offsetHeight);
12371                 }
12372                 
12373             }
12374             return dlg;
12375         },
12376
12377         /**
12378          * Updates the message box body text
12379          * @param {String} text (optional) Replaces the message box element's innerHTML with the specified string (defaults to
12380          * the XHTML-compliant non-breaking space character '&amp;#160;')
12381          * @return {Roo.MessageBox} This message box
12382          */
12383         updateText : function(text){
12384             if(!dlg.isVisible() && !opt.width){
12385                 dlg.resizeTo(this.maxWidth, 100); // resize first so content is never clipped from previous shows
12386             }
12387             msgEl.innerHTML = text || '&#160;';
12388       
12389             var cw =  Math.max(msgEl.offsetWidth, msgEl.parentNode.scrollWidth);
12390             //Roo.log("guesed size: " + JSON.stringify([cw,msgEl.offsetWidth, msgEl.parentNode.scrollWidth]));
12391             var w = Math.max(
12392                     Math.min(opt.width || cw , this.maxWidth), 
12393                     Math.max(opt.minWidth || this.minWidth, bwidth)
12394             );
12395             if(opt.prompt){
12396                 activeTextEl.setWidth(w);
12397             }
12398             if(dlg.isVisible()){
12399                 dlg.fixedcenter = false;
12400             }
12401             // to big, make it scroll. = But as usual stupid IE does not support
12402             // !important..
12403             
12404             if ( bodyEl.getHeight() > (Roo.lib.Dom.getViewHeight() - 100)) {
12405                 bodyEl.setHeight ( Roo.lib.Dom.getViewHeight() - 100 );
12406                 bodyEl.dom.style.overflowY = 'auto' + ( Roo.isIE ? '' : ' !important');
12407             } else {
12408                 bodyEl.dom.style.height = '';
12409                 bodyEl.dom.style.overflowY = '';
12410             }
12411             if (cw > w) {
12412                 bodyEl.dom.style.get = 'auto' + ( Roo.isIE ? '' : ' !important');
12413             } else {
12414                 bodyEl.dom.style.overflowX = '';
12415             }
12416             
12417             dlg.setContentSize(w, bodyEl.getHeight());
12418             if(dlg.isVisible()){
12419                 dlg.fixedcenter = true;
12420             }
12421             return this;
12422         },
12423
12424         /**
12425          * Updates a progress-style message box's text and progress bar.  Only relevant on message boxes
12426          * initiated via {@link Roo.MessageBox#progress} or by calling {@link Roo.MessageBox#show} with progress: true.
12427          * @param {Number} value Any number between 0 and 1 (e.g., .5)
12428          * @param {String} text (optional) If defined, the message box's body text is replaced with the specified string (defaults to undefined)
12429          * @return {Roo.MessageBox} This message box
12430          */
12431         updateProgress : function(value, text){
12432             if(text){
12433                 this.updateText(text);
12434             }
12435             if (pp) { // weird bug on my firefox - for some reason this is not defined
12436                 pp.setWidth(Math.floor(value*progressEl.dom.firstChild.offsetWidth));
12437             }
12438             return this;
12439         },        
12440
12441         /**
12442          * Returns true if the message box is currently displayed
12443          * @return {Boolean} True if the message box is visible, else false
12444          */
12445         isVisible : function(){
12446             return dlg && dlg.isVisible();  
12447         },
12448
12449         /**
12450          * Hides the message box if it is displayed
12451          */
12452         hide : function(){
12453             if(this.isVisible()){
12454                 dlg.hide();
12455             }  
12456         },
12457
12458         /**
12459          * Displays a new message box, or reinitializes an existing message box, based on the config options
12460          * passed in. All functions (e.g. prompt, alert, etc) on MessageBox call this function internally.
12461          * The following config object properties are supported:
12462          * <pre>
12463 Property    Type             Description
12464 ----------  ---------------  ------------------------------------------------------------------------------------
12465 animEl            String/Element   An id or Element from which the message box should animate as it opens and
12466                                    closes (defaults to undefined)
12467 buttons           Object/Boolean   A button config object (e.g., Roo.MessageBox.OKCANCEL or {ok:'Foo',
12468                                    cancel:'Bar'}), or false to not show any buttons (defaults to false)
12469 closable          Boolean          False to hide the top-right close button (defaults to true).  Note that
12470                                    progress and wait dialogs will ignore this property and always hide the
12471                                    close button as they can only be closed programmatically.
12472 cls               String           A custom CSS class to apply to the message box element
12473 defaultTextHeight Number           The default height in pixels of the message box's multiline textarea if
12474                                    displayed (defaults to 75)
12475 fn                Function         A callback function to execute after closing the dialog.  The arguments to the
12476                                    function will be btn (the name of the button that was clicked, if applicable,
12477                                    e.g. "ok"), and text (the value of the active text field, if applicable).
12478                                    Progress and wait dialogs will ignore this option since they do not respond to
12479                                    user actions and can only be closed programmatically, so any required function
12480                                    should be called by the same code after it closes the dialog.
12481 icon              String           A CSS class that provides a background image to be used as an icon for
12482                                    the dialog (e.g., Roo.MessageBox.WARNING or 'custom-class', defaults to '')
12483 maxWidth          Number           The maximum width in pixels of the message box (defaults to 600)
12484 minWidth          Number           The minimum width in pixels of the message box (defaults to 100)
12485 modal             Boolean          False to allow user interaction with the page while the message box is
12486                                    displayed (defaults to true)
12487 msg               String           A string that will replace the existing message box body text (defaults
12488                                    to the XHTML-compliant non-breaking space character '&#160;')
12489 multiline         Boolean          True to prompt the user to enter multi-line text (defaults to false)
12490 progress          Boolean          True to display a progress bar (defaults to false)
12491 progressText      String           The text to display inside the progress bar if progress = true (defaults to '')
12492 prompt            Boolean          True to prompt the user to enter single-line text (defaults to false)
12493 proxyDrag         Boolean          True to display a lightweight proxy while dragging (defaults to false)
12494 title             String           The title text
12495 value             String           The string value to set into the active textbox element if displayed
12496 wait              Boolean          True to display a progress bar (defaults to false)
12497 width             Number           The width of the dialog in pixels
12498 </pre>
12499          *
12500          * Example usage:
12501          * <pre><code>
12502 Roo.Msg.show({
12503    title: 'Address',
12504    msg: 'Please enter your address:',
12505    width: 300,
12506    buttons: Roo.MessageBox.OKCANCEL,
12507    multiline: true,
12508    fn: saveAddress,
12509    animEl: 'addAddressBtn'
12510 });
12511 </code></pre>
12512          * @param {Object} config Configuration options
12513          * @return {Roo.MessageBox} This message box
12514          */
12515         show : function(options)
12516         {
12517             
12518             // this causes nightmares if you show one dialog after another
12519             // especially on callbacks..
12520              
12521             if(this.isVisible()){
12522                 
12523                 this.hide();
12524                 Roo.log("[Roo.Messagebox] Show called while message displayed:" );
12525                 Roo.log("Old Dialog Message:" +  msgEl.innerHTML );
12526                 Roo.log("New Dialog Message:" +  options.msg )
12527                 //this.alert("ERROR", "Multiple dialogs where displayed at the same time");
12528                 //throw "Roo.MessageBox ERROR : Multiple dialogs where displayed at the same time";
12529                 
12530             }
12531             var d = this.getDialog();
12532             opt = options;
12533             d.setTitle(opt.title || "&#160;");
12534             d.close.setDisplayed(opt.closable !== false);
12535             activeTextEl = textboxEl;
12536             opt.prompt = opt.prompt || (opt.multiline ? true : false);
12537             if(opt.prompt){
12538                 if(opt.multiline){
12539                     textboxEl.hide();
12540                     textareaEl.show();
12541                     textareaEl.setHeight(typeof opt.multiline == "number" ?
12542                         opt.multiline : this.defaultTextHeight);
12543                     activeTextEl = textareaEl;
12544                 }else{
12545                     textboxEl.show();
12546                     textareaEl.hide();
12547                 }
12548             }else{
12549                 textboxEl.hide();
12550                 textareaEl.hide();
12551             }
12552             progressEl.setDisplayed(opt.progress === true);
12553             this.updateProgress(0);
12554             activeTextEl.dom.value = opt.value || "";
12555             if(opt.prompt){
12556                 dlg.setDefaultButton(activeTextEl);
12557             }else{
12558                 var bs = opt.buttons;
12559                 var db = null;
12560                 if(bs && bs.ok){
12561                     db = buttons["ok"];
12562                 }else if(bs && bs.yes){
12563                     db = buttons["yes"];
12564                 }
12565                 dlg.setDefaultButton(db);
12566             }
12567             bwidth = updateButtons(opt.buttons);
12568             this.updateText(opt.msg);
12569             if(opt.cls){
12570                 d.el.addClass(opt.cls);
12571             }
12572             d.proxyDrag = opt.proxyDrag === true;
12573             d.modal = opt.modal !== false;
12574             d.mask = opt.modal !== false ? mask : false;
12575             if(!d.isVisible()){
12576                 // force it to the end of the z-index stack so it gets a cursor in FF
12577                 document.body.appendChild(dlg.el.dom);
12578                 d.animateTarget = null;
12579                 d.show(options.animEl);
12580             }
12581             dlg.toFront();
12582             return this;
12583         },
12584
12585         /**
12586          * Displays a message box with a progress bar.  This message box has no buttons and is not closeable by
12587          * the user.  You are responsible for updating the progress bar as needed via {@link Roo.MessageBox#updateProgress}
12588          * and closing the message box when the process is complete.
12589          * @param {String} title The title bar text
12590          * @param {String} msg The message box body text
12591          * @return {Roo.MessageBox} This message box
12592          */
12593         progress : function(title, msg){
12594             this.show({
12595                 title : title,
12596                 msg : msg,
12597                 buttons: false,
12598                 progress:true,
12599                 closable:false,
12600                 minWidth: this.minProgressWidth,
12601                 modal : true
12602             });
12603             return this;
12604         },
12605
12606         /**
12607          * Displays a standard read-only message box with an OK button (comparable to the basic JavaScript Window.alert).
12608          * If a callback function is passed it will be called after the user clicks the button, and the
12609          * id of the button that was clicked will be passed as the only parameter to the callback
12610          * (could also be the top-right close button).
12611          * @param {String} title The title bar text
12612          * @param {String} msg The message box body text
12613          * @param {Function} fn (optional) The callback function invoked after the message box is closed
12614          * @param {Object} scope (optional) The scope of the callback function
12615          * @return {Roo.MessageBox} This message box
12616          */
12617         alert : function(title, msg, fn, scope){
12618             this.show({
12619                 title : title,
12620                 msg : msg,
12621                 buttons: this.OK,
12622                 fn: fn,
12623                 scope : scope,
12624                 modal : true
12625             });
12626             return this;
12627         },
12628
12629         /**
12630          * Displays a message box with an infinitely auto-updating progress bar.  This can be used to block user
12631          * interaction while waiting for a long-running process to complete that does not have defined intervals.
12632          * You are responsible for closing the message box when the process is complete.
12633          * @param {String} msg The message box body text
12634          * @param {String} title (optional) The title bar text
12635          * @return {Roo.MessageBox} This message box
12636          */
12637         wait : function(msg, title){
12638             this.show({
12639                 title : title,
12640                 msg : msg,
12641                 buttons: false,
12642                 closable:false,
12643                 progress:true,
12644                 modal:true,
12645                 width:300,
12646                 wait:true
12647             });
12648             waitTimer = Roo.TaskMgr.start({
12649                 run: function(i){
12650                     Roo.MessageBox.updateProgress(((((i+20)%20)+1)*5)*.01);
12651                 },
12652                 interval: 1000
12653             });
12654             return this;
12655         },
12656
12657         /**
12658          * Displays a confirmation message box with Yes and No buttons (comparable to JavaScript's Window.confirm).
12659          * If a callback function is passed it will be called after the user clicks either button, and the id of the
12660          * button that was clicked will be passed as the only parameter to the callback (could also be the top-right close button).
12661          * @param {String} title The title bar text
12662          * @param {String} msg The message box body text
12663          * @param {Function} fn (optional) The callback function invoked after the message box is closed
12664          * @param {Object} scope (optional) The scope of the callback function
12665          * @return {Roo.MessageBox} This message box
12666          */
12667         confirm : function(title, msg, fn, scope){
12668             this.show({
12669                 title : title,
12670                 msg : msg,
12671                 buttons: this.YESNO,
12672                 fn: fn,
12673                 scope : scope,
12674                 modal : true
12675             });
12676             return this;
12677         },
12678
12679         /**
12680          * Displays a message box with OK and Cancel buttons prompting the user to enter some text (comparable to
12681          * JavaScript's Window.prompt).  The prompt can be a single-line or multi-line textbox.  If a callback function
12682          * is passed it will be called after the user clicks either button, and the id of the button that was clicked
12683          * (could also be the top-right close button) and the text that was entered will be passed as the two
12684          * parameters to the callback.
12685          * @param {String} title The title bar text
12686          * @param {String} msg The message box body text
12687          * @param {Function} fn (optional) The callback function invoked after the message box is closed
12688          * @param {Object} scope (optional) The scope of the callback function
12689          * @param {Boolean/Number} multiline (optional) True to create a multiline textbox using the defaultTextHeight
12690          * property, or the height in pixels to create the textbox (defaults to false / single-line)
12691          * @return {Roo.MessageBox} This message box
12692          */
12693         prompt : function(title, msg, fn, scope, multiline){
12694             this.show({
12695                 title : title,
12696                 msg : msg,
12697                 buttons: this.OKCANCEL,
12698                 fn: fn,
12699                 minWidth:250,
12700                 scope : scope,
12701                 prompt:true,
12702                 multiline: multiline,
12703                 modal : true
12704             });
12705             return this;
12706         },
12707
12708         /**
12709          * Button config that displays a single OK button
12710          * @type Object
12711          */
12712         OK : {ok:true},
12713         /**
12714          * Button config that displays Yes and No buttons
12715          * @type Object
12716          */
12717         YESNO : {yes:true, no:true},
12718         /**
12719          * Button config that displays OK and Cancel buttons
12720          * @type Object
12721          */
12722         OKCANCEL : {ok:true, cancel:true},
12723         /**
12724          * Button config that displays Yes, No and Cancel buttons
12725          * @type Object
12726          */
12727         YESNOCANCEL : {yes:true, no:true, cancel:true},
12728
12729         /**
12730          * The default height in pixels of the message box's multiline textarea if displayed (defaults to 75)
12731          * @type Number
12732          */
12733         defaultTextHeight : 75,
12734         /**
12735          * The maximum width in pixels of the message box (defaults to 600)
12736          * @type Number
12737          */
12738         maxWidth : 600,
12739         /**
12740          * The minimum width in pixels of the message box (defaults to 100)
12741          * @type Number
12742          */
12743         minWidth : 100,
12744         /**
12745          * The minimum width in pixels of the message box if it is a progress-style dialog.  This is useful
12746          * for setting a different minimum width than text-only dialogs may need (defaults to 250)
12747          * @type Number
12748          */
12749         minProgressWidth : 250,
12750         /**
12751          * An object containing the default button text strings that can be overriden for localized language support.
12752          * Supported properties are: ok, cancel, yes and no.
12753          * Customize the default text like so: Roo.MessageBox.buttonText.yes = "S?";
12754          * @type Object
12755          */
12756         buttonText : {
12757             ok : "OK",
12758             cancel : "Cancel",
12759             yes : "Yes",
12760             no : "No"
12761         }
12762     };
12763 }();
12764
12765 /**
12766  * Shorthand for {@link Roo.MessageBox}
12767  */
12768 Roo.Msg = Roo.MessageBox;/*
12769  * Based on:
12770  * Ext JS Library 1.1.1
12771  * Copyright(c) 2006-2007, Ext JS, LLC.
12772  *
12773  * Originally Released Under LGPL - original licence link has changed is not relivant.
12774  *
12775  * Fork - LGPL
12776  * <script type="text/javascript">
12777  */
12778 /**
12779  * @class Roo.QuickTips
12780  * Provides attractive and customizable tooltips for any element.
12781  * @static
12782  */
12783 Roo.QuickTips = function(){
12784     var el, tipBody, tipBodyText, tipTitle, tm, cfg, close, tagEls = {}, esc, removeCls = null, bdLeft, bdRight;
12785     var ce, bd, xy, dd;
12786     var visible = false, disabled = true, inited = false;
12787     var showProc = 1, hideProc = 1, dismissProc = 1, locks = [];
12788     
12789     var onOver = function(e){
12790         if(disabled){
12791             return;
12792         }
12793         var t = e.getTarget();
12794         if(!t || t.nodeType !== 1 || t == document || t == document.body){
12795             return;
12796         }
12797         if(ce && t == ce.el){
12798             clearTimeout(hideProc);
12799             return;
12800         }
12801         if(t && tagEls[t.id]){
12802             tagEls[t.id].el = t;
12803             showProc = show.defer(tm.showDelay, tm, [tagEls[t.id]]);
12804             return;
12805         }
12806         var ttp, et = Roo.fly(t);
12807         var ns = cfg.namespace;
12808         if(tm.interceptTitles && t.title){
12809             ttp = t.title;
12810             t.qtip = ttp;
12811             t.removeAttribute("title");
12812             e.preventDefault();
12813         }else{
12814             ttp = t.qtip || et.getAttributeNS(ns, cfg.attribute) || et.getAttributeNS(cfg.alt_namespace, cfg.attribute) ;
12815         }
12816         if(ttp){
12817             showProc = show.defer(tm.showDelay, tm, [{
12818                 el: t, 
12819                 text: ttp.replace(/\\n/g,'<br/>'),
12820                 width: et.getAttributeNS(ns, cfg.width),
12821                 autoHide: et.getAttributeNS(ns, cfg.hide) != "user",
12822                 title: et.getAttributeNS(ns, cfg.title),
12823                     cls: et.getAttributeNS(ns, cfg.cls)
12824             }]);
12825         }
12826     };
12827     
12828     var onOut = function(e){
12829         clearTimeout(showProc);
12830         var t = e.getTarget();
12831         if(t && ce && ce.el == t && (tm.autoHide && ce.autoHide !== false)){
12832             hideProc = setTimeout(hide, tm.hideDelay);
12833         }
12834     };
12835     
12836     var onMove = function(e){
12837         if(disabled){
12838             return;
12839         }
12840         xy = e.getXY();
12841         xy[1] += 18;
12842         if(tm.trackMouse && ce){
12843             el.setXY(xy);
12844         }
12845     };
12846     
12847     var onDown = function(e){
12848         clearTimeout(showProc);
12849         clearTimeout(hideProc);
12850         if(!e.within(el)){
12851             if(tm.hideOnClick){
12852                 hide();
12853                 tm.disable();
12854                 tm.enable.defer(100, tm);
12855             }
12856         }
12857     };
12858     
12859     var getPad = function(){
12860         return 2;//bdLeft.getPadding('l')+bdRight.getPadding('r');
12861     };
12862
12863     var show = function(o){
12864         if(disabled){
12865             return;
12866         }
12867         clearTimeout(dismissProc);
12868         ce = o;
12869         if(removeCls){ // in case manually hidden
12870             el.removeClass(removeCls);
12871             removeCls = null;
12872         }
12873         if(ce.cls){
12874             el.addClass(ce.cls);
12875             removeCls = ce.cls;
12876         }
12877         if(ce.title){
12878             tipTitle.update(ce.title);
12879             tipTitle.show();
12880         }else{
12881             tipTitle.update('');
12882             tipTitle.hide();
12883         }
12884         el.dom.style.width  = tm.maxWidth+'px';
12885         //tipBody.dom.style.width = '';
12886         tipBodyText.update(o.text);
12887         var p = getPad(), w = ce.width;
12888         if(!w){
12889             var td = tipBodyText.dom;
12890             var aw = Math.max(td.offsetWidth, td.clientWidth, td.scrollWidth);
12891             if(aw > tm.maxWidth){
12892                 w = tm.maxWidth;
12893             }else if(aw < tm.minWidth){
12894                 w = tm.minWidth;
12895             }else{
12896                 w = aw;
12897             }
12898         }
12899         //tipBody.setWidth(w);
12900         el.setWidth(parseInt(w, 10) + p);
12901         if(ce.autoHide === false){
12902             close.setDisplayed(true);
12903             if(dd){
12904                 dd.unlock();
12905             }
12906         }else{
12907             close.setDisplayed(false);
12908             if(dd){
12909                 dd.lock();
12910             }
12911         }
12912         if(xy){
12913             el.avoidY = xy[1]-18;
12914             el.setXY(xy);
12915         }
12916         if(tm.animate){
12917             el.setOpacity(.1);
12918             el.setStyle("visibility", "visible");
12919             el.fadeIn({callback: afterShow});
12920         }else{
12921             afterShow();
12922         }
12923     };
12924     
12925     var afterShow = function(){
12926         if(ce){
12927             el.show();
12928             esc.enable();
12929             if(tm.autoDismiss && ce.autoHide !== false){
12930                 dismissProc = setTimeout(hide, tm.autoDismissDelay);
12931             }
12932         }
12933     };
12934     
12935     var hide = function(noanim){
12936         clearTimeout(dismissProc);
12937         clearTimeout(hideProc);
12938         ce = null;
12939         if(el.isVisible()){
12940             esc.disable();
12941             if(noanim !== true && tm.animate){
12942                 el.fadeOut({callback: afterHide});
12943             }else{
12944                 afterHide();
12945             } 
12946         }
12947     };
12948     
12949     var afterHide = function(){
12950         el.hide();
12951         if(removeCls){
12952             el.removeClass(removeCls);
12953             removeCls = null;
12954         }
12955     };
12956     
12957     return {
12958         /**
12959         * @cfg {Number} minWidth
12960         * The minimum width of the quick tip (defaults to 40)
12961         */
12962        minWidth : 40,
12963         /**
12964         * @cfg {Number} maxWidth
12965         * The maximum width of the quick tip (defaults to 300)
12966         */
12967        maxWidth : 300,
12968         /**
12969         * @cfg {Boolean} interceptTitles
12970         * True to automatically use the element's DOM title value if available (defaults to false)
12971         */
12972        interceptTitles : false,
12973         /**
12974         * @cfg {Boolean} trackMouse
12975         * True to have the quick tip follow the mouse as it moves over the target element (defaults to false)
12976         */
12977        trackMouse : false,
12978         /**
12979         * @cfg {Boolean} hideOnClick
12980         * True to hide the quick tip if the user clicks anywhere in the document (defaults to true)
12981         */
12982        hideOnClick : true,
12983         /**
12984         * @cfg {Number} showDelay
12985         * Delay in milliseconds before the quick tip displays after the mouse enters the target element (defaults to 500)
12986         */
12987        showDelay : 500,
12988         /**
12989         * @cfg {Number} hideDelay
12990         * Delay in milliseconds before the quick tip hides when autoHide = true (defaults to 200)
12991         */
12992        hideDelay : 200,
12993         /**
12994         * @cfg {Boolean} autoHide
12995         * True to automatically hide the quick tip after the mouse exits the target element (defaults to true).
12996         * Used in conjunction with hideDelay.
12997         */
12998        autoHide : true,
12999         /**
13000         * @cfg {Boolean}
13001         * True to automatically hide the quick tip after a set period of time, regardless of the user's actions
13002         * (defaults to true).  Used in conjunction with autoDismissDelay.
13003         */
13004        autoDismiss : true,
13005         /**
13006         * @cfg {Number}
13007         * Delay in milliseconds before the quick tip hides when autoDismiss = true (defaults to 5000)
13008         */
13009        autoDismissDelay : 5000,
13010        /**
13011         * @cfg {Boolean} animate
13012         * True to turn on fade animation. Defaults to false (ClearType/scrollbar flicker issues in IE7).
13013         */
13014        animate : false,
13015
13016        /**
13017         * @cfg {String} title
13018         * Title text to display (defaults to '').  This can be any valid HTML markup.
13019         */
13020         title: '',
13021        /**
13022         * @cfg {String} text
13023         * Body text to display (defaults to '').  This can be any valid HTML markup.
13024         */
13025         text : '',
13026        /**
13027         * @cfg {String} cls
13028         * A CSS class to apply to the base quick tip element (defaults to '').
13029         */
13030         cls : '',
13031        /**
13032         * @cfg {Number} width
13033         * Width in pixels of the quick tip (defaults to auto).  Width will be ignored if it exceeds the bounds of
13034         * minWidth or maxWidth.
13035         */
13036         width : null,
13037
13038     /**
13039      * Initialize and enable QuickTips for first use.  This should be called once before the first attempt to access
13040      * or display QuickTips in a page.
13041      */
13042        init : function(){
13043           tm = Roo.QuickTips;
13044           cfg = tm.tagConfig;
13045           if(!inited){
13046               if(!Roo.isReady){ // allow calling of init() before onReady
13047                   Roo.onReady(Roo.QuickTips.init, Roo.QuickTips);
13048                   return;
13049               }
13050               el = new Roo.Layer({cls:"x-tip", shadow:"drop", shim: true, constrain:true, shadowOffset:4});
13051               el.fxDefaults = {stopFx: true};
13052               // maximum custom styling
13053               //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>');
13054               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>');              
13055               tipTitle = el.child('h3');
13056               tipTitle.enableDisplayMode("block");
13057               tipBody = el.child('div.x-tip-bd');
13058               tipBodyText = el.child('div.x-tip-bd-inner');
13059               //bdLeft = el.child('div.x-tip-bd-left');
13060               //bdRight = el.child('div.x-tip-bd-right');
13061               close = el.child('div.x-tip-close');
13062               close.enableDisplayMode("block");
13063               close.on("click", hide);
13064               var d = Roo.get(document);
13065               d.on("mousedown", onDown);
13066               d.on("mouseover", onOver);
13067               d.on("mouseout", onOut);
13068               d.on("mousemove", onMove);
13069               esc = d.addKeyListener(27, hide);
13070               esc.disable();
13071               if(Roo.dd.DD){
13072                   dd = el.initDD("default", null, {
13073                       onDrag : function(){
13074                           el.sync();  
13075                       }
13076                   });
13077                   dd.setHandleElId(tipTitle.id);
13078                   dd.lock();
13079               }
13080               inited = true;
13081           }
13082           this.enable(); 
13083        },
13084
13085     /**
13086      * Configures a new quick tip instance and assigns it to a target element.  The following config options
13087      * are supported:
13088      * <pre>
13089 Property    Type                   Description
13090 ----------  ---------------------  ------------------------------------------------------------------------
13091 target      Element/String/Array   An Element, id or array of ids that this quick tip should be tied to
13092      * </ul>
13093      * @param {Object} config The config object
13094      */
13095        register : function(config){
13096            var cs = config instanceof Array ? config : arguments;
13097            for(var i = 0, len = cs.length; i < len; i++) {
13098                var c = cs[i];
13099                var target = c.target;
13100                if(target){
13101                    if(target instanceof Array){
13102                        for(var j = 0, jlen = target.length; j < jlen; j++){
13103                            tagEls[target[j]] = c;
13104                        }
13105                    }else{
13106                        tagEls[typeof target == 'string' ? target : Roo.id(target)] = c;
13107                    }
13108                }
13109            }
13110        },
13111
13112     /**
13113      * Removes this quick tip from its element and destroys it.
13114      * @param {String/HTMLElement/Element} el The element from which the quick tip is to be removed.
13115      */
13116        unregister : function(el){
13117            delete tagEls[Roo.id(el)];
13118        },
13119
13120     /**
13121      * Enable this quick tip.
13122      */
13123        enable : function(){
13124            if(inited && disabled){
13125                locks.pop();
13126                if(locks.length < 1){
13127                    disabled = false;
13128                }
13129            }
13130        },
13131
13132     /**
13133      * Disable this quick tip.
13134      */
13135        disable : function(){
13136           disabled = true;
13137           clearTimeout(showProc);
13138           clearTimeout(hideProc);
13139           clearTimeout(dismissProc);
13140           if(ce){
13141               hide(true);
13142           }
13143           locks.push(1);
13144        },
13145
13146     /**
13147      * Returns true if the quick tip is enabled, else false.
13148      */
13149        isEnabled : function(){
13150             return !disabled;
13151        },
13152
13153         // private
13154        tagConfig : {
13155            namespace : "roo", // was ext?? this may break..
13156            alt_namespace : "ext",
13157            attribute : "qtip",
13158            width : "width",
13159            target : "target",
13160            title : "qtitle",
13161            hide : "hide",
13162            cls : "qclass"
13163        }
13164    };
13165 }();
13166
13167 // backwards compat
13168 Roo.QuickTips.tips = Roo.QuickTips.register;/*
13169  * Based on:
13170  * Ext JS Library 1.1.1
13171  * Copyright(c) 2006-2007, Ext JS, LLC.
13172  *
13173  * Originally Released Under LGPL - original licence link has changed is not relivant.
13174  *
13175  * Fork - LGPL
13176  * <script type="text/javascript">
13177  */
13178  
13179
13180 /**
13181  * @class Roo.tree.TreePanel
13182  * @extends Roo.data.Tree
13183  * @cfg {Roo.tree.TreeNode} root The root node
13184  * @cfg {Boolean} rootVisible false to hide the root node (defaults to true)
13185  * @cfg {Boolean} lines false to disable tree lines (defaults to true)
13186  * @cfg {Boolean} enableDD true to enable drag and drop
13187  * @cfg {Boolean} enableDrag true to enable just drag
13188  * @cfg {Boolean} enableDrop true to enable just drop
13189  * @cfg {Object} dragConfig Custom config to pass to the {@link Roo.tree.TreeDragZone} instance
13190  * @cfg {Object} dropConfig Custom config to pass to the {@link Roo.tree.TreeDropZone} instance
13191  * @cfg {String} ddGroup The DD group this TreePanel belongs to
13192  * @cfg {String} ddAppendOnly True if the tree should only allow append drops (use for trees which are sorted)
13193  * @cfg {Boolean} ddScroll true to enable YUI body scrolling
13194  * @cfg {Boolean} containerScroll true to register this container with ScrollManager
13195  * @cfg {Boolean} hlDrop false to disable node highlight on drop (defaults to the value of Roo.enableFx)
13196  * @cfg {String} hlColor The color of the node highlight (defaults to C3DAF9)
13197  * @cfg {Boolean} animate true to enable animated expand/collapse (defaults to the value of Roo.enableFx)
13198  * @cfg {Boolean} singleExpand true if only 1 node per branch may be expanded
13199  * @cfg {Boolean} selModel A tree selection model to use with this TreePanel (defaults to a {@link Roo.tree.DefaultSelectionModel})
13200  * @cfg {Roo.tree.TreeLoader} loader A TreeLoader for use with this TreePanel
13201  * @cfg {Roo.tree.TreeEditor} editor The TreeEditor to display when clicked.
13202  * @cfg {String} pathSeparator The token used to separate sub-paths in path strings (defaults to '/')
13203  * @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>
13204  * @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>
13205  * 
13206  * @constructor
13207  * @param {String/HTMLElement/Element} el The container element
13208  * @param {Object} config
13209  */
13210 Roo.tree.TreePanel = function(el, config){
13211     var root = false;
13212     var loader = false;
13213     if (config.root) {
13214         root = config.root;
13215         delete config.root;
13216     }
13217     if (config.loader) {
13218         loader = config.loader;
13219         delete config.loader;
13220     }
13221     
13222     Roo.apply(this, config);
13223     Roo.tree.TreePanel.superclass.constructor.call(this);
13224     this.el = Roo.get(el);
13225     this.el.addClass('x-tree');
13226     //console.log(root);
13227     if (root) {
13228         this.setRootNode( Roo.factory(root, Roo.tree));
13229     }
13230     if (loader) {
13231         this.loader = Roo.factory(loader, Roo.tree);
13232     }
13233    /**
13234     * Read-only. The id of the container element becomes this TreePanel's id.
13235     */
13236     this.id = this.el.id;
13237     this.addEvents({
13238         /**
13239         * @event beforeload
13240         * Fires before a node is loaded, return false to cancel
13241         * @param {Node} node The node being loaded
13242         */
13243         "beforeload" : true,
13244         /**
13245         * @event load
13246         * Fires when a node is loaded
13247         * @param {Node} node The node that was loaded
13248         */
13249         "load" : true,
13250         /**
13251         * @event textchange
13252         * Fires when the text for a node is changed
13253         * @param {Node} node The node
13254         * @param {String} text The new text
13255         * @param {String} oldText The old text
13256         */
13257         "textchange" : true,
13258         /**
13259         * @event beforeexpand
13260         * Fires before a node is expanded, return false to cancel.
13261         * @param {Node} node The node
13262         * @param {Boolean} deep
13263         * @param {Boolean} anim
13264         */
13265         "beforeexpand" : true,
13266         /**
13267         * @event beforecollapse
13268         * Fires before a node is collapsed, return false to cancel.
13269         * @param {Node} node The node
13270         * @param {Boolean} deep
13271         * @param {Boolean} anim
13272         */
13273         "beforecollapse" : true,
13274         /**
13275         * @event expand
13276         * Fires when a node is expanded
13277         * @param {Node} node The node
13278         */
13279         "expand" : true,
13280         /**
13281         * @event disabledchange
13282         * Fires when the disabled status of a node changes
13283         * @param {Node} node The node
13284         * @param {Boolean} disabled
13285         */
13286         "disabledchange" : true,
13287         /**
13288         * @event collapse
13289         * Fires when a node is collapsed
13290         * @param {Node} node The node
13291         */
13292         "collapse" : true,
13293         /**
13294         * @event beforeclick
13295         * Fires before click processing on a node. Return false to cancel the default action.
13296         * @param {Node} node The node
13297         * @param {Roo.EventObject} e The event object
13298         */
13299         "beforeclick":true,
13300         /**
13301         * @event checkchange
13302         * Fires when a node with a checkbox's checked property changes
13303         * @param {Node} this This node
13304         * @param {Boolean} checked
13305         */
13306         "checkchange":true,
13307         /**
13308         * @event click
13309         * Fires when a node is clicked
13310         * @param {Node} node The node
13311         * @param {Roo.EventObject} e The event object
13312         */
13313         "click":true,
13314         /**
13315         * @event dblclick
13316         * Fires when a node is double clicked
13317         * @param {Node} node The node
13318         * @param {Roo.EventObject} e The event object
13319         */
13320         "dblclick":true,
13321         /**
13322         * @event contextmenu
13323         * Fires when a node is right clicked
13324         * @param {Node} node The node
13325         * @param {Roo.EventObject} e The event object
13326         */
13327         "contextmenu":true,
13328         /**
13329         * @event beforechildrenrendered
13330         * Fires right before the child nodes for a node are rendered
13331         * @param {Node} node The node
13332         */
13333         "beforechildrenrendered":true,
13334         /**
13335         * @event startdrag
13336         * Fires when a node starts being dragged
13337         * @param {Roo.tree.TreePanel} this
13338         * @param {Roo.tree.TreeNode} node
13339         * @param {event} e The raw browser event
13340         */ 
13341        "startdrag" : true,
13342        /**
13343         * @event enddrag
13344         * Fires when a drag operation is complete
13345         * @param {Roo.tree.TreePanel} this
13346         * @param {Roo.tree.TreeNode} node
13347         * @param {event} e The raw browser event
13348         */
13349        "enddrag" : true,
13350        /**
13351         * @event dragdrop
13352         * Fires when a dragged node is dropped on a valid DD target
13353         * @param {Roo.tree.TreePanel} this
13354         * @param {Roo.tree.TreeNode} node
13355         * @param {DD} dd The dd it was dropped on
13356         * @param {event} e The raw browser event
13357         */
13358        "dragdrop" : true,
13359        /**
13360         * @event beforenodedrop
13361         * Fires when a DD object is dropped on a node in this tree for preprocessing. Return false to cancel the drop. The dropEvent
13362         * passed to handlers has the following properties:<br />
13363         * <ul style="padding:5px;padding-left:16px;">
13364         * <li>tree - The TreePanel</li>
13365         * <li>target - The node being targeted for the drop</li>
13366         * <li>data - The drag data from the drag source</li>
13367         * <li>point - The point of the drop - append, above or below</li>
13368         * <li>source - The drag source</li>
13369         * <li>rawEvent - Raw mouse event</li>
13370         * <li>dropNode - Drop node(s) provided by the source <b>OR</b> you can supply node(s)
13371         * to be inserted by setting them on this object.</li>
13372         * <li>cancel - Set this to true to cancel the drop.</li>
13373         * </ul>
13374         * @param {Object} dropEvent
13375         */
13376        "beforenodedrop" : true,
13377        /**
13378         * @event nodedrop
13379         * Fires after a DD object is dropped on a node in this tree. The dropEvent
13380         * passed to handlers has the following properties:<br />
13381         * <ul style="padding:5px;padding-left:16px;">
13382         * <li>tree - The TreePanel</li>
13383         * <li>target - The node being targeted for the drop</li>
13384         * <li>data - The drag data from the drag source</li>
13385         * <li>point - The point of the drop - append, above or below</li>
13386         * <li>source - The drag source</li>
13387         * <li>rawEvent - Raw mouse event</li>
13388         * <li>dropNode - Dropped node(s).</li>
13389         * </ul>
13390         * @param {Object} dropEvent
13391         */
13392        "nodedrop" : true,
13393         /**
13394         * @event nodedragover
13395         * Fires when a tree node is being targeted for a drag drop, return false to signal drop not allowed. The dragOverEvent
13396         * passed to handlers has the following properties:<br />
13397         * <ul style="padding:5px;padding-left:16px;">
13398         * <li>tree - The TreePanel</li>
13399         * <li>target - The node being targeted for the drop</li>
13400         * <li>data - The drag data from the drag source</li>
13401         * <li>point - The point of the drop - append, above or below</li>
13402         * <li>source - The drag source</li>
13403         * <li>rawEvent - Raw mouse event</li>
13404         * <li>dropNode - Drop node(s) provided by the source.</li>
13405         * <li>cancel - Set this to true to signal drop not allowed.</li>
13406         * </ul>
13407         * @param {Object} dragOverEvent
13408         */
13409        "nodedragover" : true,
13410        /**
13411         * @event appendnode
13412         * Fires when append node to the tree
13413         * @param {Roo.tree.TreePanel} this
13414         * @param {Roo.tree.TreeNode} node
13415         * @param {Number} index The index of the newly appended node
13416         */
13417        "appendnode" : true
13418         
13419     });
13420     if(this.singleExpand){
13421        this.on("beforeexpand", this.restrictExpand, this);
13422     }
13423     if (this.editor) {
13424         this.editor.tree = this;
13425         this.editor = Roo.factory(this.editor, Roo.tree);
13426     }
13427     
13428     if (this.selModel) {
13429         this.selModel = Roo.factory(this.selModel, Roo.tree);
13430     }
13431    
13432 };
13433 Roo.extend(Roo.tree.TreePanel, Roo.data.Tree, {
13434     rootVisible : true,
13435     animate: Roo.enableFx,
13436     lines : true,
13437     enableDD : false,
13438     hlDrop : Roo.enableFx,
13439   
13440     renderer: false,
13441     
13442     rendererTip: false,
13443     // private
13444     restrictExpand : function(node){
13445         var p = node.parentNode;
13446         if(p){
13447             if(p.expandedChild && p.expandedChild.parentNode == p){
13448                 p.expandedChild.collapse();
13449             }
13450             p.expandedChild = node;
13451         }
13452     },
13453
13454     // private override
13455     setRootNode : function(node){
13456         Roo.tree.TreePanel.superclass.setRootNode.call(this, node);
13457         if(!this.rootVisible){
13458             node.ui = new Roo.tree.RootTreeNodeUI(node);
13459         }
13460         return node;
13461     },
13462
13463     /**
13464      * Returns the container element for this TreePanel
13465      */
13466     getEl : function(){
13467         return this.el;
13468     },
13469
13470     /**
13471      * Returns the default TreeLoader for this TreePanel
13472      */
13473     getLoader : function(){
13474         return this.loader;
13475     },
13476
13477     /**
13478      * Expand all nodes
13479      */
13480     expandAll : function(){
13481         this.root.expand(true);
13482     },
13483
13484     /**
13485      * Collapse all nodes
13486      */
13487     collapseAll : function(){
13488         this.root.collapse(true);
13489     },
13490
13491     /**
13492      * Returns the selection model used by this TreePanel
13493      */
13494     getSelectionModel : function(){
13495         if(!this.selModel){
13496             this.selModel = new Roo.tree.DefaultSelectionModel();
13497         }
13498         return this.selModel;
13499     },
13500
13501     /**
13502      * Retrieve an array of checked nodes, or an array of a specific attribute of checked nodes (e.g. "id")
13503      * @param {String} attribute (optional) Defaults to null (return the actual nodes)
13504      * @param {TreeNode} startNode (optional) The node to start from, defaults to the root
13505      * @return {Array}
13506      */
13507     getChecked : function(a, startNode){
13508         startNode = startNode || this.root;
13509         var r = [];
13510         var f = function(){
13511             if(this.attributes.checked){
13512                 r.push(!a ? this : (a == 'id' ? this.id : this.attributes[a]));
13513             }
13514         }
13515         startNode.cascade(f);
13516         return r;
13517     },
13518
13519     /**
13520      * Expands a specified path in this TreePanel. A path can be retrieved from a node with {@link Roo.data.Node#getPath}
13521      * @param {String} path
13522      * @param {String} attr (optional) The attribute used in the path (see {@link Roo.data.Node#getPath} for more info)
13523      * @param {Function} callback (optional) The callback to call when the expand is complete. The callback will be called with
13524      * (bSuccess, oLastNode) where bSuccess is if the expand was successful and oLastNode is the last node that was expanded.
13525      */
13526     expandPath : function(path, attr, callback){
13527         attr = attr || "id";
13528         var keys = path.split(this.pathSeparator);
13529         var curNode = this.root;
13530         if(curNode.attributes[attr] != keys[1]){ // invalid root
13531             if(callback){
13532                 callback(false, null);
13533             }
13534             return;
13535         }
13536         var index = 1;
13537         var f = function(){
13538             if(++index == keys.length){
13539                 if(callback){
13540                     callback(true, curNode);
13541                 }
13542                 return;
13543             }
13544             var c = curNode.findChild(attr, keys[index]);
13545             if(!c){
13546                 if(callback){
13547                     callback(false, curNode);
13548                 }
13549                 return;
13550             }
13551             curNode = c;
13552             c.expand(false, false, f);
13553         };
13554         curNode.expand(false, false, f);
13555     },
13556
13557     /**
13558      * Selects the node in this tree at the specified path. A path can be retrieved from a node with {@link Roo.data.Node#getPath}
13559      * @param {String} path
13560      * @param {String} attr (optional) The attribute used in the path (see {@link Roo.data.Node#getPath} for more info)
13561      * @param {Function} callback (optional) The callback to call when the selection is complete. The callback will be called with
13562      * (bSuccess, oSelNode) where bSuccess is if the selection was successful and oSelNode is the selected node.
13563      */
13564     selectPath : function(path, attr, callback){
13565         attr = attr || "id";
13566         var keys = path.split(this.pathSeparator);
13567         var v = keys.pop();
13568         if(keys.length > 0){
13569             var f = function(success, node){
13570                 if(success && node){
13571                     var n = node.findChild(attr, v);
13572                     if(n){
13573                         n.select();
13574                         if(callback){
13575                             callback(true, n);
13576                         }
13577                     }else if(callback){
13578                         callback(false, n);
13579                     }
13580                 }else{
13581                     if(callback){
13582                         callback(false, n);
13583                     }
13584                 }
13585             };
13586             this.expandPath(keys.join(this.pathSeparator), attr, f);
13587         }else{
13588             this.root.select();
13589             if(callback){
13590                 callback(true, this.root);
13591             }
13592         }
13593     },
13594
13595     getTreeEl : function(){
13596         return this.el;
13597     },
13598
13599     /**
13600      * Trigger rendering of this TreePanel
13601      */
13602     render : function(){
13603         if (this.innerCt) {
13604             return this; // stop it rendering more than once!!
13605         }
13606         
13607         this.innerCt = this.el.createChild({tag:"ul",
13608                cls:"x-tree-root-ct " +
13609                (this.lines ? "x-tree-lines" : "x-tree-no-lines")});
13610
13611         if(this.containerScroll){
13612             Roo.dd.ScrollManager.register(this.el);
13613         }
13614         if((this.enableDD || this.enableDrop) && !this.dropZone){
13615            /**
13616             * The dropZone used by this tree if drop is enabled
13617             * @type Roo.tree.TreeDropZone
13618             */
13619              this.dropZone = new Roo.tree.TreeDropZone(this, this.dropConfig || {
13620                ddGroup: this.ddGroup || "TreeDD", appendOnly: this.ddAppendOnly === true
13621            });
13622         }
13623         if((this.enableDD || this.enableDrag) && !this.dragZone){
13624            /**
13625             * The dragZone used by this tree if drag is enabled
13626             * @type Roo.tree.TreeDragZone
13627             */
13628             this.dragZone = new Roo.tree.TreeDragZone(this, this.dragConfig || {
13629                ddGroup: this.ddGroup || "TreeDD",
13630                scroll: this.ddScroll
13631            });
13632         }
13633         this.getSelectionModel().init(this);
13634         if (!this.root) {
13635             Roo.log("ROOT not set in tree");
13636             return this;
13637         }
13638         this.root.render();
13639         if(!this.rootVisible){
13640             this.root.renderChildren();
13641         }
13642         return this;
13643     }
13644 });/*
13645  * Based on:
13646  * Ext JS Library 1.1.1
13647  * Copyright(c) 2006-2007, Ext JS, LLC.
13648  *
13649  * Originally Released Under LGPL - original licence link has changed is not relivant.
13650  *
13651  * Fork - LGPL
13652  * <script type="text/javascript">
13653  */
13654  
13655
13656 /**
13657  * @class Roo.tree.DefaultSelectionModel
13658  * @extends Roo.util.Observable
13659  * The default single selection for a TreePanel.
13660  * @param {Object} cfg Configuration
13661  */
13662 Roo.tree.DefaultSelectionModel = function(cfg){
13663    this.selNode = null;
13664    
13665    
13666    
13667    this.addEvents({
13668        /**
13669         * @event selectionchange
13670         * Fires when the selected node changes
13671         * @param {DefaultSelectionModel} this
13672         * @param {TreeNode} node the new selection
13673         */
13674        "selectionchange" : true,
13675
13676        /**
13677         * @event beforeselect
13678         * Fires before the selected node changes, return false to cancel the change
13679         * @param {DefaultSelectionModel} this
13680         * @param {TreeNode} node the new selection
13681         * @param {TreeNode} node the old selection
13682         */
13683        "beforeselect" : true
13684    });
13685    
13686     Roo.tree.DefaultSelectionModel.superclass.constructor.call(this,cfg);
13687 };
13688
13689 Roo.extend(Roo.tree.DefaultSelectionModel, Roo.util.Observable, {
13690     init : function(tree){
13691         this.tree = tree;
13692         tree.getTreeEl().on("keydown", this.onKeyDown, this);
13693         tree.on("click", this.onNodeClick, this);
13694     },
13695     
13696     onNodeClick : function(node, e){
13697         if (e.ctrlKey && this.selNode == node)  {
13698             this.unselect(node);
13699             return;
13700         }
13701         this.select(node);
13702     },
13703     
13704     /**
13705      * Select a node.
13706      * @param {TreeNode} node The node to select
13707      * @return {TreeNode} The selected node
13708      */
13709     select : function(node){
13710         var last = this.selNode;
13711         if(last != node && this.fireEvent('beforeselect', this, node, last) !== false){
13712             if(last){
13713                 last.ui.onSelectedChange(false);
13714             }
13715             this.selNode = node;
13716             node.ui.onSelectedChange(true);
13717             this.fireEvent("selectionchange", this, node, last);
13718         }
13719         return node;
13720     },
13721     
13722     /**
13723      * Deselect a node.
13724      * @param {TreeNode} node The node to unselect
13725      */
13726     unselect : function(node){
13727         if(this.selNode == node){
13728             this.clearSelections();
13729         }    
13730     },
13731     
13732     /**
13733      * Clear all selections
13734      */
13735     clearSelections : function(){
13736         var n = this.selNode;
13737         if(n){
13738             n.ui.onSelectedChange(false);
13739             this.selNode = null;
13740             this.fireEvent("selectionchange", this, null);
13741         }
13742         return n;
13743     },
13744     
13745     /**
13746      * Get the selected node
13747      * @return {TreeNode} The selected node
13748      */
13749     getSelectedNode : function(){
13750         return this.selNode;    
13751     },
13752     
13753     /**
13754      * Returns true if the node is selected
13755      * @param {TreeNode} node The node to check
13756      * @return {Boolean}
13757      */
13758     isSelected : function(node){
13759         return this.selNode == node;  
13760     },
13761
13762     /**
13763      * Selects the node above the selected node in the tree, intelligently walking the nodes
13764      * @return TreeNode The new selection
13765      */
13766     selectPrevious : function(){
13767         var s = this.selNode || this.lastSelNode;
13768         if(!s){
13769             return null;
13770         }
13771         var ps = s.previousSibling;
13772         if(ps){
13773             if(!ps.isExpanded() || ps.childNodes.length < 1){
13774                 return this.select(ps);
13775             } else{
13776                 var lc = ps.lastChild;
13777                 while(lc && lc.isExpanded() && lc.childNodes.length > 0){
13778                     lc = lc.lastChild;
13779                 }
13780                 return this.select(lc);
13781             }
13782         } else if(s.parentNode && (this.tree.rootVisible || !s.parentNode.isRoot)){
13783             return this.select(s.parentNode);
13784         }
13785         return null;
13786     },
13787
13788     /**
13789      * Selects the node above the selected node in the tree, intelligently walking the nodes
13790      * @return TreeNode The new selection
13791      */
13792     selectNext : function(){
13793         var s = this.selNode || this.lastSelNode;
13794         if(!s){
13795             return null;
13796         }
13797         if(s.firstChild && s.isExpanded()){
13798              return this.select(s.firstChild);
13799          }else if(s.nextSibling){
13800              return this.select(s.nextSibling);
13801          }else if(s.parentNode){
13802             var newS = null;
13803             s.parentNode.bubble(function(){
13804                 if(this.nextSibling){
13805                     newS = this.getOwnerTree().selModel.select(this.nextSibling);
13806                     return false;
13807                 }
13808             });
13809             return newS;
13810          }
13811         return null;
13812     },
13813
13814     onKeyDown : function(e){
13815         var s = this.selNode || this.lastSelNode;
13816         // undesirable, but required
13817         var sm = this;
13818         if(!s){
13819             return;
13820         }
13821         var k = e.getKey();
13822         switch(k){
13823              case e.DOWN:
13824                  e.stopEvent();
13825                  this.selectNext();
13826              break;
13827              case e.UP:
13828                  e.stopEvent();
13829                  this.selectPrevious();
13830              break;
13831              case e.RIGHT:
13832                  e.preventDefault();
13833                  if(s.hasChildNodes()){
13834                      if(!s.isExpanded()){
13835                          s.expand();
13836                      }else if(s.firstChild){
13837                          this.select(s.firstChild, e);
13838                      }
13839                  }
13840              break;
13841              case e.LEFT:
13842                  e.preventDefault();
13843                  if(s.hasChildNodes() && s.isExpanded()){
13844                      s.collapse();
13845                  }else if(s.parentNode && (this.tree.rootVisible || s.parentNode != this.tree.getRootNode())){
13846                      this.select(s.parentNode, e);
13847                  }
13848              break;
13849         };
13850     }
13851 });
13852
13853 /**
13854  * @class Roo.tree.MultiSelectionModel
13855  * @extends Roo.util.Observable
13856  * Multi selection for a TreePanel.
13857  * @param {Object} cfg Configuration
13858  */
13859 Roo.tree.MultiSelectionModel = function(){
13860    this.selNodes = [];
13861    this.selMap = {};
13862    this.addEvents({
13863        /**
13864         * @event selectionchange
13865         * Fires when the selected nodes change
13866         * @param {MultiSelectionModel} this
13867         * @param {Array} nodes Array of the selected nodes
13868         */
13869        "selectionchange" : true
13870    });
13871    Roo.tree.MultiSelectionModel.superclass.constructor.call(this,cfg);
13872    
13873 };
13874
13875 Roo.extend(Roo.tree.MultiSelectionModel, Roo.util.Observable, {
13876     init : function(tree){
13877         this.tree = tree;
13878         tree.getTreeEl().on("keydown", this.onKeyDown, this);
13879         tree.on("click", this.onNodeClick, this);
13880     },
13881     
13882     onNodeClick : function(node, e){
13883         this.select(node, e, e.ctrlKey);
13884     },
13885     
13886     /**
13887      * Select a node.
13888      * @param {TreeNode} node The node to select
13889      * @param {EventObject} e (optional) An event associated with the selection
13890      * @param {Boolean} keepExisting True to retain existing selections
13891      * @return {TreeNode} The selected node
13892      */
13893     select : function(node, e, keepExisting){
13894         if(keepExisting !== true){
13895             this.clearSelections(true);
13896         }
13897         if(this.isSelected(node)){
13898             this.lastSelNode = node;
13899             return node;
13900         }
13901         this.selNodes.push(node);
13902         this.selMap[node.id] = node;
13903         this.lastSelNode = node;
13904         node.ui.onSelectedChange(true);
13905         this.fireEvent("selectionchange", this, this.selNodes);
13906         return node;
13907     },
13908     
13909     /**
13910      * Deselect a node.
13911      * @param {TreeNode} node The node to unselect
13912      */
13913     unselect : function(node){
13914         if(this.selMap[node.id]){
13915             node.ui.onSelectedChange(false);
13916             var sn = this.selNodes;
13917             var index = -1;
13918             if(sn.indexOf){
13919                 index = sn.indexOf(node);
13920             }else{
13921                 for(var i = 0, len = sn.length; i < len; i++){
13922                     if(sn[i] == node){
13923                         index = i;
13924                         break;
13925                     }
13926                 }
13927             }
13928             if(index != -1){
13929                 this.selNodes.splice(index, 1);
13930             }
13931             delete this.selMap[node.id];
13932             this.fireEvent("selectionchange", this, this.selNodes);
13933         }
13934     },
13935     
13936     /**
13937      * Clear all selections
13938      */
13939     clearSelections : function(suppressEvent){
13940         var sn = this.selNodes;
13941         if(sn.length > 0){
13942             for(var i = 0, len = sn.length; i < len; i++){
13943                 sn[i].ui.onSelectedChange(false);
13944             }
13945             this.selNodes = [];
13946             this.selMap = {};
13947             if(suppressEvent !== true){
13948                 this.fireEvent("selectionchange", this, this.selNodes);
13949             }
13950         }
13951     },
13952     
13953     /**
13954      * Returns true if the node is selected
13955      * @param {TreeNode} node The node to check
13956      * @return {Boolean}
13957      */
13958     isSelected : function(node){
13959         return this.selMap[node.id] ? true : false;  
13960     },
13961     
13962     /**
13963      * Returns an array of the selected nodes
13964      * @return {Array}
13965      */
13966     getSelectedNodes : function(){
13967         return this.selNodes;    
13968     },
13969
13970     onKeyDown : Roo.tree.DefaultSelectionModel.prototype.onKeyDown,
13971
13972     selectNext : Roo.tree.DefaultSelectionModel.prototype.selectNext,
13973
13974     selectPrevious : Roo.tree.DefaultSelectionModel.prototype.selectPrevious
13975 });/*
13976  * Based on:
13977  * Ext JS Library 1.1.1
13978  * Copyright(c) 2006-2007, Ext JS, LLC.
13979  *
13980  * Originally Released Under LGPL - original licence link has changed is not relivant.
13981  *
13982  * Fork - LGPL
13983  * <script type="text/javascript">
13984  */
13985  
13986 /**
13987  * @class Roo.tree.TreeNode
13988  * @extends Roo.data.Node
13989  * @cfg {String} text The text for this node
13990  * @cfg {Boolean} expanded true to start the node expanded
13991  * @cfg {Boolean} allowDrag false to make this node undraggable if DD is on (defaults to true)
13992  * @cfg {Boolean} allowDrop false if this node cannot be drop on
13993  * @cfg {Boolean} disabled true to start the node disabled
13994  * @cfg {String} icon The path to an icon for the node. The preferred way to do this
13995  *    is to use the cls or iconCls attributes and add the icon via a CSS background image.
13996  * @cfg {String} cls A css class to be added to the node
13997  * @cfg {String} iconCls A css class to be added to the nodes icon element for applying css background images
13998  * @cfg {String} href URL of the link used for the node (defaults to #)
13999  * @cfg {String} hrefTarget target frame for the link
14000  * @cfg {String} qtip An Ext QuickTip for the node
14001  * @cfg {String} qtipCfg An Ext QuickTip config for the node (used instead of qtip)
14002  * @cfg {Boolean} singleClickExpand True for single click expand on this node
14003  * @cfg {Function} uiProvider A UI <b>class</b> to use for this node (defaults to Roo.tree.TreeNodeUI)
14004  * @cfg {Boolean} checked True to render a checked checkbox for this node, false to render an unchecked checkbox
14005  * (defaults to undefined with no checkbox rendered)
14006  * @constructor
14007  * @param {Object/String} attributes The attributes/config for the node or just a string with the text for the node
14008  */
14009 Roo.tree.TreeNode = function(attributes){
14010     attributes = attributes || {};
14011     if(typeof attributes == "string"){
14012         attributes = {text: attributes};
14013     }
14014     this.childrenRendered = false;
14015     this.rendered = false;
14016     Roo.tree.TreeNode.superclass.constructor.call(this, attributes);
14017     this.expanded = attributes.expanded === true;
14018     this.isTarget = attributes.isTarget !== false;
14019     this.draggable = attributes.draggable !== false && attributes.allowDrag !== false;
14020     this.allowChildren = attributes.allowChildren !== false && attributes.allowDrop !== false;
14021
14022     /**
14023      * Read-only. The text for this node. To change it use setText().
14024      * @type String
14025      */
14026     this.text = attributes.text;
14027     /**
14028      * True if this node is disabled.
14029      * @type Boolean
14030      */
14031     this.disabled = attributes.disabled === true;
14032
14033     this.addEvents({
14034         /**
14035         * @event textchange
14036         * Fires when the text for this node is changed
14037         * @param {Node} this This node
14038         * @param {String} text The new text
14039         * @param {String} oldText The old text
14040         */
14041         "textchange" : true,
14042         /**
14043         * @event beforeexpand
14044         * Fires before this node is expanded, return false to cancel.
14045         * @param {Node} this This node
14046         * @param {Boolean} deep
14047         * @param {Boolean} anim
14048         */
14049         "beforeexpand" : true,
14050         /**
14051         * @event beforecollapse
14052         * Fires before this node is collapsed, return false to cancel.
14053         * @param {Node} this This node
14054         * @param {Boolean} deep
14055         * @param {Boolean} anim
14056         */
14057         "beforecollapse" : true,
14058         /**
14059         * @event expand
14060         * Fires when this node is expanded
14061         * @param {Node} this This node
14062         */
14063         "expand" : true,
14064         /**
14065         * @event disabledchange
14066         * Fires when the disabled status of this node changes
14067         * @param {Node} this This node
14068         * @param {Boolean} disabled
14069         */
14070         "disabledchange" : true,
14071         /**
14072         * @event collapse
14073         * Fires when this node is collapsed
14074         * @param {Node} this This node
14075         */
14076         "collapse" : true,
14077         /**
14078         * @event beforeclick
14079         * Fires before click processing. Return false to cancel the default action.
14080         * @param {Node} this This node
14081         * @param {Roo.EventObject} e The event object
14082         */
14083         "beforeclick":true,
14084         /**
14085         * @event checkchange
14086         * Fires when a node with a checkbox's checked property changes
14087         * @param {Node} this This node
14088         * @param {Boolean} checked
14089         */
14090         "checkchange":true,
14091         /**
14092         * @event click
14093         * Fires when this node is clicked
14094         * @param {Node} this This node
14095         * @param {Roo.EventObject} e The event object
14096         */
14097         "click":true,
14098         /**
14099         * @event dblclick
14100         * Fires when this node is double clicked
14101         * @param {Node} this This node
14102         * @param {Roo.EventObject} e The event object
14103         */
14104         "dblclick":true,
14105         /**
14106         * @event contextmenu
14107         * Fires when this node is right clicked
14108         * @param {Node} this This node
14109         * @param {Roo.EventObject} e The event object
14110         */
14111         "contextmenu":true,
14112         /**
14113         * @event beforechildrenrendered
14114         * Fires right before the child nodes for this node are rendered
14115         * @param {Node} this This node
14116         */
14117         "beforechildrenrendered":true
14118     });
14119
14120     var uiClass = this.attributes.uiProvider || Roo.tree.TreeNodeUI;
14121
14122     /**
14123      * Read-only. The UI for this node
14124      * @type TreeNodeUI
14125      */
14126     this.ui = new uiClass(this);
14127     
14128     // finally support items[]
14129     if (typeof(this.attributes.items) == 'undefined' || !this.attributes.items) {
14130         return;
14131     }
14132     
14133     
14134     Roo.each(this.attributes.items, function(c) {
14135         this.appendChild(Roo.factory(c,Roo.Tree));
14136     }, this);
14137     delete this.attributes.items;
14138     
14139     
14140     
14141 };
14142 Roo.extend(Roo.tree.TreeNode, Roo.data.Node, {
14143     preventHScroll: true,
14144     /**
14145      * Returns true if this node is expanded
14146      * @return {Boolean}
14147      */
14148     isExpanded : function(){
14149         return this.expanded;
14150     },
14151
14152     /**
14153      * Returns the UI object for this node
14154      * @return {TreeNodeUI}
14155      */
14156     getUI : function(){
14157         return this.ui;
14158     },
14159
14160     // private override
14161     setFirstChild : function(node){
14162         var of = this.firstChild;
14163         Roo.tree.TreeNode.superclass.setFirstChild.call(this, node);
14164         if(this.childrenRendered && of && node != of){
14165             of.renderIndent(true, true);
14166         }
14167         if(this.rendered){
14168             this.renderIndent(true, true);
14169         }
14170     },
14171
14172     // private override
14173     setLastChild : function(node){
14174         var ol = this.lastChild;
14175         Roo.tree.TreeNode.superclass.setLastChild.call(this, node);
14176         if(this.childrenRendered && ol && node != ol){
14177             ol.renderIndent(true, true);
14178         }
14179         if(this.rendered){
14180             this.renderIndent(true, true);
14181         }
14182     },
14183
14184     // these methods are overridden to provide lazy rendering support
14185     // private override
14186     appendChild : function()
14187     {
14188         var node = Roo.tree.TreeNode.superclass.appendChild.apply(this, arguments);
14189         if(node && this.childrenRendered){
14190             node.render();
14191         }
14192         this.ui.updateExpandIcon();
14193         return node;
14194     },
14195
14196     // private override
14197     removeChild : function(node){
14198         this.ownerTree.getSelectionModel().unselect(node);
14199         Roo.tree.TreeNode.superclass.removeChild.apply(this, arguments);
14200         // if it's been rendered remove dom node
14201         if(this.childrenRendered){
14202             node.ui.remove();
14203         }
14204         if(this.childNodes.length < 1){
14205             this.collapse(false, false);
14206         }else{
14207             this.ui.updateExpandIcon();
14208         }
14209         if(!this.firstChild) {
14210             this.childrenRendered = false;
14211         }
14212         return node;
14213     },
14214
14215     // private override
14216     insertBefore : function(node, refNode){
14217         var newNode = Roo.tree.TreeNode.superclass.insertBefore.apply(this, arguments);
14218         if(newNode && refNode && this.childrenRendered){
14219             node.render();
14220         }
14221         this.ui.updateExpandIcon();
14222         return newNode;
14223     },
14224
14225     /**
14226      * Sets the text for this node
14227      * @param {String} text
14228      */
14229     setText : function(text){
14230         var oldText = this.text;
14231         this.text = text;
14232         this.attributes.text = text;
14233         if(this.rendered){ // event without subscribing
14234             this.ui.onTextChange(this, text, oldText);
14235         }
14236         this.fireEvent("textchange", this, text, oldText);
14237     },
14238
14239     /**
14240      * Triggers selection of this node
14241      */
14242     select : function(){
14243         this.getOwnerTree().getSelectionModel().select(this);
14244     },
14245
14246     /**
14247      * Triggers deselection of this node
14248      */
14249     unselect : function(){
14250         this.getOwnerTree().getSelectionModel().unselect(this);
14251     },
14252
14253     /**
14254      * Returns true if this node is selected
14255      * @return {Boolean}
14256      */
14257     isSelected : function(){
14258         return this.getOwnerTree().getSelectionModel().isSelected(this);
14259     },
14260
14261     /**
14262      * Expand this node.
14263      * @param {Boolean} deep (optional) True to expand all children as well
14264      * @param {Boolean} anim (optional) false to cancel the default animation
14265      * @param {Function} callback (optional) A callback to be called when
14266      * expanding this node completes (does not wait for deep expand to complete).
14267      * Called with 1 parameter, this node.
14268      */
14269     expand : function(deep, anim, callback){
14270         if(!this.expanded){
14271             if(this.fireEvent("beforeexpand", this, deep, anim) === false){
14272                 return;
14273             }
14274             if(!this.childrenRendered){
14275                 this.renderChildren();
14276             }
14277             this.expanded = true;
14278             
14279             if(!this.isHiddenRoot() && (this.getOwnerTree() && this.getOwnerTree().animate && anim !== false) || anim){
14280                 this.ui.animExpand(function(){
14281                     this.fireEvent("expand", this);
14282                     if(typeof callback == "function"){
14283                         callback(this);
14284                     }
14285                     if(deep === true){
14286                         this.expandChildNodes(true);
14287                     }
14288                 }.createDelegate(this));
14289                 return;
14290             }else{
14291                 this.ui.expand();
14292                 this.fireEvent("expand", this);
14293                 if(typeof callback == "function"){
14294                     callback(this);
14295                 }
14296             }
14297         }else{
14298            if(typeof callback == "function"){
14299                callback(this);
14300            }
14301         }
14302         if(deep === true){
14303             this.expandChildNodes(true);
14304         }
14305     },
14306
14307     isHiddenRoot : function(){
14308         return this.isRoot && !this.getOwnerTree().rootVisible;
14309     },
14310
14311     /**
14312      * Collapse this node.
14313      * @param {Boolean} deep (optional) True to collapse all children as well
14314      * @param {Boolean} anim (optional) false to cancel the default animation
14315      */
14316     collapse : function(deep, anim){
14317         if(this.expanded && !this.isHiddenRoot()){
14318             if(this.fireEvent("beforecollapse", this, deep, anim) === false){
14319                 return;
14320             }
14321             this.expanded = false;
14322             if((this.getOwnerTree().animate && anim !== false) || anim){
14323                 this.ui.animCollapse(function(){
14324                     this.fireEvent("collapse", this);
14325                     if(deep === true){
14326                         this.collapseChildNodes(true);
14327                     }
14328                 }.createDelegate(this));
14329                 return;
14330             }else{
14331                 this.ui.collapse();
14332                 this.fireEvent("collapse", this);
14333             }
14334         }
14335         if(deep === true){
14336             var cs = this.childNodes;
14337             for(var i = 0, len = cs.length; i < len; i++) {
14338                 cs[i].collapse(true, false);
14339             }
14340         }
14341     },
14342
14343     // private
14344     delayedExpand : function(delay){
14345         if(!this.expandProcId){
14346             this.expandProcId = this.expand.defer(delay, this);
14347         }
14348     },
14349
14350     // private
14351     cancelExpand : function(){
14352         if(this.expandProcId){
14353             clearTimeout(this.expandProcId);
14354         }
14355         this.expandProcId = false;
14356     },
14357
14358     /**
14359      * Toggles expanded/collapsed state of the node
14360      */
14361     toggle : function(){
14362         if(this.expanded){
14363             this.collapse();
14364         }else{
14365             this.expand();
14366         }
14367     },
14368
14369     /**
14370      * Ensures all parent nodes are expanded
14371      */
14372     ensureVisible : function(callback){
14373         var tree = this.getOwnerTree();
14374         tree.expandPath(this.parentNode.getPath(), false, function(){
14375             tree.getTreeEl().scrollChildIntoView(this.ui.anchor);
14376             Roo.callback(callback);
14377         }.createDelegate(this));
14378     },
14379
14380     /**
14381      * Expand all child nodes
14382      * @param {Boolean} deep (optional) true if the child nodes should also expand their child nodes
14383      */
14384     expandChildNodes : function(deep){
14385         var cs = this.childNodes;
14386         for(var i = 0, len = cs.length; i < len; i++) {
14387                 cs[i].expand(deep);
14388         }
14389     },
14390
14391     /**
14392      * Collapse all child nodes
14393      * @param {Boolean} deep (optional) true if the child nodes should also collapse their child nodes
14394      */
14395     collapseChildNodes : function(deep){
14396         var cs = this.childNodes;
14397         for(var i = 0, len = cs.length; i < len; i++) {
14398                 cs[i].collapse(deep);
14399         }
14400     },
14401
14402     /**
14403      * Disables this node
14404      */
14405     disable : function(){
14406         this.disabled = true;
14407         this.unselect();
14408         if(this.rendered && this.ui.onDisableChange){ // event without subscribing
14409             this.ui.onDisableChange(this, true);
14410         }
14411         this.fireEvent("disabledchange", this, true);
14412     },
14413
14414     /**
14415      * Enables this node
14416      */
14417     enable : function(){
14418         this.disabled = false;
14419         if(this.rendered && this.ui.onDisableChange){ // event without subscribing
14420             this.ui.onDisableChange(this, false);
14421         }
14422         this.fireEvent("disabledchange", this, false);
14423     },
14424
14425     // private
14426     renderChildren : function(suppressEvent){
14427         if(suppressEvent !== false){
14428             this.fireEvent("beforechildrenrendered", this);
14429         }
14430         var cs = this.childNodes;
14431         for(var i = 0, len = cs.length; i < len; i++){
14432             cs[i].render(true);
14433         }
14434         this.childrenRendered = true;
14435     },
14436
14437     // private
14438     sort : function(fn, scope){
14439         Roo.tree.TreeNode.superclass.sort.apply(this, arguments);
14440         if(this.childrenRendered){
14441             var cs = this.childNodes;
14442             for(var i = 0, len = cs.length; i < len; i++){
14443                 cs[i].render(true);
14444             }
14445         }
14446     },
14447
14448     // private
14449     render : function(bulkRender){
14450         this.ui.render(bulkRender);
14451         if(!this.rendered){
14452             this.rendered = true;
14453             if(this.expanded){
14454                 this.expanded = false;
14455                 this.expand(false, false);
14456             }
14457         }
14458     },
14459
14460     // private
14461     renderIndent : function(deep, refresh){
14462         if(refresh){
14463             this.ui.childIndent = null;
14464         }
14465         this.ui.renderIndent();
14466         if(deep === true && this.childrenRendered){
14467             var cs = this.childNodes;
14468             for(var i = 0, len = cs.length; i < len; i++){
14469                 cs[i].renderIndent(true, refresh);
14470             }
14471         }
14472     }
14473 });/*
14474  * Based on:
14475  * Ext JS Library 1.1.1
14476  * Copyright(c) 2006-2007, Ext JS, LLC.
14477  *
14478  * Originally Released Under LGPL - original licence link has changed is not relivant.
14479  *
14480  * Fork - LGPL
14481  * <script type="text/javascript">
14482  */
14483  
14484 /**
14485  * @class Roo.tree.AsyncTreeNode
14486  * @extends Roo.tree.TreeNode
14487  * @cfg {TreeLoader} loader A TreeLoader to be used by this node (defaults to the loader defined on the tree)
14488  * @constructor
14489  * @param {Object/String} attributes The attributes/config for the node or just a string with the text for the node 
14490  */
14491  Roo.tree.AsyncTreeNode = function(config){
14492     this.loaded = false;
14493     this.loading = false;
14494     Roo.tree.AsyncTreeNode.superclass.constructor.apply(this, arguments);
14495     /**
14496     * @event beforeload
14497     * Fires before this node is loaded, return false to cancel
14498     * @param {Node} this This node
14499     */
14500     this.addEvents({'beforeload':true, 'load': true});
14501     /**
14502     * @event load
14503     * Fires when this node is loaded
14504     * @param {Node} this This node
14505     */
14506     /**
14507      * The loader used by this node (defaults to using the tree's defined loader)
14508      * @type TreeLoader
14509      * @property loader
14510      */
14511 };
14512 Roo.extend(Roo.tree.AsyncTreeNode, Roo.tree.TreeNode, {
14513     expand : function(deep, anim, callback){
14514         if(this.loading){ // if an async load is already running, waiting til it's done
14515             var timer;
14516             var f = function(){
14517                 if(!this.loading){ // done loading
14518                     clearInterval(timer);
14519                     this.expand(deep, anim, callback);
14520                 }
14521             }.createDelegate(this);
14522             timer = setInterval(f, 200);
14523             return;
14524         }
14525         if(!this.loaded){
14526             if(this.fireEvent("beforeload", this) === false){
14527                 return;
14528             }
14529             this.loading = true;
14530             this.ui.beforeLoad(this);
14531             var loader = this.loader || this.attributes.loader || this.getOwnerTree().getLoader();
14532             if(loader){
14533                 loader.load(this, this.loadComplete.createDelegate(this, [deep, anim, callback]));
14534                 return;
14535             }
14536         }
14537         Roo.tree.AsyncTreeNode.superclass.expand.call(this, deep, anim, callback);
14538     },
14539     
14540     /**
14541      * Returns true if this node is currently loading
14542      * @return {Boolean}
14543      */
14544     isLoading : function(){
14545         return this.loading;  
14546     },
14547     
14548     loadComplete : function(deep, anim, callback){
14549         this.loading = false;
14550         this.loaded = true;
14551         this.ui.afterLoad(this);
14552         this.fireEvent("load", this);
14553         this.expand(deep, anim, callback);
14554     },
14555     
14556     /**
14557      * Returns true if this node has been loaded
14558      * @return {Boolean}
14559      */
14560     isLoaded : function(){
14561         return this.loaded;
14562     },
14563     
14564     hasChildNodes : function(){
14565         if(!this.isLeaf() && !this.loaded){
14566             return true;
14567         }else{
14568             return Roo.tree.AsyncTreeNode.superclass.hasChildNodes.call(this);
14569         }
14570     },
14571
14572     /**
14573      * Trigger a reload for this node
14574      * @param {Function} callback
14575      */
14576     reload : function(callback){
14577         this.collapse(false, false);
14578         while(this.firstChild){
14579             this.removeChild(this.firstChild);
14580         }
14581         this.childrenRendered = false;
14582         this.loaded = false;
14583         if(this.isHiddenRoot()){
14584             this.expanded = false;
14585         }
14586         this.expand(false, false, callback);
14587     }
14588 });/*
14589  * Based on:
14590  * Ext JS Library 1.1.1
14591  * Copyright(c) 2006-2007, Ext JS, LLC.
14592  *
14593  * Originally Released Under LGPL - original licence link has changed is not relivant.
14594  *
14595  * Fork - LGPL
14596  * <script type="text/javascript">
14597  */
14598  
14599 /**
14600  * @class Roo.tree.TreeNodeUI
14601  * @constructor
14602  * @param {Object} node The node to render
14603  * The TreeNode UI implementation is separate from the
14604  * tree implementation. Unless you are customizing the tree UI,
14605  * you should never have to use this directly.
14606  */
14607 Roo.tree.TreeNodeUI = function(node){
14608     this.node = node;
14609     this.rendered = false;
14610     this.animating = false;
14611     this.emptyIcon = Roo.BLANK_IMAGE_URL;
14612 };
14613
14614 Roo.tree.TreeNodeUI.prototype = {
14615     removeChild : function(node){
14616         if(this.rendered){
14617             this.ctNode.removeChild(node.ui.getEl());
14618         }
14619     },
14620
14621     beforeLoad : function(){
14622          this.addClass("x-tree-node-loading");
14623     },
14624
14625     afterLoad : function(){
14626          this.removeClass("x-tree-node-loading");
14627     },
14628
14629     onTextChange : function(node, text, oldText){
14630         if(this.rendered){
14631             this.textNode.innerHTML = text;
14632         }
14633     },
14634
14635     onDisableChange : function(node, state){
14636         this.disabled = state;
14637         if(state){
14638             this.addClass("x-tree-node-disabled");
14639         }else{
14640             this.removeClass("x-tree-node-disabled");
14641         }
14642     },
14643
14644     onSelectedChange : function(state){
14645         if(state){
14646             this.focus();
14647             this.addClass("x-tree-selected");
14648         }else{
14649             //this.blur();
14650             this.removeClass("x-tree-selected");
14651         }
14652     },
14653
14654     onMove : function(tree, node, oldParent, newParent, index, refNode){
14655         this.childIndent = null;
14656         if(this.rendered){
14657             var targetNode = newParent.ui.getContainer();
14658             if(!targetNode){//target not rendered
14659                 this.holder = document.createElement("div");
14660                 this.holder.appendChild(this.wrap);
14661                 return;
14662             }
14663             var insertBefore = refNode ? refNode.ui.getEl() : null;
14664             if(insertBefore){
14665                 targetNode.insertBefore(this.wrap, insertBefore);
14666             }else{
14667                 targetNode.appendChild(this.wrap);
14668             }
14669             this.node.renderIndent(true);
14670         }
14671     },
14672
14673     addClass : function(cls){
14674         if(this.elNode){
14675             Roo.fly(this.elNode).addClass(cls);
14676         }
14677     },
14678
14679     removeClass : function(cls){
14680         if(this.elNode){
14681             Roo.fly(this.elNode).removeClass(cls);
14682         }
14683     },
14684
14685     remove : function(){
14686         if(this.rendered){
14687             this.holder = document.createElement("div");
14688             this.holder.appendChild(this.wrap);
14689         }
14690     },
14691
14692     fireEvent : function(){
14693         return this.node.fireEvent.apply(this.node, arguments);
14694     },
14695
14696     initEvents : function(){
14697         this.node.on("move", this.onMove, this);
14698         var E = Roo.EventManager;
14699         var a = this.anchor;
14700
14701         var el = Roo.fly(a, '_treeui');
14702
14703         if(Roo.isOpera){ // opera render bug ignores the CSS
14704             el.setStyle("text-decoration", "none");
14705         }
14706
14707         el.on("click", this.onClick, this);
14708         el.on("dblclick", this.onDblClick, this);
14709
14710         if(this.checkbox){
14711             Roo.EventManager.on(this.checkbox,
14712                     Roo.isIE ? 'click' : 'change', this.onCheckChange, this);
14713         }
14714
14715         el.on("contextmenu", this.onContextMenu, this);
14716
14717         var icon = Roo.fly(this.iconNode);
14718         icon.on("click", this.onClick, this);
14719         icon.on("dblclick", this.onDblClick, this);
14720         icon.on("contextmenu", this.onContextMenu, this);
14721         E.on(this.ecNode, "click", this.ecClick, this, true);
14722
14723         if(this.node.disabled){
14724             this.addClass("x-tree-node-disabled");
14725         }
14726         if(this.node.hidden){
14727             this.addClass("x-tree-node-disabled");
14728         }
14729         var ot = this.node.getOwnerTree();
14730         var dd = ot ? (ot.enableDD || ot.enableDrag || ot.enableDrop) : false;
14731         if(dd && (!this.node.isRoot || ot.rootVisible)){
14732             Roo.dd.Registry.register(this.elNode, {
14733                 node: this.node,
14734                 handles: this.getDDHandles(),
14735                 isHandle: false
14736             });
14737         }
14738     },
14739
14740     getDDHandles : function(){
14741         return [this.iconNode, this.textNode];
14742     },
14743
14744     hide : function(){
14745         if(this.rendered){
14746             this.wrap.style.display = "none";
14747         }
14748     },
14749
14750     show : function(){
14751         if(this.rendered){
14752             this.wrap.style.display = "";
14753         }
14754     },
14755
14756     onContextMenu : function(e){
14757         if (this.node.hasListener("contextmenu") || this.node.getOwnerTree().hasListener("contextmenu")) {
14758             e.preventDefault();
14759             this.focus();
14760             this.fireEvent("contextmenu", this.node, e);
14761         }
14762     },
14763
14764     onClick : function(e){
14765         if(this.dropping){
14766             e.stopEvent();
14767             return;
14768         }
14769         if(this.fireEvent("beforeclick", this.node, e) !== false){
14770             if(!this.disabled && this.node.attributes.href){
14771                 this.fireEvent("click", this.node, e);
14772                 return;
14773             }
14774             e.preventDefault();
14775             if(this.disabled){
14776                 return;
14777             }
14778
14779             if(this.node.attributes.singleClickExpand && !this.animating && this.node.hasChildNodes()){
14780                 this.node.toggle();
14781             }
14782
14783             this.fireEvent("click", this.node, e);
14784         }else{
14785             e.stopEvent();
14786         }
14787     },
14788
14789     onDblClick : function(e){
14790         e.preventDefault();
14791         if(this.disabled){
14792             return;
14793         }
14794         if(this.checkbox){
14795             this.toggleCheck();
14796         }
14797         if(!this.animating && this.node.hasChildNodes()){
14798             this.node.toggle();
14799         }
14800         this.fireEvent("dblclick", this.node, e);
14801     },
14802
14803     onCheckChange : function(){
14804         var checked = this.checkbox.checked;
14805         this.node.attributes.checked = checked;
14806         this.fireEvent('checkchange', this.node, checked);
14807     },
14808
14809     ecClick : function(e){
14810         if(!this.animating && this.node.hasChildNodes()){
14811             this.node.toggle();
14812         }
14813     },
14814
14815     startDrop : function(){
14816         this.dropping = true;
14817     },
14818
14819     // delayed drop so the click event doesn't get fired on a drop
14820     endDrop : function(){
14821        setTimeout(function(){
14822            this.dropping = false;
14823        }.createDelegate(this), 50);
14824     },
14825
14826     expand : function(){
14827         this.updateExpandIcon();
14828         this.ctNode.style.display = "";
14829     },
14830
14831     focus : function(){
14832         if(!this.node.preventHScroll){
14833             try{this.anchor.focus();
14834             }catch(e){}
14835         }else if(!Roo.isIE){
14836             try{
14837                 var noscroll = this.node.getOwnerTree().getTreeEl().dom;
14838                 var l = noscroll.scrollLeft;
14839                 this.anchor.focus();
14840                 noscroll.scrollLeft = l;
14841             }catch(e){}
14842         }
14843     },
14844
14845     toggleCheck : function(value){
14846         var cb = this.checkbox;
14847         if(cb){
14848             cb.checked = (value === undefined ? !cb.checked : value);
14849         }
14850     },
14851
14852     blur : function(){
14853         try{
14854             this.anchor.blur();
14855         }catch(e){}
14856     },
14857
14858     animExpand : function(callback){
14859         var ct = Roo.get(this.ctNode);
14860         ct.stopFx();
14861         if(!this.node.hasChildNodes()){
14862             this.updateExpandIcon();
14863             this.ctNode.style.display = "";
14864             Roo.callback(callback);
14865             return;
14866         }
14867         this.animating = true;
14868         this.updateExpandIcon();
14869
14870         ct.slideIn('t', {
14871            callback : function(){
14872                this.animating = false;
14873                Roo.callback(callback);
14874             },
14875             scope: this,
14876             duration: this.node.ownerTree.duration || .25
14877         });
14878     },
14879
14880     highlight : function(){
14881         var tree = this.node.getOwnerTree();
14882         Roo.fly(this.wrap).highlight(
14883             tree.hlColor || "C3DAF9",
14884             {endColor: tree.hlBaseColor}
14885         );
14886     },
14887
14888     collapse : function(){
14889         this.updateExpandIcon();
14890         this.ctNode.style.display = "none";
14891     },
14892
14893     animCollapse : function(callback){
14894         var ct = Roo.get(this.ctNode);
14895         ct.enableDisplayMode('block');
14896         ct.stopFx();
14897
14898         this.animating = true;
14899         this.updateExpandIcon();
14900
14901         ct.slideOut('t', {
14902             callback : function(){
14903                this.animating = false;
14904                Roo.callback(callback);
14905             },
14906             scope: this,
14907             duration: this.node.ownerTree.duration || .25
14908         });
14909     },
14910
14911     getContainer : function(){
14912         return this.ctNode;
14913     },
14914
14915     getEl : function(){
14916         return this.wrap;
14917     },
14918
14919     appendDDGhost : function(ghostNode){
14920         ghostNode.appendChild(this.elNode.cloneNode(true));
14921     },
14922
14923     getDDRepairXY : function(){
14924         return Roo.lib.Dom.getXY(this.iconNode);
14925     },
14926
14927     onRender : function(){
14928         this.render();
14929     },
14930
14931     render : function(bulkRender){
14932         var n = this.node, a = n.attributes;
14933         var targetNode = n.parentNode ?
14934               n.parentNode.ui.getContainer() : n.ownerTree.innerCt.dom;
14935
14936         if(!this.rendered){
14937             this.rendered = true;
14938
14939             this.renderElements(n, a, targetNode, bulkRender);
14940
14941             if(a.qtip){
14942                if(this.textNode.setAttributeNS){
14943                    this.textNode.setAttributeNS("ext", "qtip", a.qtip);
14944                    if(a.qtipTitle){
14945                        this.textNode.setAttributeNS("ext", "qtitle", a.qtipTitle);
14946                    }
14947                }else{
14948                    this.textNode.setAttribute("ext:qtip", a.qtip);
14949                    if(a.qtipTitle){
14950                        this.textNode.setAttribute("ext:qtitle", a.qtipTitle);
14951                    }
14952                }
14953             }else if(a.qtipCfg){
14954                 a.qtipCfg.target = Roo.id(this.textNode);
14955                 Roo.QuickTips.register(a.qtipCfg);
14956             }
14957             this.initEvents();
14958             if(!this.node.expanded){
14959                 this.updateExpandIcon();
14960             }
14961         }else{
14962             if(bulkRender === true) {
14963                 targetNode.appendChild(this.wrap);
14964             }
14965         }
14966     },
14967
14968     renderElements : function(n, a, targetNode, bulkRender)
14969     {
14970         // add some indent caching, this helps performance when rendering a large tree
14971         this.indentMarkup = n.parentNode ? n.parentNode.ui.getChildIndent() : '';
14972         var t = n.getOwnerTree();
14973         var txt = t && t.renderer ? t.renderer(n.attributes) : Roo.util.Format.htmlEncode(n.text);
14974         if (typeof(n.attributes.html) != 'undefined') {
14975             txt = n.attributes.html;
14976         }
14977         var tip = t && t.rendererTip ? t.rendererTip(n.attributes) : txt;
14978         var cb = typeof a.checked == 'boolean';
14979         var href = a.href ? a.href : Roo.isGecko ? "" : "#";
14980         var buf = ['<li class="x-tree-node"><div class="x-tree-node-el ', a.cls,'">',
14981             '<span class="x-tree-node-indent">',this.indentMarkup,"</span>",
14982             '<img src="', this.emptyIcon, '" class="x-tree-ec-icon" />',
14983             '<img src="', a.icon || this.emptyIcon, '" class="x-tree-node-icon',(a.icon ? " x-tree-node-inline-icon" : ""),(a.iconCls ? " "+a.iconCls : ""),'" unselectable="on" />',
14984             cb ? ('<input class="x-tree-node-cb" type="checkbox" ' + (a.checked ? 'checked="checked" />' : ' />')) : '',
14985             '<a hidefocus="on" href="',href,'" tabIndex="1" ',
14986              a.hrefTarget ? ' target="'+a.hrefTarget+'"' : "", 
14987                 '><span unselectable="on" qtip="' , tip ,'">',txt,"</span></a></div>",
14988             '<ul class="x-tree-node-ct" style="display:none;"></ul>',
14989             "</li>"];
14990
14991         if(bulkRender !== true && n.nextSibling && n.nextSibling.ui.getEl()){
14992             this.wrap = Roo.DomHelper.insertHtml("beforeBegin",
14993                                 n.nextSibling.ui.getEl(), buf.join(""));
14994         }else{
14995             this.wrap = Roo.DomHelper.insertHtml("beforeEnd", targetNode, buf.join(""));
14996         }
14997
14998         this.elNode = this.wrap.childNodes[0];
14999         this.ctNode = this.wrap.childNodes[1];
15000         var cs = this.elNode.childNodes;
15001         this.indentNode = cs[0];
15002         this.ecNode = cs[1];
15003         this.iconNode = cs[2];
15004         var index = 3;
15005         if(cb){
15006             this.checkbox = cs[3];
15007             index++;
15008         }
15009         this.anchor = cs[index];
15010         this.textNode = cs[index].firstChild;
15011     },
15012
15013     getAnchor : function(){
15014         return this.anchor;
15015     },
15016
15017     getTextEl : function(){
15018         return this.textNode;
15019     },
15020
15021     getIconEl : function(){
15022         return this.iconNode;
15023     },
15024
15025     isChecked : function(){
15026         return this.checkbox ? this.checkbox.checked : false;
15027     },
15028
15029     updateExpandIcon : function(){
15030         if(this.rendered){
15031             var n = this.node, c1, c2;
15032             var cls = n.isLast() ? "x-tree-elbow-end" : "x-tree-elbow";
15033             var hasChild = n.hasChildNodes();
15034             if(hasChild){
15035                 if(n.expanded){
15036                     cls += "-minus";
15037                     c1 = "x-tree-node-collapsed";
15038                     c2 = "x-tree-node-expanded";
15039                 }else{
15040                     cls += "-plus";
15041                     c1 = "x-tree-node-expanded";
15042                     c2 = "x-tree-node-collapsed";
15043                 }
15044                 if(this.wasLeaf){
15045                     this.removeClass("x-tree-node-leaf");
15046                     this.wasLeaf = false;
15047                 }
15048                 if(this.c1 != c1 || this.c2 != c2){
15049                     Roo.fly(this.elNode).replaceClass(c1, c2);
15050                     this.c1 = c1; this.c2 = c2;
15051                 }
15052             }else{
15053                 // this changes non-leafs into leafs if they have no children.
15054                 // it's not very rational behaviour..
15055                 
15056                 if(!this.wasLeaf && this.node.leaf){
15057                     Roo.fly(this.elNode).replaceClass("x-tree-node-expanded", "x-tree-node-leaf");
15058                     delete this.c1;
15059                     delete this.c2;
15060                     this.wasLeaf = true;
15061                 }
15062             }
15063             var ecc = "x-tree-ec-icon "+cls;
15064             if(this.ecc != ecc){
15065                 this.ecNode.className = ecc;
15066                 this.ecc = ecc;
15067             }
15068         }
15069     },
15070
15071     getChildIndent : function(){
15072         if(!this.childIndent){
15073             var buf = [];
15074             var p = this.node;
15075             while(p){
15076                 if(!p.isRoot || (p.isRoot && p.ownerTree.rootVisible)){
15077                     if(!p.isLast()) {
15078                         buf.unshift('<img src="'+this.emptyIcon+'" class="x-tree-elbow-line" />');
15079                     } else {
15080                         buf.unshift('<img src="'+this.emptyIcon+'" class="x-tree-icon" />');
15081                     }
15082                 }
15083                 p = p.parentNode;
15084             }
15085             this.childIndent = buf.join("");
15086         }
15087         return this.childIndent;
15088     },
15089
15090     renderIndent : function(){
15091         if(this.rendered){
15092             var indent = "";
15093             var p = this.node.parentNode;
15094             if(p){
15095                 indent = p.ui.getChildIndent();
15096             }
15097             if(this.indentMarkup != indent){ // don't rerender if not required
15098                 this.indentNode.innerHTML = indent;
15099                 this.indentMarkup = indent;
15100             }
15101             this.updateExpandIcon();
15102         }
15103     }
15104 };
15105
15106 Roo.tree.RootTreeNodeUI = function(){
15107     Roo.tree.RootTreeNodeUI.superclass.constructor.apply(this, arguments);
15108 };
15109 Roo.extend(Roo.tree.RootTreeNodeUI, Roo.tree.TreeNodeUI, {
15110     render : function(){
15111         if(!this.rendered){
15112             var targetNode = this.node.ownerTree.innerCt.dom;
15113             this.node.expanded = true;
15114             targetNode.innerHTML = '<div class="x-tree-root-node"></div>';
15115             this.wrap = this.ctNode = targetNode.firstChild;
15116         }
15117     },
15118     collapse : function(){
15119     },
15120     expand : function(){
15121     }
15122 });/*
15123  * Based on:
15124  * Ext JS Library 1.1.1
15125  * Copyright(c) 2006-2007, Ext JS, LLC.
15126  *
15127  * Originally Released Under LGPL - original licence link has changed is not relivant.
15128  *
15129  * Fork - LGPL
15130  * <script type="text/javascript">
15131  */
15132 /**
15133  * @class Roo.tree.TreeLoader
15134  * @extends Roo.util.Observable
15135  * A TreeLoader provides for lazy loading of an {@link Roo.tree.TreeNode}'s child
15136  * nodes from a specified URL. The response must be a javascript Array definition
15137  * who's elements are node definition objects. eg:
15138  * <pre><code>
15139 {  success : true,
15140    data :      [
15141    
15142     { 'id': 1, 'text': 'A folder Node', 'leaf': false },
15143     { 'id': 2, 'text': 'A leaf Node', 'leaf': true }
15144     ]
15145 }
15146
15147
15148 </code></pre>
15149  * <br><br>
15150  * The old style respose with just an array is still supported, but not recommended.
15151  * <br><br>
15152  *
15153  * A server request is sent, and child nodes are loaded only when a node is expanded.
15154  * The loading node's id is passed to the server under the parameter name "node" to
15155  * enable the server to produce the correct child nodes.
15156  * <br><br>
15157  * To pass extra parameters, an event handler may be attached to the "beforeload"
15158  * event, and the parameters specified in the TreeLoader's baseParams property:
15159  * <pre><code>
15160     myTreeLoader.on("beforeload", function(treeLoader, node) {
15161         this.baseParams.category = node.attributes.category;
15162     }, this);
15163     
15164 </code></pre>
15165  *
15166  * This would pass an HTTP parameter called "category" to the server containing
15167  * the value of the Node's "category" attribute.
15168  * @constructor
15169  * Creates a new Treeloader.
15170  * @param {Object} config A config object containing config properties.
15171  */
15172 Roo.tree.TreeLoader = function(config){
15173     this.baseParams = {};
15174     this.requestMethod = "POST";
15175     Roo.apply(this, config);
15176
15177     this.addEvents({
15178     
15179         /**
15180          * @event beforeload
15181          * Fires before a network request is made to retrieve the Json text which specifies a node's children.
15182          * @param {Object} This TreeLoader object.
15183          * @param {Object} node The {@link Roo.tree.TreeNode} object being loaded.
15184          * @param {Object} callback The callback function specified in the {@link #load} call.
15185          */
15186         beforeload : true,
15187         /**
15188          * @event load
15189          * Fires when the node has been successfuly loaded.
15190          * @param {Object} This TreeLoader object.
15191          * @param {Object} node The {@link Roo.tree.TreeNode} object being loaded.
15192          * @param {Object} response The response object containing the data from the server.
15193          */
15194         load : true,
15195         /**
15196          * @event loadexception
15197          * Fires if the network request failed.
15198          * @param {Object} This TreeLoader object.
15199          * @param {Object} node The {@link Roo.tree.TreeNode} object being loaded.
15200          * @param {Object} response The response object containing the data from the server.
15201          */
15202         loadexception : true,
15203         /**
15204          * @event create
15205          * Fires before a node is created, enabling you to return custom Node types 
15206          * @param {Object} This TreeLoader object.
15207          * @param {Object} attr - the data returned from the AJAX call (modify it to suit)
15208          */
15209         create : true
15210     });
15211
15212     Roo.tree.TreeLoader.superclass.constructor.call(this);
15213 };
15214
15215 Roo.extend(Roo.tree.TreeLoader, Roo.util.Observable, {
15216     /**
15217     * @cfg {String} dataUrl The URL from which to request a Json string which
15218     * specifies an array of node definition object representing the child nodes
15219     * to be loaded.
15220     */
15221     /**
15222     * @cfg {String} requestMethod either GET or POST
15223     * defaults to POST (due to BC)
15224     * to be loaded.
15225     */
15226     /**
15227     * @cfg {Object} baseParams (optional) An object containing properties which
15228     * specify HTTP parameters to be passed to each request for child nodes.
15229     */
15230     /**
15231     * @cfg {Object} baseAttrs (optional) An object containing attributes to be added to all nodes
15232     * created by this loader. If the attributes sent by the server have an attribute in this object,
15233     * they take priority.
15234     */
15235     /**
15236     * @cfg {Object} uiProviders (optional) An object containing properties which
15237     * 
15238     * DEPRECATED - use 'create' event handler to modify attributes - which affect creation.
15239     * specify custom {@link Roo.tree.TreeNodeUI} implementations. If the optional
15240     * <i>uiProvider</i> attribute of a returned child node is a string rather
15241     * than a reference to a TreeNodeUI implementation, this that string value
15242     * is used as a property name in the uiProviders object. You can define the provider named
15243     * 'default' , and this will be used for all nodes (if no uiProvider is delivered by the node data)
15244     */
15245     uiProviders : {},
15246
15247     /**
15248     * @cfg {Boolean} clearOnLoad (optional) Default to true. Remove previously existing
15249     * child nodes before loading.
15250     */
15251     clearOnLoad : true,
15252
15253     /**
15254     * @cfg {String} root (optional) Default to false. Use this to read data from an object 
15255     * property on loading, rather than expecting an array. (eg. more compatible to a standard
15256     * Grid query { data : [ .....] }
15257     */
15258     
15259     root : false,
15260      /**
15261     * @cfg {String} queryParam (optional) 
15262     * Name of the query as it will be passed on the querystring (defaults to 'node')
15263     * eg. the request will be ?node=[id]
15264     */
15265     
15266     
15267     queryParam: false,
15268     
15269     /**
15270      * Load an {@link Roo.tree.TreeNode} from the URL specified in the constructor.
15271      * This is called automatically when a node is expanded, but may be used to reload
15272      * a node (or append new children if the {@link #clearOnLoad} option is false.)
15273      * @param {Roo.tree.TreeNode} node
15274      * @param {Function} callback
15275      */
15276     load : function(node, callback){
15277         if(this.clearOnLoad){
15278             while(node.firstChild){
15279                 node.removeChild(node.firstChild);
15280             }
15281         }
15282         if(node.attributes.children){ // preloaded json children
15283             var cs = node.attributes.children;
15284             for(var i = 0, len = cs.length; i < len; i++){
15285                 node.appendChild(this.createNode(cs[i]));
15286             }
15287             if(typeof callback == "function"){
15288                 callback();
15289             }
15290         }else if(this.dataUrl){
15291             this.requestData(node, callback);
15292         }
15293     },
15294
15295     getParams: function(node){
15296         var buf = [], bp = this.baseParams;
15297         for(var key in bp){
15298             if(typeof bp[key] != "function"){
15299                 buf.push(encodeURIComponent(key), "=", encodeURIComponent(bp[key]), "&");
15300             }
15301         }
15302         var n = this.queryParam === false ? 'node' : this.queryParam;
15303         buf.push(n + "=", encodeURIComponent(node.id));
15304         return buf.join("");
15305     },
15306
15307     requestData : function(node, callback){
15308         if(this.fireEvent("beforeload", this, node, callback) !== false){
15309             this.transId = Roo.Ajax.request({
15310                 method:this.requestMethod,
15311                 url: this.dataUrl||this.url,
15312                 success: this.handleResponse,
15313                 failure: this.handleFailure,
15314                 scope: this,
15315                 argument: {callback: callback, node: node},
15316                 params: this.getParams(node)
15317             });
15318         }else{
15319             // if the load is cancelled, make sure we notify
15320             // the node that we are done
15321             if(typeof callback == "function"){
15322                 callback();
15323             }
15324         }
15325     },
15326
15327     isLoading : function(){
15328         return this.transId ? true : false;
15329     },
15330
15331     abort : function(){
15332         if(this.isLoading()){
15333             Roo.Ajax.abort(this.transId);
15334         }
15335     },
15336
15337     // private
15338     createNode : function(attr)
15339     {
15340         // apply baseAttrs, nice idea Corey!
15341         if(this.baseAttrs){
15342             Roo.applyIf(attr, this.baseAttrs);
15343         }
15344         if(this.applyLoader !== false){
15345             attr.loader = this;
15346         }
15347         // uiProvider = depreciated..
15348         
15349         if(typeof(attr.uiProvider) == 'string'){
15350            attr.uiProvider = this.uiProviders[attr.uiProvider] || 
15351                 /**  eval:var:attr */ eval(attr.uiProvider);
15352         }
15353         if(typeof(this.uiProviders['default']) != 'undefined') {
15354             attr.uiProvider = this.uiProviders['default'];
15355         }
15356         
15357         this.fireEvent('create', this, attr);
15358         
15359         attr.leaf  = typeof(attr.leaf) == 'string' ? attr.leaf * 1 : attr.leaf;
15360         return(attr.leaf ?
15361                         new Roo.tree.TreeNode(attr) :
15362                         new Roo.tree.AsyncTreeNode(attr));
15363     },
15364
15365     processResponse : function(response, node, callback)
15366     {
15367         var json = response.responseText;
15368         try {
15369             
15370             var o = Roo.decode(json);
15371             
15372             if (this.root === false && typeof(o.success) != undefined) {
15373                 this.root = 'data'; // the default behaviour for list like data..
15374                 }
15375                 
15376             if (this.root !== false &&  !o.success) {
15377                 // it's a failure condition.
15378                 var a = response.argument;
15379                 this.fireEvent("loadexception", this, a.node, response);
15380                 Roo.log("Load failed - should have a handler really");
15381                 return;
15382             }
15383             
15384             
15385             
15386             if (this.root !== false) {
15387                  o = o[this.root];
15388             }
15389             
15390             for(var i = 0, len = o.length; i < len; i++){
15391                 var n = this.createNode(o[i]);
15392                 if(n){
15393                     node.appendChild(n);
15394                 }
15395             }
15396             if(typeof callback == "function"){
15397                 callback(this, node);
15398             }
15399         }catch(e){
15400             this.handleFailure(response);
15401         }
15402     },
15403
15404     handleResponse : function(response){
15405         this.transId = false;
15406         var a = response.argument;
15407         this.processResponse(response, a.node, a.callback);
15408         this.fireEvent("load", this, a.node, response);
15409     },
15410
15411     handleFailure : function(response)
15412     {
15413         // should handle failure better..
15414         this.transId = false;
15415         var a = response.argument;
15416         this.fireEvent("loadexception", this, a.node, response);
15417         if(typeof a.callback == "function"){
15418             a.callback(this, a.node);
15419         }
15420     }
15421 });/*
15422  * Based on:
15423  * Ext JS Library 1.1.1
15424  * Copyright(c) 2006-2007, Ext JS, LLC.
15425  *
15426  * Originally Released Under LGPL - original licence link has changed is not relivant.
15427  *
15428  * Fork - LGPL
15429  * <script type="text/javascript">
15430  */
15431
15432 /**
15433 * @class Roo.tree.TreeFilter
15434 * Note this class is experimental and doesn't update the indent (lines) or expand collapse icons of the nodes
15435 * @param {TreePanel} tree
15436 * @param {Object} config (optional)
15437  */
15438 Roo.tree.TreeFilter = function(tree, config){
15439     this.tree = tree;
15440     this.filtered = {};
15441     Roo.apply(this, config);
15442 };
15443
15444 Roo.tree.TreeFilter.prototype = {
15445     clearBlank:false,
15446     reverse:false,
15447     autoClear:false,
15448     remove:false,
15449
15450      /**
15451      * Filter the data by a specific attribute.
15452      * @param {String/RegExp} value Either string that the attribute value
15453      * should start with or a RegExp to test against the attribute
15454      * @param {String} attr (optional) The attribute passed in your node's attributes collection. Defaults to "text".
15455      * @param {TreeNode} startNode (optional) The node to start the filter at.
15456      */
15457     filter : function(value, attr, startNode){
15458         attr = attr || "text";
15459         var f;
15460         if(typeof value == "string"){
15461             var vlen = value.length;
15462             // auto clear empty filter
15463             if(vlen == 0 && this.clearBlank){
15464                 this.clear();
15465                 return;
15466             }
15467             value = value.toLowerCase();
15468             f = function(n){
15469                 return n.attributes[attr].substr(0, vlen).toLowerCase() == value;
15470             };
15471         }else if(value.exec){ // regex?
15472             f = function(n){
15473                 return value.test(n.attributes[attr]);
15474             };
15475         }else{
15476             throw 'Illegal filter type, must be string or regex';
15477         }
15478         this.filterBy(f, null, startNode);
15479         },
15480
15481     /**
15482      * Filter by a function. The passed function will be called with each
15483      * node in the tree (or from the startNode). If the function returns true, the node is kept
15484      * otherwise it is filtered. If a node is filtered, its children are also filtered.
15485      * @param {Function} fn The filter function
15486      * @param {Object} scope (optional) The scope of the function (defaults to the current node)
15487      */
15488     filterBy : function(fn, scope, startNode){
15489         startNode = startNode || this.tree.root;
15490         if(this.autoClear){
15491             this.clear();
15492         }
15493         var af = this.filtered, rv = this.reverse;
15494         var f = function(n){
15495             if(n == startNode){
15496                 return true;
15497             }
15498             if(af[n.id]){
15499                 return false;
15500             }
15501             var m = fn.call(scope || n, n);
15502             if(!m || rv){
15503                 af[n.id] = n;
15504                 n.ui.hide();
15505                 return false;
15506             }
15507             return true;
15508         };
15509         startNode.cascade(f);
15510         if(this.remove){
15511            for(var id in af){
15512                if(typeof id != "function"){
15513                    var n = af[id];
15514                    if(n && n.parentNode){
15515                        n.parentNode.removeChild(n);
15516                    }
15517                }
15518            }
15519         }
15520     },
15521
15522     /**
15523      * Clears the current filter. Note: with the "remove" option
15524      * set a filter cannot be cleared.
15525      */
15526     clear : function(){
15527         var t = this.tree;
15528         var af = this.filtered;
15529         for(var id in af){
15530             if(typeof id != "function"){
15531                 var n = af[id];
15532                 if(n){
15533                     n.ui.show();
15534                 }
15535             }
15536         }
15537         this.filtered = {};
15538     }
15539 };
15540 /*
15541  * Based on:
15542  * Ext JS Library 1.1.1
15543  * Copyright(c) 2006-2007, Ext JS, LLC.
15544  *
15545  * Originally Released Under LGPL - original licence link has changed is not relivant.
15546  *
15547  * Fork - LGPL
15548  * <script type="text/javascript">
15549  */
15550  
15551
15552 /**
15553  * @class Roo.tree.TreeSorter
15554  * Provides sorting of nodes in a TreePanel
15555  * 
15556  * @cfg {Boolean} folderSort True to sort leaf nodes under non leaf nodes
15557  * @cfg {String} property The named attribute on the node to sort by (defaults to text)
15558  * @cfg {String} dir The direction to sort (asc or desc) (defaults to asc)
15559  * @cfg {String} leafAttr The attribute used to determine leaf nodes in folder sort (defaults to "leaf")
15560  * @cfg {Boolean} caseSensitive true for case sensitive sort (defaults to false)
15561  * @cfg {Function} sortType A custom "casting" function used to convert node values before sorting
15562  * @constructor
15563  * @param {TreePanel} tree
15564  * @param {Object} config
15565  */
15566 Roo.tree.TreeSorter = function(tree, config){
15567     Roo.apply(this, config);
15568     tree.on("beforechildrenrendered", this.doSort, this);
15569     tree.on("append", this.updateSort, this);
15570     tree.on("insert", this.updateSort, this);
15571     
15572     var dsc = this.dir && this.dir.toLowerCase() == "desc";
15573     var p = this.property || "text";
15574     var sortType = this.sortType;
15575     var fs = this.folderSort;
15576     var cs = this.caseSensitive === true;
15577     var leafAttr = this.leafAttr || 'leaf';
15578
15579     this.sortFn = function(n1, n2){
15580         if(fs){
15581             if(n1.attributes[leafAttr] && !n2.attributes[leafAttr]){
15582                 return 1;
15583             }
15584             if(!n1.attributes[leafAttr] && n2.attributes[leafAttr]){
15585                 return -1;
15586             }
15587         }
15588         var v1 = sortType ? sortType(n1) : (cs ? n1.attributes[p] : n1.attributes[p].toUpperCase());
15589         var v2 = sortType ? sortType(n2) : (cs ? n2.attributes[p] : n2.attributes[p].toUpperCase());
15590         if(v1 < v2){
15591                         return dsc ? +1 : -1;
15592                 }else if(v1 > v2){
15593                         return dsc ? -1 : +1;
15594         }else{
15595                 return 0;
15596         }
15597     };
15598 };
15599
15600 Roo.tree.TreeSorter.prototype = {
15601     doSort : function(node){
15602         node.sort(this.sortFn);
15603     },
15604     
15605     compareNodes : function(n1, n2){
15606         return (n1.text.toUpperCase() > n2.text.toUpperCase() ? 1 : -1);
15607     },
15608     
15609     updateSort : function(tree, node){
15610         if(node.childrenRendered){
15611             this.doSort.defer(1, this, [node]);
15612         }
15613     }
15614 };/*
15615  * Based on:
15616  * Ext JS Library 1.1.1
15617  * Copyright(c) 2006-2007, Ext JS, LLC.
15618  *
15619  * Originally Released Under LGPL - original licence link has changed is not relivant.
15620  *
15621  * Fork - LGPL
15622  * <script type="text/javascript">
15623  */
15624
15625 if(Roo.dd.DropZone){
15626     
15627 Roo.tree.TreeDropZone = function(tree, config){
15628     this.allowParentInsert = false;
15629     this.allowContainerDrop = false;
15630     this.appendOnly = false;
15631     Roo.tree.TreeDropZone.superclass.constructor.call(this, tree.innerCt, config);
15632     this.tree = tree;
15633     this.lastInsertClass = "x-tree-no-status";
15634     this.dragOverData = {};
15635 };
15636
15637 Roo.extend(Roo.tree.TreeDropZone, Roo.dd.DropZone, {
15638     ddGroup : "TreeDD",
15639     scroll:  true,
15640     
15641     expandDelay : 1000,
15642     
15643     expandNode : function(node){
15644         if(node.hasChildNodes() && !node.isExpanded()){
15645             node.expand(false, null, this.triggerCacheRefresh.createDelegate(this));
15646         }
15647     },
15648     
15649     queueExpand : function(node){
15650         this.expandProcId = this.expandNode.defer(this.expandDelay, this, [node]);
15651     },
15652     
15653     cancelExpand : function(){
15654         if(this.expandProcId){
15655             clearTimeout(this.expandProcId);
15656             this.expandProcId = false;
15657         }
15658     },
15659     
15660     isValidDropPoint : function(n, pt, dd, e, data){
15661         if(!n || !data){ return false; }
15662         var targetNode = n.node;
15663         var dropNode = data.node;
15664         // default drop rules
15665         if(!(targetNode && targetNode.isTarget && pt)){
15666             return false;
15667         }
15668         if(pt == "append" && targetNode.allowChildren === false){
15669             return false;
15670         }
15671         if((pt == "above" || pt == "below") && (targetNode.parentNode && targetNode.parentNode.allowChildren === false)){
15672             return false;
15673         }
15674         if(dropNode && (targetNode == dropNode || dropNode.contains(targetNode))){
15675             return false;
15676         }
15677         // reuse the object
15678         var overEvent = this.dragOverData;
15679         overEvent.tree = this.tree;
15680         overEvent.target = targetNode;
15681         overEvent.data = data;
15682         overEvent.point = pt;
15683         overEvent.source = dd;
15684         overEvent.rawEvent = e;
15685         overEvent.dropNode = dropNode;
15686         overEvent.cancel = false;  
15687         var result = this.tree.fireEvent("nodedragover", overEvent);
15688         return overEvent.cancel === false && result !== false;
15689     },
15690     
15691     getDropPoint : function(e, n, dd)
15692     {
15693         var tn = n.node;
15694         if(tn.isRoot){
15695             return tn.allowChildren !== false ? "append" : false; // always append for root
15696         }
15697         var dragEl = n.ddel;
15698         var t = Roo.lib.Dom.getY(dragEl), b = t + dragEl.offsetHeight;
15699         var y = Roo.lib.Event.getPageY(e);
15700         //var noAppend = tn.allowChildren === false || tn.isLeaf();
15701         
15702         // we may drop nodes anywhere, as long as allowChildren has not been set to false..
15703         var noAppend = tn.allowChildren === false;
15704         if(this.appendOnly || tn.parentNode.allowChildren === false){
15705             return noAppend ? false : "append";
15706         }
15707         var noBelow = false;
15708         if(!this.allowParentInsert){
15709             noBelow = tn.hasChildNodes() && tn.isExpanded();
15710         }
15711         var q = (b - t) / (noAppend ? 2 : 3);
15712         if(y >= t && y < (t + q)){
15713             return "above";
15714         }else if(!noBelow && (noAppend || y >= b-q && y <= b)){
15715             return "below";
15716         }else{
15717             return "append";
15718         }
15719     },
15720     
15721     onNodeEnter : function(n, dd, e, data)
15722     {
15723         this.cancelExpand();
15724     },
15725     
15726     onNodeOver : function(n, dd, e, data)
15727     {
15728        
15729         var pt = this.getDropPoint(e, n, dd);
15730         var node = n.node;
15731         
15732         // auto node expand check
15733         if(!this.expandProcId && pt == "append" && node.hasChildNodes() && !n.node.isExpanded()){
15734             this.queueExpand(node);
15735         }else if(pt != "append"){
15736             this.cancelExpand();
15737         }
15738         
15739         // set the insert point style on the target node
15740         var returnCls = this.dropNotAllowed;
15741         if(this.isValidDropPoint(n, pt, dd, e, data)){
15742            if(pt){
15743                var el = n.ddel;
15744                var cls;
15745                if(pt == "above"){
15746                    returnCls = n.node.isFirst() ? "x-tree-drop-ok-above" : "x-tree-drop-ok-between";
15747                    cls = "x-tree-drag-insert-above";
15748                }else if(pt == "below"){
15749                    returnCls = n.node.isLast() ? "x-tree-drop-ok-below" : "x-tree-drop-ok-between";
15750                    cls = "x-tree-drag-insert-below";
15751                }else{
15752                    returnCls = "x-tree-drop-ok-append";
15753                    cls = "x-tree-drag-append";
15754                }
15755                if(this.lastInsertClass != cls){
15756                    Roo.fly(el).replaceClass(this.lastInsertClass, cls);
15757                    this.lastInsertClass = cls;
15758                }
15759            }
15760        }
15761        return returnCls;
15762     },
15763     
15764     onNodeOut : function(n, dd, e, data){
15765         
15766         this.cancelExpand();
15767         this.removeDropIndicators(n);
15768     },
15769     
15770     onNodeDrop : function(n, dd, e, data){
15771         var point = this.getDropPoint(e, n, dd);
15772         var targetNode = n.node;
15773         targetNode.ui.startDrop();
15774         if(!this.isValidDropPoint(n, point, dd, e, data)){
15775             targetNode.ui.endDrop();
15776             return false;
15777         }
15778         // first try to find the drop node
15779         var dropNode = data.node || (dd.getTreeNode ? dd.getTreeNode(data, targetNode, point, e) : null);
15780         var dropEvent = {
15781             tree : this.tree,
15782             target: targetNode,
15783             data: data,
15784             point: point,
15785             source: dd,
15786             rawEvent: e,
15787             dropNode: dropNode,
15788             cancel: !dropNode   
15789         };
15790         var retval = this.tree.fireEvent("beforenodedrop", dropEvent);
15791         if(retval === false || dropEvent.cancel === true || !dropEvent.dropNode){
15792             targetNode.ui.endDrop();
15793             return false;
15794         }
15795         // allow target changing
15796         targetNode = dropEvent.target;
15797         if(point == "append" && !targetNode.isExpanded()){
15798             targetNode.expand(false, null, function(){
15799                 this.completeDrop(dropEvent);
15800             }.createDelegate(this));
15801         }else{
15802             this.completeDrop(dropEvent);
15803         }
15804         return true;
15805     },
15806     
15807     completeDrop : function(de){
15808         var ns = de.dropNode, p = de.point, t = de.target;
15809         if(!(ns instanceof Array)){
15810             ns = [ns];
15811         }
15812         var n;
15813         for(var i = 0, len = ns.length; i < len; i++){
15814             n = ns[i];
15815             if(p == "above"){
15816                 t.parentNode.insertBefore(n, t);
15817             }else if(p == "below"){
15818                 t.parentNode.insertBefore(n, t.nextSibling);
15819             }else{
15820                 t.appendChild(n);
15821             }
15822         }
15823         n.ui.focus();
15824         if(this.tree.hlDrop){
15825             n.ui.highlight();
15826         }
15827         t.ui.endDrop();
15828         this.tree.fireEvent("nodedrop", de);
15829     },
15830     
15831     afterNodeMoved : function(dd, data, e, targetNode, dropNode){
15832         if(this.tree.hlDrop){
15833             dropNode.ui.focus();
15834             dropNode.ui.highlight();
15835         }
15836         this.tree.fireEvent("nodedrop", this.tree, targetNode, data, dd, e);
15837     },
15838     
15839     getTree : function(){
15840         return this.tree;
15841     },
15842     
15843     removeDropIndicators : function(n){
15844         if(n && n.ddel){
15845             var el = n.ddel;
15846             Roo.fly(el).removeClass([
15847                     "x-tree-drag-insert-above",
15848                     "x-tree-drag-insert-below",
15849                     "x-tree-drag-append"]);
15850             this.lastInsertClass = "_noclass";
15851         }
15852     },
15853     
15854     beforeDragDrop : function(target, e, id){
15855         this.cancelExpand();
15856         return true;
15857     },
15858     
15859     afterRepair : function(data){
15860         if(data && Roo.enableFx){
15861             data.node.ui.highlight();
15862         }
15863         this.hideProxy();
15864     } 
15865     
15866 });
15867
15868 }
15869 /*
15870  * Based on:
15871  * Ext JS Library 1.1.1
15872  * Copyright(c) 2006-2007, Ext JS, LLC.
15873  *
15874  * Originally Released Under LGPL - original licence link has changed is not relivant.
15875  *
15876  * Fork - LGPL
15877  * <script type="text/javascript">
15878  */
15879  
15880
15881 if(Roo.dd.DragZone){
15882 Roo.tree.TreeDragZone = function(tree, config){
15883     Roo.tree.TreeDragZone.superclass.constructor.call(this, tree.getTreeEl(), config);
15884     this.tree = tree;
15885 };
15886
15887 Roo.extend(Roo.tree.TreeDragZone, Roo.dd.DragZone, {
15888     ddGroup : "TreeDD",
15889    
15890     onBeforeDrag : function(data, e){
15891         var n = data.node;
15892         return n && n.draggable && !n.disabled;
15893     },
15894      
15895     
15896     onInitDrag : function(e){
15897         var data = this.dragData;
15898         this.tree.getSelectionModel().select(data.node);
15899         this.proxy.update("");
15900         data.node.ui.appendDDGhost(this.proxy.ghost.dom);
15901         this.tree.fireEvent("startdrag", this.tree, data.node, e);
15902     },
15903     
15904     getRepairXY : function(e, data){
15905         return data.node.ui.getDDRepairXY();
15906     },
15907     
15908     onEndDrag : function(data, e){
15909         this.tree.fireEvent("enddrag", this.tree, data.node, e);
15910         
15911         
15912     },
15913     
15914     onValidDrop : function(dd, e, id){
15915         this.tree.fireEvent("dragdrop", this.tree, this.dragData.node, dd, e);
15916         this.hideProxy();
15917     },
15918     
15919     beforeInvalidDrop : function(e, id){
15920         // this scrolls the original position back into view
15921         var sm = this.tree.getSelectionModel();
15922         sm.clearSelections();
15923         sm.select(this.dragData.node);
15924     }
15925 });
15926 }/*
15927  * Based on:
15928  * Ext JS Library 1.1.1
15929  * Copyright(c) 2006-2007, Ext JS, LLC.
15930  *
15931  * Originally Released Under LGPL - original licence link has changed is not relivant.
15932  *
15933  * Fork - LGPL
15934  * <script type="text/javascript">
15935  */
15936 /**
15937  * @class Roo.tree.TreeEditor
15938  * @extends Roo.Editor
15939  * Provides editor functionality for inline tree node editing.  Any valid {@link Roo.form.Field} can be used
15940  * as the editor field.
15941  * @constructor
15942  * @param {Object} config (used to be the tree panel.)
15943  * @param {Object} oldconfig DEPRECIATED Either a prebuilt {@link Roo.form.Field} instance or a Field config object
15944  * 
15945  * @cfg {Roo.tree.TreePanel} tree The tree to bind to.
15946  * @cfg {Roo.form.TextField} field [required] The field configuration
15947  *
15948  * 
15949  */
15950 Roo.tree.TreeEditor = function(config, oldconfig) { // was -- (tree, config){
15951     var tree = config;
15952     var field;
15953     if (oldconfig) { // old style..
15954         field = oldconfig.events ? oldconfig : new Roo.form.TextField(oldconfig);
15955     } else {
15956         // new style..
15957         tree = config.tree;
15958         config.field = config.field  || {};
15959         config.field.xtype = 'TextField';
15960         field = Roo.factory(config.field, Roo.form);
15961     }
15962     config = config || {};
15963     
15964     
15965     this.addEvents({
15966         /**
15967          * @event beforenodeedit
15968          * Fires when editing is initiated, but before the value changes.  Editing can be canceled by returning
15969          * false from the handler of this event.
15970          * @param {Editor} this
15971          * @param {Roo.tree.Node} node 
15972          */
15973         "beforenodeedit" : true
15974     });
15975     
15976     //Roo.log(config);
15977     Roo.tree.TreeEditor.superclass.constructor.call(this, field, config);
15978
15979     this.tree = tree;
15980
15981     tree.on('beforeclick', this.beforeNodeClick, this);
15982     tree.getTreeEl().on('mousedown', this.hide, this);
15983     this.on('complete', this.updateNode, this);
15984     this.on('beforestartedit', this.fitToTree, this);
15985     this.on('startedit', this.bindScroll, this, {delay:10});
15986     this.on('specialkey', this.onSpecialKey, this);
15987 };
15988
15989 Roo.extend(Roo.tree.TreeEditor, Roo.Editor, {
15990     /**
15991      * @cfg {String} alignment
15992      * The position to align to (see {@link Roo.Element#alignTo} for more details, defaults to "l-l").
15993      */
15994     alignment: "l-l",
15995     // inherit
15996     autoSize: false,
15997     /**
15998      * @cfg {Boolean} hideEl
15999      * True to hide the bound element while the editor is displayed (defaults to false)
16000      */
16001     hideEl : false,
16002     /**
16003      * @cfg {String} cls
16004      * CSS class to apply to the editor (defaults to "x-small-editor x-tree-editor")
16005      */
16006     cls: "x-small-editor x-tree-editor",
16007     /**
16008      * @cfg {Boolean} shim
16009      * True to shim the editor if selects/iframes could be displayed beneath it (defaults to false)
16010      */
16011     shim:false,
16012     // inherit
16013     shadow:"frame",
16014     /**
16015      * @cfg {Number} maxWidth
16016      * The maximum width in pixels of the editor field (defaults to 250).  Note that if the maxWidth would exceed
16017      * the containing tree element's size, it will be automatically limited for you to the container width, taking
16018      * scroll and client offsets into account prior to each edit.
16019      */
16020     maxWidth: 250,
16021
16022     editDelay : 350,
16023
16024     // private
16025     fitToTree : function(ed, el){
16026         var td = this.tree.getTreeEl().dom, nd = el.dom;
16027         if(td.scrollLeft >  nd.offsetLeft){ // ensure the node left point is visible
16028             td.scrollLeft = nd.offsetLeft;
16029         }
16030         var w = Math.min(
16031                 this.maxWidth,
16032                 (td.clientWidth > 20 ? td.clientWidth : td.offsetWidth) - Math.max(0, nd.offsetLeft-td.scrollLeft) - /*cushion*/5);
16033         this.setSize(w, '');
16034         
16035         return this.fireEvent('beforenodeedit', this, this.editNode);
16036         
16037     },
16038
16039     // private
16040     triggerEdit : function(node){
16041         this.completeEdit();
16042         this.editNode = node;
16043         this.startEdit(node.ui.textNode, node.text);
16044     },
16045
16046     // private
16047     bindScroll : function(){
16048         this.tree.getTreeEl().on('scroll', this.cancelEdit, this);
16049     },
16050
16051     // private
16052     beforeNodeClick : function(node, e){
16053         var sinceLast = (this.lastClick ? this.lastClick.getElapsed() : 0);
16054         this.lastClick = new Date();
16055         if(sinceLast > this.editDelay && this.tree.getSelectionModel().isSelected(node)){
16056             e.stopEvent();
16057             this.triggerEdit(node);
16058             return false;
16059         }
16060         return true;
16061     },
16062
16063     // private
16064     updateNode : function(ed, value){
16065         this.tree.getTreeEl().un('scroll', this.cancelEdit, this);
16066         this.editNode.setText(value);
16067     },
16068
16069     // private
16070     onHide : function(){
16071         Roo.tree.TreeEditor.superclass.onHide.call(this);
16072         if(this.editNode){
16073             this.editNode.ui.focus();
16074         }
16075     },
16076
16077     // private
16078     onSpecialKey : function(field, e){
16079         var k = e.getKey();
16080         if(k == e.ESC){
16081             e.stopEvent();
16082             this.cancelEdit();
16083         }else if(k == e.ENTER && !e.hasModifier()){
16084             e.stopEvent();
16085             this.completeEdit();
16086         }
16087     }
16088 });//<Script type="text/javascript">
16089 /*
16090  * Based on:
16091  * Ext JS Library 1.1.1
16092  * Copyright(c) 2006-2007, Ext JS, LLC.
16093  *
16094  * Originally Released Under LGPL - original licence link has changed is not relivant.
16095  *
16096  * Fork - LGPL
16097  * <script type="text/javascript">
16098  */
16099  
16100 /**
16101  * Not documented??? - probably should be...
16102  */
16103
16104 Roo.tree.ColumnNodeUI = Roo.extend(Roo.tree.TreeNodeUI, {
16105     //focus: Roo.emptyFn, // prevent odd scrolling behavior
16106     
16107     renderElements : function(n, a, targetNode, bulkRender){
16108         //consel.log("renderElements?");
16109         this.indentMarkup = n.parentNode ? n.parentNode.ui.getChildIndent() : '';
16110
16111         var t = n.getOwnerTree();
16112         var tid = Pman.Tab.Document_TypesTree.tree.el.id;
16113         
16114         var cols = t.columns;
16115         var bw = t.borderWidth;
16116         var c = cols[0];
16117         var href = a.href ? a.href : Roo.isGecko ? "" : "#";
16118          var cb = typeof a.checked == "boolean";
16119         var tx = String.format('{0}',n.text || (c.renderer ? c.renderer(a[c.dataIndex], n, a) : a[c.dataIndex]));
16120         var colcls = 'x-t-' + tid + '-c0';
16121         var buf = [
16122             '<li class="x-tree-node">',
16123             
16124                 
16125                 '<div class="x-tree-node-el ', a.cls,'">',
16126                     // extran...
16127                     '<div class="x-tree-col ', colcls, '" style="width:', c.width-bw, 'px;">',
16128                 
16129                 
16130                         '<span class="x-tree-node-indent">',this.indentMarkup,'</span>',
16131                         '<img src="', this.emptyIcon, '" class="x-tree-ec-icon  " />',
16132                         '<img src="', a.icon || this.emptyIcon, '" class="x-tree-node-icon',
16133                            (a.icon ? ' x-tree-node-inline-icon' : ''),
16134                            (a.iconCls ? ' '+a.iconCls : ''),
16135                            '" unselectable="on" />',
16136                         (cb ? ('<input class="x-tree-node-cb" type="checkbox" ' + 
16137                              (a.checked ? 'checked="checked" />' : ' />')) : ''),
16138                              
16139                         '<a class="x-tree-node-anchor" hidefocus="on" href="',href,'" tabIndex="1" ',
16140                             (a.hrefTarget ? ' target="' +a.hrefTarget + '"' : ''), '>',
16141                             '<span unselectable="on" qtip="' + tx + '">',
16142                              tx,
16143                              '</span></a>' ,
16144                     '</div>',
16145                      '<a class="x-tree-node-anchor" hidefocus="on" href="',href,'" tabIndex="1" ',
16146                             (a.hrefTarget ? ' target="' +a.hrefTarget + '"' : ''), '>'
16147                  ];
16148         for(var i = 1, len = cols.length; i < len; i++){
16149             c = cols[i];
16150             colcls = 'x-t-' + tid + '-c' +i;
16151             tx = String.format('{0}', (c.renderer ? c.renderer(a[c.dataIndex], n, a) : a[c.dataIndex]));
16152             buf.push('<div class="x-tree-col ', colcls, ' ' ,(c.cls?c.cls:''),'" style="width:',c.width-bw,'px;">',
16153                         '<div class="x-tree-col-text" qtip="' + tx +'">',tx,"</div>",
16154                       "</div>");
16155          }
16156          
16157          buf.push(
16158             '</a>',
16159             '<div class="x-clear"></div></div>',
16160             '<ul class="x-tree-node-ct" style="display:none;"></ul>',
16161             "</li>");
16162         
16163         if(bulkRender !== true && n.nextSibling && n.nextSibling.ui.getEl()){
16164             this.wrap = Roo.DomHelper.insertHtml("beforeBegin",
16165                                 n.nextSibling.ui.getEl(), buf.join(""));
16166         }else{
16167             this.wrap = Roo.DomHelper.insertHtml("beforeEnd", targetNode, buf.join(""));
16168         }
16169         var el = this.wrap.firstChild;
16170         this.elRow = el;
16171         this.elNode = el.firstChild;
16172         this.ranchor = el.childNodes[1];
16173         this.ctNode = this.wrap.childNodes[1];
16174         var cs = el.firstChild.childNodes;
16175         this.indentNode = cs[0];
16176         this.ecNode = cs[1];
16177         this.iconNode = cs[2];
16178         var index = 3;
16179         if(cb){
16180             this.checkbox = cs[3];
16181             index++;
16182         }
16183         this.anchor = cs[index];
16184         
16185         this.textNode = cs[index].firstChild;
16186         
16187         //el.on("click", this.onClick, this);
16188         //el.on("dblclick", this.onDblClick, this);
16189         
16190         
16191        // console.log(this);
16192     },
16193     initEvents : function(){
16194         Roo.tree.ColumnNodeUI.superclass.initEvents.call(this);
16195         
16196             
16197         var a = this.ranchor;
16198
16199         var el = Roo.get(a);
16200
16201         if(Roo.isOpera){ // opera render bug ignores the CSS
16202             el.setStyle("text-decoration", "none");
16203         }
16204
16205         el.on("click", this.onClick, this);
16206         el.on("dblclick", this.onDblClick, this);
16207         el.on("contextmenu", this.onContextMenu, this);
16208         
16209     },
16210     
16211     /*onSelectedChange : function(state){
16212         if(state){
16213             this.focus();
16214             this.addClass("x-tree-selected");
16215         }else{
16216             //this.blur();
16217             this.removeClass("x-tree-selected");
16218         }
16219     },*/
16220     addClass : function(cls){
16221         if(this.elRow){
16222             Roo.fly(this.elRow).addClass(cls);
16223         }
16224         
16225     },
16226     
16227     
16228     removeClass : function(cls){
16229         if(this.elRow){
16230             Roo.fly(this.elRow).removeClass(cls);
16231         }
16232     }
16233
16234     
16235     
16236 });//<Script type="text/javascript">
16237
16238 /*
16239  * Based on:
16240  * Ext JS Library 1.1.1
16241  * Copyright(c) 2006-2007, Ext JS, LLC.
16242  *
16243  * Originally Released Under LGPL - original licence link has changed is not relivant.
16244  *
16245  * Fork - LGPL
16246  * <script type="text/javascript">
16247  */
16248  
16249
16250 /**
16251  * @class Roo.tree.ColumnTree
16252  * @extends Roo.tree.TreePanel
16253  * @cfg {Object} columns  Including width, header, renderer, cls, dataIndex 
16254  * @cfg {int} borderWidth  compined right/left border allowance
16255  * @constructor
16256  * @param {String/HTMLElement/Element} el The container element
16257  * @param {Object} config
16258  */
16259 Roo.tree.ColumnTree =  function(el, config)
16260 {
16261    Roo.tree.ColumnTree.superclass.constructor.call(this, el , config);
16262    this.addEvents({
16263         /**
16264         * @event resize
16265         * Fire this event on a container when it resizes
16266         * @param {int} w Width
16267         * @param {int} h Height
16268         */
16269        "resize" : true
16270     });
16271     this.on('resize', this.onResize, this);
16272 };
16273
16274 Roo.extend(Roo.tree.ColumnTree, Roo.tree.TreePanel, {
16275     //lines:false,
16276     
16277     
16278     borderWidth: Roo.isBorderBox ? 0 : 2, 
16279     headEls : false,
16280     
16281     render : function(){
16282         // add the header.....
16283        
16284         Roo.tree.ColumnTree.superclass.render.apply(this);
16285         
16286         this.el.addClass('x-column-tree');
16287         
16288         this.headers = this.el.createChild(
16289             {cls:'x-tree-headers'},this.innerCt.dom);
16290    
16291         var cols = this.columns, c;
16292         var totalWidth = 0;
16293         this.headEls = [];
16294         var  len = cols.length;
16295         for(var i = 0; i < len; i++){
16296              c = cols[i];
16297              totalWidth += c.width;
16298             this.headEls.push(this.headers.createChild({
16299                  cls:'x-tree-hd ' + (c.cls?c.cls+'-hd':''),
16300                  cn: {
16301                      cls:'x-tree-hd-text',
16302                      html: c.header
16303                  },
16304                  style:'width:'+(c.width-this.borderWidth)+'px;'
16305              }));
16306         }
16307         this.headers.createChild({cls:'x-clear'});
16308         // prevent floats from wrapping when clipped
16309         this.headers.setWidth(totalWidth);
16310         //this.innerCt.setWidth(totalWidth);
16311         this.innerCt.setStyle({ overflow: 'auto' });
16312         this.onResize(this.width, this.height);
16313              
16314         
16315     },
16316     onResize : function(w,h)
16317     {
16318         this.height = h;
16319         this.width = w;
16320         // resize cols..
16321         this.innerCt.setWidth(this.width);
16322         this.innerCt.setHeight(this.height-20);
16323         
16324         // headers...
16325         var cols = this.columns, c;
16326         var totalWidth = 0;
16327         var expEl = false;
16328         var len = cols.length;
16329         for(var i = 0; i < len; i++){
16330             c = cols[i];
16331             if (this.autoExpandColumn !== false && c.dataIndex == this.autoExpandColumn) {
16332                 // it's the expander..
16333                 expEl  = this.headEls[i];
16334                 continue;
16335             }
16336             totalWidth += c.width;
16337             
16338         }
16339         if (expEl) {
16340             expEl.setWidth(  ((w - totalWidth)-this.borderWidth - 20));
16341         }
16342         this.headers.setWidth(w-20);
16343
16344         
16345         
16346         
16347     }
16348 });
16349 /*
16350  * Based on:
16351  * Ext JS Library 1.1.1
16352  * Copyright(c) 2006-2007, Ext JS, LLC.
16353  *
16354  * Originally Released Under LGPL - original licence link has changed is not relivant.
16355  *
16356  * Fork - LGPL
16357  * <script type="text/javascript">
16358  */
16359  
16360 /**
16361  * @class Roo.menu.Menu
16362  * @extends Roo.util.Observable
16363  * @children Roo.menu.Item Roo.menu.Separator Roo.menu.TextItem
16364  * A menu object.  This is the container to which you add all other menu items.  Menu can also serve a as a base class
16365  * when you want a specialzed menu based off of another component (like {@link Roo.menu.DateMenu} for example).
16366  * @constructor
16367  * Creates a new Menu
16368  * @param {Object} config Configuration options
16369  */
16370 Roo.menu.Menu = function(config){
16371     
16372     Roo.menu.Menu.superclass.constructor.call(this, config);
16373     
16374     this.id = this.id || Roo.id();
16375     this.addEvents({
16376         /**
16377          * @event beforeshow
16378          * Fires before this menu is displayed
16379          * @param {Roo.menu.Menu} this
16380          */
16381         beforeshow : true,
16382         /**
16383          * @event beforehide
16384          * Fires before this menu is hidden
16385          * @param {Roo.menu.Menu} this
16386          */
16387         beforehide : true,
16388         /**
16389          * @event show
16390          * Fires after this menu is displayed
16391          * @param {Roo.menu.Menu} this
16392          */
16393         show : true,
16394         /**
16395          * @event hide
16396          * Fires after this menu is hidden
16397          * @param {Roo.menu.Menu} this
16398          */
16399         hide : true,
16400         /**
16401          * @event click
16402          * Fires when this menu is clicked (or when the enter key is pressed while it is active)
16403          * @param {Roo.menu.Menu} this
16404          * @param {Roo.menu.Item} menuItem The menu item that was clicked
16405          * @param {Roo.EventObject} e
16406          */
16407         click : true,
16408         /**
16409          * @event mouseover
16410          * Fires when the mouse is hovering over this menu
16411          * @param {Roo.menu.Menu} this
16412          * @param {Roo.EventObject} e
16413          * @param {Roo.menu.Item} menuItem The menu item that was clicked
16414          */
16415         mouseover : true,
16416         /**
16417          * @event mouseout
16418          * Fires when the mouse exits this menu
16419          * @param {Roo.menu.Menu} this
16420          * @param {Roo.EventObject} e
16421          * @param {Roo.menu.Item} menuItem The menu item that was clicked
16422          */
16423         mouseout : true,
16424         /**
16425          * @event itemclick
16426          * Fires when a menu item contained in this menu is clicked
16427          * @param {Roo.menu.BaseItem} baseItem The BaseItem that was clicked
16428          * @param {Roo.EventObject} e
16429          */
16430         itemclick: true
16431     });
16432     if (this.registerMenu) {
16433         Roo.menu.MenuMgr.register(this);
16434     }
16435     
16436     var mis = this.items;
16437     this.items = new Roo.util.MixedCollection();
16438     if(mis){
16439         this.add.apply(this, mis);
16440     }
16441 };
16442
16443 Roo.extend(Roo.menu.Menu, Roo.util.Observable, {
16444     /**
16445      * @cfg {Number} minWidth The minimum width of the menu in pixels (defaults to 120)
16446      */
16447     minWidth : 120,
16448     /**
16449      * @cfg {Boolean/String} shadow True or "sides" for the default effect, "frame" for 4-way shadow, and "drop"
16450      * for bottom-right shadow (defaults to "sides")
16451      */
16452     shadow : "sides",
16453     /**
16454      * @cfg {String} subMenuAlign The {@link Roo.Element#alignTo} anchor position value to use for submenus of
16455      * this menu (defaults to "tl-tr?")
16456      */
16457     subMenuAlign : "tl-tr?",
16458     /**
16459      * @cfg {String} defaultAlign The default {@link Roo.Element#alignTo) anchor position value for this menu
16460      * relative to its element of origin (defaults to "tl-bl?")
16461      */
16462     defaultAlign : "tl-bl?",
16463     /**
16464      * @cfg {Boolean} allowOtherMenus True to allow multiple menus to be displayed at the same time (defaults to false)
16465      */
16466     allowOtherMenus : false,
16467     /**
16468      * @cfg {Boolean} registerMenu True (default) - means that clicking on screen etc. hides it.
16469      */
16470     registerMenu : true,
16471
16472     hidden:true,
16473
16474     // private
16475     render : function(){
16476         if(this.el){
16477             return;
16478         }
16479         var el = this.el = new Roo.Layer({
16480             cls: "x-menu",
16481             shadow:this.shadow,
16482             constrain: false,
16483             parentEl: this.parentEl || document.body,
16484             zindex:15000
16485         });
16486
16487         this.keyNav = new Roo.menu.MenuNav(this);
16488
16489         if(this.plain){
16490             el.addClass("x-menu-plain");
16491         }
16492         if(this.cls){
16493             el.addClass(this.cls);
16494         }
16495         // generic focus element
16496         this.focusEl = el.createChild({
16497             tag: "a", cls: "x-menu-focus", href: "#", onclick: "return false;", tabIndex:"-1"
16498         });
16499         var ul = el.createChild({tag: "ul", cls: "x-menu-list"});
16500         //disabling touch- as it's causing issues ..
16501         //ul.on(Roo.isTouch ? 'touchstart' : 'click'   , this.onClick, this);
16502         ul.on('click'   , this.onClick, this);
16503         
16504         
16505         ul.on("mouseover", this.onMouseOver, this);
16506         ul.on("mouseout", this.onMouseOut, this);
16507         this.items.each(function(item){
16508             if (item.hidden) {
16509                 return;
16510             }
16511             
16512             var li = document.createElement("li");
16513             li.className = "x-menu-list-item";
16514             ul.dom.appendChild(li);
16515             item.render(li, this);
16516         }, this);
16517         this.ul = ul;
16518         this.autoWidth();
16519     },
16520
16521     // private
16522     autoWidth : function(){
16523         var el = this.el, ul = this.ul;
16524         if(!el){
16525             return;
16526         }
16527         var w = this.width;
16528         if(w){
16529             el.setWidth(w);
16530         }else if(Roo.isIE){
16531             el.setWidth(this.minWidth);
16532             var t = el.dom.offsetWidth; // force recalc
16533             el.setWidth(ul.getWidth()+el.getFrameWidth("lr"));
16534         }
16535     },
16536
16537     // private
16538     delayAutoWidth : function(){
16539         if(this.rendered){
16540             if(!this.awTask){
16541                 this.awTask = new Roo.util.DelayedTask(this.autoWidth, this);
16542             }
16543             this.awTask.delay(20);
16544         }
16545     },
16546
16547     // private
16548     findTargetItem : function(e){
16549         var t = e.getTarget(".x-menu-list-item", this.ul,  true);
16550         if(t && t.menuItemId){
16551             return this.items.get(t.menuItemId);
16552         }
16553     },
16554
16555     // private
16556     onClick : function(e){
16557         Roo.log("menu.onClick");
16558         var t = this.findTargetItem(e);
16559         if(!t){
16560             return;
16561         }
16562         Roo.log(e);
16563         if (Roo.isTouch && e.type == 'touchstart' && t.menu  && !t.disabled) {
16564             if(t == this.activeItem && t.shouldDeactivate(e)){
16565                 this.activeItem.deactivate();
16566                 delete this.activeItem;
16567                 return;
16568             }
16569             if(t.canActivate){
16570                 this.setActiveItem(t, true);
16571             }
16572             return;
16573             
16574             
16575         }
16576         
16577         t.onClick(e);
16578         this.fireEvent("click", this, t, e);
16579     },
16580
16581     // private
16582     setActiveItem : function(item, autoExpand){
16583         if(item != this.activeItem){
16584             if(this.activeItem){
16585                 this.activeItem.deactivate();
16586             }
16587             this.activeItem = item;
16588             item.activate(autoExpand);
16589         }else if(autoExpand){
16590             item.expandMenu();
16591         }
16592     },
16593
16594     // private
16595     tryActivate : function(start, step){
16596         var items = this.items;
16597         for(var i = start, len = items.length; i >= 0 && i < len; i+= step){
16598             var item = items.get(i);
16599             if(!item.disabled && item.canActivate){
16600                 this.setActiveItem(item, false);
16601                 return item;
16602             }
16603         }
16604         return false;
16605     },
16606
16607     // private
16608     onMouseOver : function(e){
16609         var t;
16610         if(t = this.findTargetItem(e)){
16611             if(t.canActivate && !t.disabled){
16612                 this.setActiveItem(t, true);
16613             }
16614         }
16615         this.fireEvent("mouseover", this, e, t);
16616     },
16617
16618     // private
16619     onMouseOut : function(e){
16620         var t;
16621         if(t = this.findTargetItem(e)){
16622             if(t == this.activeItem && t.shouldDeactivate(e)){
16623                 this.activeItem.deactivate();
16624                 delete this.activeItem;
16625             }
16626         }
16627         this.fireEvent("mouseout", this, e, t);
16628     },
16629
16630     /**
16631      * Read-only.  Returns true if the menu is currently displayed, else false.
16632      * @type Boolean
16633      */
16634     isVisible : function(){
16635         return this.el && !this.hidden;
16636     },
16637
16638     /**
16639      * Displays this menu relative to another element
16640      * @param {String/HTMLElement/Roo.Element} element The element to align to
16641      * @param {String} position (optional) The {@link Roo.Element#alignTo} anchor position to use in aligning to
16642      * the element (defaults to this.defaultAlign)
16643      * @param {Roo.menu.Menu} parentMenu (optional) This menu's parent menu, if applicable (defaults to undefined)
16644      */
16645     show : function(el, pos, parentMenu){
16646         this.parentMenu = parentMenu;
16647         if(!this.el){
16648             this.render();
16649         }
16650         this.fireEvent("beforeshow", this);
16651         this.showAt(this.el.getAlignToXY(el, pos || this.defaultAlign), parentMenu, false);
16652     },
16653
16654     /**
16655      * Displays this menu at a specific xy position
16656      * @param {Array} xyPosition Contains X & Y [x, y] values for the position at which to show the menu (coordinates are page-based)
16657      * @param {Roo.menu.Menu} parentMenu (optional) This menu's parent menu, if applicable (defaults to undefined)
16658      */
16659     showAt : function(xy, parentMenu, /* private: */_e){
16660         this.parentMenu = parentMenu;
16661         if(!this.el){
16662             this.render();
16663         }
16664         if(_e !== false){
16665             this.fireEvent("beforeshow", this);
16666             xy = this.el.adjustForConstraints(xy);
16667         }
16668         this.el.setXY(xy);
16669         this.el.show();
16670         this.hidden = false;
16671         this.focus();
16672         this.fireEvent("show", this);
16673     },
16674
16675     focus : function(){
16676         if(!this.hidden){
16677             this.doFocus.defer(50, this);
16678         }
16679     },
16680
16681     doFocus : function(){
16682         if(!this.hidden){
16683             this.focusEl.focus();
16684         }
16685     },
16686
16687     /**
16688      * Hides this menu and optionally all parent menus
16689      * @param {Boolean} deep (optional) True to hide all parent menus recursively, if any (defaults to false)
16690      */
16691     hide : function(deep){
16692         if(this.el && this.isVisible()){
16693             this.fireEvent("beforehide", this);
16694             if(this.activeItem){
16695                 this.activeItem.deactivate();
16696                 this.activeItem = null;
16697             }
16698             this.el.hide();
16699             this.hidden = true;
16700             this.fireEvent("hide", this);
16701         }
16702         if(deep === true && this.parentMenu){
16703             this.parentMenu.hide(true);
16704         }
16705     },
16706
16707     /**
16708      * Addds one or more items of any type supported by the Menu class, or that can be converted into menu items.
16709      * Any of the following are valid:
16710      * <ul>
16711      * <li>Any menu item object based on {@link Roo.menu.Item}</li>
16712      * <li>An HTMLElement object which will be converted to a menu item</li>
16713      * <li>A menu item config object that will be created as a new menu item</li>
16714      * <li>A string, which can either be '-' or 'separator' to add a menu separator, otherwise
16715      * it will be converted into a {@link Roo.menu.TextItem} and added</li>
16716      * </ul>
16717      * Usage:
16718      * <pre><code>
16719 // Create the menu
16720 var menu = new Roo.menu.Menu();
16721
16722 // Create a menu item to add by reference
16723 var menuItem = new Roo.menu.Item({ text: 'New Item!' });
16724
16725 // Add a bunch of items at once using different methods.
16726 // Only the last item added will be returned.
16727 var item = menu.add(
16728     menuItem,                // add existing item by ref
16729     'Dynamic Item',          // new TextItem
16730     '-',                     // new separator
16731     { text: 'Config Item' }  // new item by config
16732 );
16733 </code></pre>
16734      * @param {Mixed} args One or more menu items, menu item configs or other objects that can be converted to menu items
16735      * @return {Roo.menu.Item} The menu item that was added, or the last one if multiple items were added
16736      */
16737     add : function(){
16738         var a = arguments, l = a.length, item;
16739         for(var i = 0; i < l; i++){
16740             var el = a[i];
16741             if ((typeof(el) == "object") && el.xtype && el.xns) {
16742                 el = Roo.factory(el, Roo.menu);
16743             }
16744             
16745             if(el.render){ // some kind of Item
16746                 item = this.addItem(el);
16747             }else if(typeof el == "string"){ // string
16748                 if(el == "separator" || el == "-"){
16749                     item = this.addSeparator();
16750                 }else{
16751                     item = this.addText(el);
16752                 }
16753             }else if(el.tagName || el.el){ // element
16754                 item = this.addElement(el);
16755             }else if(typeof el == "object"){ // must be menu item config?
16756                 item = this.addMenuItem(el);
16757             }
16758         }
16759         return item;
16760     },
16761
16762     /**
16763      * Returns this menu's underlying {@link Roo.Element} object
16764      * @return {Roo.Element} The element
16765      */
16766     getEl : function(){
16767         if(!this.el){
16768             this.render();
16769         }
16770         return this.el;
16771     },
16772
16773     /**
16774      * Adds a separator bar to the menu
16775      * @return {Roo.menu.Item} The menu item that was added
16776      */
16777     addSeparator : function(){
16778         return this.addItem(new Roo.menu.Separator());
16779     },
16780
16781     /**
16782      * Adds an {@link Roo.Element} object to the menu
16783      * @param {String/HTMLElement/Roo.Element} el The element or DOM node to add, or its id
16784      * @return {Roo.menu.Item} The menu item that was added
16785      */
16786     addElement : function(el){
16787         return this.addItem(new Roo.menu.BaseItem(el));
16788     },
16789
16790     /**
16791      * Adds an existing object based on {@link Roo.menu.Item} to the menu
16792      * @param {Roo.menu.Item} item The menu item to add
16793      * @return {Roo.menu.Item} The menu item that was added
16794      */
16795     addItem : function(item){
16796         this.items.add(item);
16797         if(this.ul){
16798             var li = document.createElement("li");
16799             li.className = "x-menu-list-item";
16800             this.ul.dom.appendChild(li);
16801             item.render(li, this);
16802             this.delayAutoWidth();
16803         }
16804         return item;
16805     },
16806
16807     /**
16808      * Creates a new {@link Roo.menu.Item} based an the supplied config object and adds it to the menu
16809      * @param {Object} config A MenuItem config object
16810      * @return {Roo.menu.Item} The menu item that was added
16811      */
16812     addMenuItem : function(config){
16813         if(!(config instanceof Roo.menu.Item)){
16814             if(typeof config.checked == "boolean"){ // must be check menu item config?
16815                 config = new Roo.menu.CheckItem(config);
16816             }else{
16817                 config = new Roo.menu.Item(config);
16818             }
16819         }
16820         return this.addItem(config);
16821     },
16822
16823     /**
16824      * Creates a new {@link Roo.menu.TextItem} with the supplied text and adds it to the menu
16825      * @param {String} text The text to display in the menu item
16826      * @return {Roo.menu.Item} The menu item that was added
16827      */
16828     addText : function(text){
16829         return this.addItem(new Roo.menu.TextItem({ text : text }));
16830     },
16831
16832     /**
16833      * Inserts an existing object based on {@link Roo.menu.Item} to the menu at a specified index
16834      * @param {Number} index The index in the menu's list of current items where the new item should be inserted
16835      * @param {Roo.menu.Item} item The menu item to add
16836      * @return {Roo.menu.Item} The menu item that was added
16837      */
16838     insert : function(index, item){
16839         this.items.insert(index, item);
16840         if(this.ul){
16841             var li = document.createElement("li");
16842             li.className = "x-menu-list-item";
16843             this.ul.dom.insertBefore(li, this.ul.dom.childNodes[index]);
16844             item.render(li, this);
16845             this.delayAutoWidth();
16846         }
16847         return item;
16848     },
16849
16850     /**
16851      * Removes an {@link Roo.menu.Item} from the menu and destroys the object
16852      * @param {Roo.menu.Item} item The menu item to remove
16853      */
16854     remove : function(item){
16855         this.items.removeKey(item.id);
16856         item.destroy();
16857     },
16858
16859     /**
16860      * Removes and destroys all items in the menu
16861      */
16862     removeAll : function(){
16863         var f;
16864         while(f = this.items.first()){
16865             this.remove(f);
16866         }
16867     }
16868 });
16869
16870 // MenuNav is a private utility class used internally by the Menu
16871 Roo.menu.MenuNav = function(menu){
16872     Roo.menu.MenuNav.superclass.constructor.call(this, menu.el);
16873     this.scope = this.menu = menu;
16874 };
16875
16876 Roo.extend(Roo.menu.MenuNav, Roo.KeyNav, {
16877     doRelay : function(e, h){
16878         var k = e.getKey();
16879         if(!this.menu.activeItem && e.isNavKeyPress() && k != e.SPACE && k != e.RETURN){
16880             this.menu.tryActivate(0, 1);
16881             return false;
16882         }
16883         return h.call(this.scope || this, e, this.menu);
16884     },
16885
16886     up : function(e, m){
16887         if(!m.tryActivate(m.items.indexOf(m.activeItem)-1, -1)){
16888             m.tryActivate(m.items.length-1, -1);
16889         }
16890     },
16891
16892     down : function(e, m){
16893         if(!m.tryActivate(m.items.indexOf(m.activeItem)+1, 1)){
16894             m.tryActivate(0, 1);
16895         }
16896     },
16897
16898     right : function(e, m){
16899         if(m.activeItem){
16900             m.activeItem.expandMenu(true);
16901         }
16902     },
16903
16904     left : function(e, m){
16905         m.hide();
16906         if(m.parentMenu && m.parentMenu.activeItem){
16907             m.parentMenu.activeItem.activate();
16908         }
16909     },
16910
16911     enter : function(e, m){
16912         if(m.activeItem){
16913             e.stopPropagation();
16914             m.activeItem.onClick(e);
16915             m.fireEvent("click", this, m.activeItem);
16916             return true;
16917         }
16918     }
16919 });/*
16920  * Based on:
16921  * Ext JS Library 1.1.1
16922  * Copyright(c) 2006-2007, Ext JS, LLC.
16923  *
16924  * Originally Released Under LGPL - original licence link has changed is not relivant.
16925  *
16926  * Fork - LGPL
16927  * <script type="text/javascript">
16928  */
16929  
16930 /**
16931  * @class Roo.menu.MenuMgr
16932  * Provides a common registry of all menu items on a page so that they can be easily accessed by id.
16933  * @static
16934  */
16935 Roo.menu.MenuMgr = function(){
16936    var menus, active, groups = {}, attached = false, lastShow = new Date();
16937
16938    // private - called when first menu is created
16939    function init(){
16940        menus = {};
16941        active = new Roo.util.MixedCollection();
16942        Roo.get(document).addKeyListener(27, function(){
16943            if(active.length > 0){
16944                hideAll();
16945            }
16946        });
16947    }
16948
16949    // private
16950    function hideAll(){
16951        if(active && active.length > 0){
16952            var c = active.clone();
16953            c.each(function(m){
16954                m.hide();
16955            });
16956        }
16957    }
16958
16959    // private
16960    function onHide(m){
16961        active.remove(m);
16962        if(active.length < 1){
16963            Roo.get(document).un("mousedown", onMouseDown);
16964            attached = false;
16965        }
16966    }
16967
16968    // private
16969    function onShow(m){
16970        var last = active.last();
16971        lastShow = new Date();
16972        active.add(m);
16973        if(!attached){
16974            Roo.get(document).on("mousedown", onMouseDown);
16975            attached = true;
16976        }
16977        if(m.parentMenu){
16978           m.getEl().setZIndex(parseInt(m.parentMenu.getEl().getStyle("z-index"), 10) + 3);
16979           m.parentMenu.activeChild = m;
16980        }else if(last && last.isVisible()){
16981           m.getEl().setZIndex(parseInt(last.getEl().getStyle("z-index"), 10) + 3);
16982        }
16983    }
16984
16985    // private
16986    function onBeforeHide(m){
16987        if(m.activeChild){
16988            m.activeChild.hide();
16989        }
16990        if(m.autoHideTimer){
16991            clearTimeout(m.autoHideTimer);
16992            delete m.autoHideTimer;
16993        }
16994    }
16995
16996    // private
16997    function onBeforeShow(m){
16998        var pm = m.parentMenu;
16999        if(!pm && !m.allowOtherMenus){
17000            hideAll();
17001        }else if(pm && pm.activeChild && active != m){
17002            pm.activeChild.hide();
17003        }
17004    }
17005
17006    // private
17007    function onMouseDown(e){
17008        if(lastShow.getElapsed() > 50 && active.length > 0 && !e.getTarget(".x-menu")){
17009            hideAll();
17010        }
17011    }
17012
17013    // private
17014    function onBeforeCheck(mi, state){
17015        if(state){
17016            var g = groups[mi.group];
17017            for(var i = 0, l = g.length; i < l; i++){
17018                if(g[i] != mi){
17019                    g[i].setChecked(false);
17020                }
17021            }
17022        }
17023    }
17024
17025    return {
17026
17027        /**
17028         * Hides all menus that are currently visible
17029         */
17030        hideAll : function(){
17031             hideAll();  
17032        },
17033
17034        // private
17035        register : function(menu){
17036            if(!menus){
17037                init();
17038            }
17039            menus[menu.id] = menu;
17040            menu.on("beforehide", onBeforeHide);
17041            menu.on("hide", onHide);
17042            menu.on("beforeshow", onBeforeShow);
17043            menu.on("show", onShow);
17044            var g = menu.group;
17045            if(g && menu.events["checkchange"]){
17046                if(!groups[g]){
17047                    groups[g] = [];
17048                }
17049                groups[g].push(menu);
17050                menu.on("checkchange", onCheck);
17051            }
17052        },
17053
17054         /**
17055          * Returns a {@link Roo.menu.Menu} object
17056          * @param {String/Object} menu The string menu id, an existing menu object reference, or a Menu config that will
17057          * be used to generate and return a new Menu instance.
17058          */
17059        get : function(menu){
17060            if(typeof menu == "string"){ // menu id
17061                return menus[menu];
17062            }else if(menu.events){  // menu instance
17063                return menu;
17064            }else if(typeof menu.length == 'number'){ // array of menu items?
17065                return new Roo.menu.Menu({items:menu});
17066            }else{ // otherwise, must be a config
17067                return new Roo.menu.Menu(menu);
17068            }
17069        },
17070
17071        // private
17072        unregister : function(menu){
17073            delete menus[menu.id];
17074            menu.un("beforehide", onBeforeHide);
17075            menu.un("hide", onHide);
17076            menu.un("beforeshow", onBeforeShow);
17077            menu.un("show", onShow);
17078            var g = menu.group;
17079            if(g && menu.events["checkchange"]){
17080                groups[g].remove(menu);
17081                menu.un("checkchange", onCheck);
17082            }
17083        },
17084
17085        // private
17086        registerCheckable : function(menuItem){
17087            var g = menuItem.group;
17088            if(g){
17089                if(!groups[g]){
17090                    groups[g] = [];
17091                }
17092                groups[g].push(menuItem);
17093                menuItem.on("beforecheckchange", onBeforeCheck);
17094            }
17095        },
17096
17097        // private
17098        unregisterCheckable : function(menuItem){
17099            var g = menuItem.group;
17100            if(g){
17101                groups[g].remove(menuItem);
17102                menuItem.un("beforecheckchange", onBeforeCheck);
17103            }
17104        }
17105    };
17106 }();/*
17107  * Based on:
17108  * Ext JS Library 1.1.1
17109  * Copyright(c) 2006-2007, Ext JS, LLC.
17110  *
17111  * Originally Released Under LGPL - original licence link has changed is not relivant.
17112  *
17113  * Fork - LGPL
17114  * <script type="text/javascript">
17115  */
17116  
17117
17118 /**
17119  * @class Roo.menu.BaseItem
17120  * @extends Roo.Component
17121  * @abstract
17122  * The base class for all items that render into menus.  BaseItem provides default rendering, activated state
17123  * management and base configuration options shared by all menu components.
17124  * @constructor
17125  * Creates a new BaseItem
17126  * @param {Object} config Configuration options
17127  */
17128 Roo.menu.BaseItem = function(config){
17129     Roo.menu.BaseItem.superclass.constructor.call(this, config);
17130
17131     this.addEvents({
17132         /**
17133          * @event click
17134          * Fires when this item is clicked
17135          * @param {Roo.menu.BaseItem} this
17136          * @param {Roo.EventObject} e
17137          */
17138         click: true,
17139         /**
17140          * @event activate
17141          * Fires when this item is activated
17142          * @param {Roo.menu.BaseItem} this
17143          */
17144         activate : true,
17145         /**
17146          * @event deactivate
17147          * Fires when this item is deactivated
17148          * @param {Roo.menu.BaseItem} this
17149          */
17150         deactivate : true
17151     });
17152
17153     if(this.handler){
17154         this.on("click", this.handler, this.scope, true);
17155     }
17156 };
17157
17158 Roo.extend(Roo.menu.BaseItem, Roo.Component, {
17159     /**
17160      * @cfg {Function} handler
17161      * A function that will handle the click event of this menu item (defaults to undefined)
17162      */
17163     /**
17164      * @cfg {Boolean} canActivate True if this item can be visually activated (defaults to false)
17165      */
17166     canActivate : false,
17167     
17168      /**
17169      * @cfg {Boolean} hidden True to prevent creation of this menu item (defaults to false)
17170      */
17171     hidden: false,
17172     
17173     /**
17174      * @cfg {String} activeClass The CSS class to use when the item becomes activated (defaults to "x-menu-item-active")
17175      */
17176     activeClass : "x-menu-item-active",
17177     /**
17178      * @cfg {Boolean} hideOnClick True to hide the containing menu after this item is clicked (defaults to true)
17179      */
17180     hideOnClick : true,
17181     /**
17182      * @cfg {Number} hideDelay Length of time in milliseconds to wait before hiding after a click (defaults to 100)
17183      */
17184     hideDelay : 100,
17185
17186     // private
17187     ctype: "Roo.menu.BaseItem",
17188
17189     // private
17190     actionMode : "container",
17191
17192     // private
17193     render : function(container, parentMenu){
17194         this.parentMenu = parentMenu;
17195         Roo.menu.BaseItem.superclass.render.call(this, container);
17196         this.container.menuItemId = this.id;
17197     },
17198
17199     // private
17200     onRender : function(container, position){
17201         this.el = Roo.get(this.el);
17202         container.dom.appendChild(this.el.dom);
17203     },
17204
17205     // private
17206     onClick : function(e){
17207         if(!this.disabled && this.fireEvent("click", this, e) !== false
17208                 && this.parentMenu.fireEvent("itemclick", this, e) !== false){
17209             this.handleClick(e);
17210         }else{
17211             e.stopEvent();
17212         }
17213     },
17214
17215     // private
17216     activate : function(){
17217         if(this.disabled){
17218             return false;
17219         }
17220         var li = this.container;
17221         li.addClass(this.activeClass);
17222         this.region = li.getRegion().adjust(2, 2, -2, -2);
17223         this.fireEvent("activate", this);
17224         return true;
17225     },
17226
17227     // private
17228     deactivate : function(){
17229         this.container.removeClass(this.activeClass);
17230         this.fireEvent("deactivate", this);
17231     },
17232
17233     // private
17234     shouldDeactivate : function(e){
17235         return !this.region || !this.region.contains(e.getPoint());
17236     },
17237
17238     // private
17239     handleClick : function(e){
17240         if(this.hideOnClick){
17241             this.parentMenu.hide.defer(this.hideDelay, this.parentMenu, [true]);
17242         }
17243     },
17244
17245     // private
17246     expandMenu : function(autoActivate){
17247         // do nothing
17248     },
17249
17250     // private
17251     hideMenu : function(){
17252         // do nothing
17253     }
17254 });/*
17255  * Based on:
17256  * Ext JS Library 1.1.1
17257  * Copyright(c) 2006-2007, Ext JS, LLC.
17258  *
17259  * Originally Released Under LGPL - original licence link has changed is not relivant.
17260  *
17261  * Fork - LGPL
17262  * <script type="text/javascript">
17263  */
17264  
17265 /**
17266  * @class Roo.menu.Adapter
17267  * @extends Roo.menu.BaseItem
17268  * @abstract
17269  * 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.
17270  * It provides basic rendering, activation management and enable/disable logic required to work in menus.
17271  * @constructor
17272  * Creates a new Adapter
17273  * @param {Object} config Configuration options
17274  */
17275 Roo.menu.Adapter = function(component, config){
17276     Roo.menu.Adapter.superclass.constructor.call(this, config);
17277     this.component = component;
17278 };
17279 Roo.extend(Roo.menu.Adapter, Roo.menu.BaseItem, {
17280     // private
17281     canActivate : true,
17282
17283     // private
17284     onRender : function(container, position){
17285         this.component.render(container);
17286         this.el = this.component.getEl();
17287     },
17288
17289     // private
17290     activate : function(){
17291         if(this.disabled){
17292             return false;
17293         }
17294         this.component.focus();
17295         this.fireEvent("activate", this);
17296         return true;
17297     },
17298
17299     // private
17300     deactivate : function(){
17301         this.fireEvent("deactivate", this);
17302     },
17303
17304     // private
17305     disable : function(){
17306         this.component.disable();
17307         Roo.menu.Adapter.superclass.disable.call(this);
17308     },
17309
17310     // private
17311     enable : function(){
17312         this.component.enable();
17313         Roo.menu.Adapter.superclass.enable.call(this);
17314     }
17315 });/*
17316  * Based on:
17317  * Ext JS Library 1.1.1
17318  * Copyright(c) 2006-2007, Ext JS, LLC.
17319  *
17320  * Originally Released Under LGPL - original licence link has changed is not relivant.
17321  *
17322  * Fork - LGPL
17323  * <script type="text/javascript">
17324  */
17325
17326 /**
17327  * @class Roo.menu.TextItem
17328  * @extends Roo.menu.BaseItem
17329  * Adds a static text string to a menu, usually used as either a heading or group separator.
17330  * Note: old style constructor with text is still supported.
17331  * 
17332  * @constructor
17333  * Creates a new TextItem
17334  * @param {Object} cfg Configuration
17335  */
17336 Roo.menu.TextItem = function(cfg){
17337     if (typeof(cfg) == 'string') {
17338         this.text = cfg;
17339     } else {
17340         Roo.apply(this,cfg);
17341     }
17342     
17343     Roo.menu.TextItem.superclass.constructor.call(this);
17344 };
17345
17346 Roo.extend(Roo.menu.TextItem, Roo.menu.BaseItem, {
17347     /**
17348      * @cfg {String} text Text to show on item.
17349      */
17350     text : '',
17351     
17352     /**
17353      * @cfg {Boolean} hideOnClick True to hide the containing menu after this item is clicked (defaults to false)
17354      */
17355     hideOnClick : false,
17356     /**
17357      * @cfg {String} itemCls The default CSS class to use for text items (defaults to "x-menu-text")
17358      */
17359     itemCls : "x-menu-text",
17360
17361     // private
17362     onRender : function(){
17363         var s = document.createElement("span");
17364         s.className = this.itemCls;
17365         s.innerHTML = this.text;
17366         this.el = s;
17367         Roo.menu.TextItem.superclass.onRender.apply(this, arguments);
17368     }
17369 });/*
17370  * Based on:
17371  * Ext JS Library 1.1.1
17372  * Copyright(c) 2006-2007, Ext JS, LLC.
17373  *
17374  * Originally Released Under LGPL - original licence link has changed is not relivant.
17375  *
17376  * Fork - LGPL
17377  * <script type="text/javascript">
17378  */
17379
17380 /**
17381  * @class Roo.menu.Separator
17382  * @extends Roo.menu.BaseItem
17383  * Adds a separator bar to a menu, used to divide logical groups of menu items. Generally you will
17384  * add one of these by using "-" in you call to add() or in your items config rather than creating one directly.
17385  * @constructor
17386  * @param {Object} config Configuration options
17387  */
17388 Roo.menu.Separator = function(config){
17389     Roo.menu.Separator.superclass.constructor.call(this, config);
17390 };
17391
17392 Roo.extend(Roo.menu.Separator, Roo.menu.BaseItem, {
17393     /**
17394      * @cfg {String} itemCls The default CSS class to use for separators (defaults to "x-menu-sep")
17395      */
17396     itemCls : "x-menu-sep",
17397     /**
17398      * @cfg {Boolean} hideOnClick True to hide the containing menu after this item is clicked (defaults to false)
17399      */
17400     hideOnClick : false,
17401
17402     // private
17403     onRender : function(li){
17404         var s = document.createElement("span");
17405         s.className = this.itemCls;
17406         s.innerHTML = "&#160;";
17407         this.el = s;
17408         li.addClass("x-menu-sep-li");
17409         Roo.menu.Separator.superclass.onRender.apply(this, arguments);
17410     }
17411 });/*
17412  * Based on:
17413  * Ext JS Library 1.1.1
17414  * Copyright(c) 2006-2007, Ext JS, LLC.
17415  *
17416  * Originally Released Under LGPL - original licence link has changed is not relivant.
17417  *
17418  * Fork - LGPL
17419  * <script type="text/javascript">
17420  */
17421 /**
17422  * @class Roo.menu.Item
17423  * @extends Roo.menu.BaseItem
17424  * A base class for all menu items that require menu-related functionality (like sub-menus) and are not static
17425  * display items.  Item extends the base functionality of {@link Roo.menu.BaseItem} by adding menu-specific
17426  * activation and click handling.
17427  * @constructor
17428  * Creates a new Item
17429  * @param {Object} config Configuration options
17430  */
17431 Roo.menu.Item = function(config){
17432     Roo.menu.Item.superclass.constructor.call(this, config);
17433     if(this.menu){
17434         this.menu = Roo.menu.MenuMgr.get(this.menu);
17435     }
17436 };
17437 Roo.extend(Roo.menu.Item, Roo.menu.BaseItem, {
17438     /**
17439      * @cfg {Roo.menu.Menu} menu
17440      * A Sub menu
17441      */
17442     /**
17443      * @cfg {String} text
17444      * The text to show on the menu item.
17445      */
17446     text: '',
17447      /**
17448      * @cfg {String} html to render in menu
17449      * The text to show on the menu item (HTML version).
17450      */
17451     html: '',
17452     /**
17453      * @cfg {String} icon
17454      * The path to an icon to display in this menu item (defaults to Roo.BLANK_IMAGE_URL)
17455      */
17456     icon: undefined,
17457     /**
17458      * @cfg {String} itemCls The default CSS class to use for menu items (defaults to "x-menu-item")
17459      */
17460     itemCls : "x-menu-item",
17461     /**
17462      * @cfg {Boolean} canActivate True if this item can be visually activated (defaults to true)
17463      */
17464     canActivate : true,
17465     /**
17466      * @cfg {Number} showDelay Length of time in milliseconds to wait before showing this item (defaults to 200)
17467      */
17468     showDelay: 200,
17469     // doc'd in BaseItem
17470     hideDelay: 200,
17471
17472     // private
17473     ctype: "Roo.menu.Item",
17474     
17475     // private
17476     onRender : function(container, position){
17477         var el = document.createElement("a");
17478         el.hideFocus = true;
17479         el.unselectable = "on";
17480         el.href = this.href || "#";
17481         if(this.hrefTarget){
17482             el.target = this.hrefTarget;
17483         }
17484         el.className = this.itemCls + (this.menu ?  " x-menu-item-arrow" : "") + (this.cls ?  " " + this.cls : "");
17485         
17486         var html = this.html.length ? this.html  : String.format('{0}',this.text);
17487         
17488         el.innerHTML = String.format(
17489                 '<img src="{0}" class="x-menu-item-icon {1}" />' + html,
17490                 this.icon || Roo.BLANK_IMAGE_URL, this.iconCls || '');
17491         this.el = el;
17492         Roo.menu.Item.superclass.onRender.call(this, container, position);
17493     },
17494
17495     /**
17496      * Sets the text to display in this menu item
17497      * @param {String} text The text to display
17498      * @param {Boolean} isHTML true to indicate text is pure html.
17499      */
17500     setText : function(text, isHTML){
17501         if (isHTML) {
17502             this.html = text;
17503         } else {
17504             this.text = text;
17505             this.html = '';
17506         }
17507         if(this.rendered){
17508             var html = this.html.length ? this.html  : String.format('{0}',this.text);
17509      
17510             this.el.update(String.format(
17511                 '<img src="{0}" class="x-menu-item-icon {2}">' + html,
17512                 this.icon || Roo.BLANK_IMAGE_URL, this.text, this.iconCls || ''));
17513             this.parentMenu.autoWidth();
17514         }
17515     },
17516
17517     // private
17518     handleClick : function(e){
17519         if(!this.href){ // if no link defined, stop the event automatically
17520             e.stopEvent();
17521         }
17522         Roo.menu.Item.superclass.handleClick.apply(this, arguments);
17523     },
17524
17525     // private
17526     activate : function(autoExpand){
17527         if(Roo.menu.Item.superclass.activate.apply(this, arguments)){
17528             this.focus();
17529             if(autoExpand){
17530                 this.expandMenu();
17531             }
17532         }
17533         return true;
17534     },
17535
17536     // private
17537     shouldDeactivate : function(e){
17538         if(Roo.menu.Item.superclass.shouldDeactivate.call(this, e)){
17539             if(this.menu && this.menu.isVisible()){
17540                 return !this.menu.getEl().getRegion().contains(e.getPoint());
17541             }
17542             return true;
17543         }
17544         return false;
17545     },
17546
17547     // private
17548     deactivate : function(){
17549         Roo.menu.Item.superclass.deactivate.apply(this, arguments);
17550         this.hideMenu();
17551     },
17552
17553     // private
17554     expandMenu : function(autoActivate){
17555         if(!this.disabled && this.menu){
17556             clearTimeout(this.hideTimer);
17557             delete this.hideTimer;
17558             if(!this.menu.isVisible() && !this.showTimer){
17559                 this.showTimer = this.deferExpand.defer(this.showDelay, this, [autoActivate]);
17560             }else if (this.menu.isVisible() && autoActivate){
17561                 this.menu.tryActivate(0, 1);
17562             }
17563         }
17564     },
17565
17566     // private
17567     deferExpand : function(autoActivate){
17568         delete this.showTimer;
17569         this.menu.show(this.container, this.parentMenu.subMenuAlign || "tl-tr?", this.parentMenu);
17570         if(autoActivate){
17571             this.menu.tryActivate(0, 1);
17572         }
17573     },
17574
17575     // private
17576     hideMenu : function(){
17577         clearTimeout(this.showTimer);
17578         delete this.showTimer;
17579         if(!this.hideTimer && this.menu && this.menu.isVisible()){
17580             this.hideTimer = this.deferHide.defer(this.hideDelay, this);
17581         }
17582     },
17583
17584     // private
17585     deferHide : function(){
17586         delete this.hideTimer;
17587         this.menu.hide();
17588     }
17589 });/*
17590  * Based on:
17591  * Ext JS Library 1.1.1
17592  * Copyright(c) 2006-2007, Ext JS, LLC.
17593  *
17594  * Originally Released Under LGPL - original licence link has changed is not relivant.
17595  *
17596  * Fork - LGPL
17597  * <script type="text/javascript">
17598  */
17599  
17600 /**
17601  * @class Roo.menu.CheckItem
17602  * @extends Roo.menu.Item
17603  * Adds a menu item that contains a checkbox by default, but can also be part of a radio group.
17604  * @constructor
17605  * Creates a new CheckItem
17606  * @param {Object} config Configuration options
17607  */
17608 Roo.menu.CheckItem = function(config){
17609     Roo.menu.CheckItem.superclass.constructor.call(this, config);
17610     this.addEvents({
17611         /**
17612          * @event beforecheckchange
17613          * Fires before the checked value is set, providing an opportunity to cancel if needed
17614          * @param {Roo.menu.CheckItem} this
17615          * @param {Boolean} checked The new checked value that will be set
17616          */
17617         "beforecheckchange" : true,
17618         /**
17619          * @event checkchange
17620          * Fires after the checked value has been set
17621          * @param {Roo.menu.CheckItem} this
17622          * @param {Boolean} checked The checked value that was set
17623          */
17624         "checkchange" : true
17625     });
17626     if(this.checkHandler){
17627         this.on('checkchange', this.checkHandler, this.scope);
17628     }
17629 };
17630 Roo.extend(Roo.menu.CheckItem, Roo.menu.Item, {
17631     /**
17632      * @cfg {String} group
17633      * All check items with the same group name will automatically be grouped into a single-select
17634      * radio button group (defaults to '')
17635      */
17636     /**
17637      * @cfg {String} itemCls The default CSS class to use for check items (defaults to "x-menu-item x-menu-check-item")
17638      */
17639     itemCls : "x-menu-item x-menu-check-item",
17640     /**
17641      * @cfg {String} groupClass The default CSS class to use for radio group check items (defaults to "x-menu-group-item")
17642      */
17643     groupClass : "x-menu-group-item",
17644
17645     /**
17646      * @cfg {Boolean} checked True to initialize this checkbox as checked (defaults to false).  Note that
17647      * if this checkbox is part of a radio group (group = true) only the last item in the group that is
17648      * initialized with checked = true will be rendered as checked.
17649      */
17650     checked: false,
17651
17652     // private
17653     ctype: "Roo.menu.CheckItem",
17654
17655     // private
17656     onRender : function(c){
17657         Roo.menu.CheckItem.superclass.onRender.apply(this, arguments);
17658         if(this.group){
17659             this.el.addClass(this.groupClass);
17660         }
17661         Roo.menu.MenuMgr.registerCheckable(this);
17662         if(this.checked){
17663             this.checked = false;
17664             this.setChecked(true, true);
17665         }
17666     },
17667
17668     // private
17669     destroy : function(){
17670         if(this.rendered){
17671             Roo.menu.MenuMgr.unregisterCheckable(this);
17672         }
17673         Roo.menu.CheckItem.superclass.destroy.apply(this, arguments);
17674     },
17675
17676     /**
17677      * Set the checked state of this item
17678      * @param {Boolean} checked The new checked value
17679      * @param {Boolean} suppressEvent (optional) True to prevent the checkchange event from firing (defaults to false)
17680      */
17681     setChecked : function(state, suppressEvent){
17682         if(this.checked != state && this.fireEvent("beforecheckchange", this, state) !== false){
17683             if(this.container){
17684                 this.container[state ? "addClass" : "removeClass"]("x-menu-item-checked");
17685             }
17686             this.checked = state;
17687             if(suppressEvent !== true){
17688                 this.fireEvent("checkchange", this, state);
17689             }
17690         }
17691     },
17692
17693     // private
17694     handleClick : function(e){
17695        if(!this.disabled && !(this.checked && this.group)){// disable unselect on radio item
17696            this.setChecked(!this.checked);
17697        }
17698        Roo.menu.CheckItem.superclass.handleClick.apply(this, arguments);
17699     }
17700 });/*
17701  * Based on:
17702  * Ext JS Library 1.1.1
17703  * Copyright(c) 2006-2007, Ext JS, LLC.
17704  *
17705  * Originally Released Under LGPL - original licence link has changed is not relivant.
17706  *
17707  * Fork - LGPL
17708  * <script type="text/javascript">
17709  */
17710  
17711 /**
17712  * @class Roo.menu.DateItem
17713  * @extends Roo.menu.Adapter
17714  * A menu item that wraps the {@link Roo.DatPicker} component.
17715  * @constructor
17716  * Creates a new DateItem
17717  * @param {Object} config Configuration options
17718  */
17719 Roo.menu.DateItem = function(config){
17720     Roo.menu.DateItem.superclass.constructor.call(this, new Roo.DatePicker(config), config);
17721     /** The Roo.DatePicker object @type Roo.DatePicker */
17722     this.picker = this.component;
17723     this.addEvents({select: true});
17724     
17725     this.picker.on("render", function(picker){
17726         picker.getEl().swallowEvent("click");
17727         picker.container.addClass("x-menu-date-item");
17728     });
17729
17730     this.picker.on("select", this.onSelect, this);
17731 };
17732
17733 Roo.extend(Roo.menu.DateItem, Roo.menu.Adapter, {
17734     // private
17735     onSelect : function(picker, date){
17736         this.fireEvent("select", this, date, picker);
17737         Roo.menu.DateItem.superclass.handleClick.call(this);
17738     }
17739 });/*
17740  * Based on:
17741  * Ext JS Library 1.1.1
17742  * Copyright(c) 2006-2007, Ext JS, LLC.
17743  *
17744  * Originally Released Under LGPL - original licence link has changed is not relivant.
17745  *
17746  * Fork - LGPL
17747  * <script type="text/javascript">
17748  */
17749  
17750 /**
17751  * @class Roo.menu.ColorItem
17752  * @extends Roo.menu.Adapter
17753  * A menu item that wraps the {@link Roo.ColorPalette} component.
17754  * @constructor
17755  * Creates a new ColorItem
17756  * @param {Object} config Configuration options
17757  */
17758 Roo.menu.ColorItem = function(config){
17759     Roo.menu.ColorItem.superclass.constructor.call(this, new Roo.ColorPalette(config), config);
17760     /** The Roo.ColorPalette object @type Roo.ColorPalette */
17761     this.palette = this.component;
17762     this.relayEvents(this.palette, ["select"]);
17763     if(this.selectHandler){
17764         this.on('select', this.selectHandler, this.scope);
17765     }
17766 };
17767 Roo.extend(Roo.menu.ColorItem, Roo.menu.Adapter);/*
17768  * Based on:
17769  * Ext JS Library 1.1.1
17770  * Copyright(c) 2006-2007, Ext JS, LLC.
17771  *
17772  * Originally Released Under LGPL - original licence link has changed is not relivant.
17773  *
17774  * Fork - LGPL
17775  * <script type="text/javascript">
17776  */
17777  
17778
17779 /**
17780  * @class Roo.menu.DateMenu
17781  * @extends Roo.menu.Menu
17782  * A menu containing a {@link Roo.menu.DateItem} component (which provides a date picker).
17783  * @constructor
17784  * Creates a new DateMenu
17785  * @param {Object} config Configuration options
17786  */
17787 Roo.menu.DateMenu = function(config){
17788     Roo.menu.DateMenu.superclass.constructor.call(this, config);
17789     this.plain = true;
17790     var di = new Roo.menu.DateItem(config);
17791     this.add(di);
17792     /**
17793      * The {@link Roo.DatePicker} instance for this DateMenu
17794      * @type DatePicker
17795      */
17796     this.picker = di.picker;
17797     /**
17798      * @event select
17799      * @param {DatePicker} picker
17800      * @param {Date} date
17801      */
17802     this.relayEvents(di, ["select"]);
17803     this.on('beforeshow', function(){
17804         if(this.picker){
17805             this.picker.hideMonthPicker(false);
17806         }
17807     }, this);
17808 };
17809 Roo.extend(Roo.menu.DateMenu, Roo.menu.Menu, {
17810     cls:'x-date-menu'
17811 });/*
17812  * Based on:
17813  * Ext JS Library 1.1.1
17814  * Copyright(c) 2006-2007, Ext JS, LLC.
17815  *
17816  * Originally Released Under LGPL - original licence link has changed is not relivant.
17817  *
17818  * Fork - LGPL
17819  * <script type="text/javascript">
17820  */
17821  
17822
17823 /**
17824  * @class Roo.menu.ColorMenu
17825  * @extends Roo.menu.Menu
17826  * A menu containing a {@link Roo.menu.ColorItem} component (which provides a basic color picker).
17827  * @constructor
17828  * Creates a new ColorMenu
17829  * @param {Object} config Configuration options
17830  */
17831 Roo.menu.ColorMenu = function(config){
17832     Roo.menu.ColorMenu.superclass.constructor.call(this, config);
17833     this.plain = true;
17834     var ci = new Roo.menu.ColorItem(config);
17835     this.add(ci);
17836     /**
17837      * The {@link Roo.ColorPalette} instance for this ColorMenu
17838      * @type ColorPalette
17839      */
17840     this.palette = ci.palette;
17841     /**
17842      * @event select
17843      * @param {ColorPalette} palette
17844      * @param {String} color
17845      */
17846     this.relayEvents(ci, ["select"]);
17847 };
17848 Roo.extend(Roo.menu.ColorMenu, Roo.menu.Menu);/*
17849  * Based on:
17850  * Ext JS Library 1.1.1
17851  * Copyright(c) 2006-2007, Ext JS, LLC.
17852  *
17853  * Originally Released Under LGPL - original licence link has changed is not relivant.
17854  *
17855  * Fork - LGPL
17856  * <script type="text/javascript">
17857  */
17858  
17859 /**
17860  * @class Roo.form.TextItem
17861  * @extends Roo.BoxComponent
17862  * Base class for form fields that provides default event handling, sizing, value handling and other functionality.
17863  * @constructor
17864  * Creates a new TextItem
17865  * @param {Object} config Configuration options
17866  */
17867 Roo.form.TextItem = function(config){
17868     Roo.form.TextItem.superclass.constructor.call(this, config);
17869 };
17870
17871 Roo.extend(Roo.form.TextItem, Roo.BoxComponent,  {
17872     
17873     /**
17874      * @cfg {String} tag the tag for this item (default div)
17875      */
17876     tag : 'div',
17877     /**
17878      * @cfg {String} html the content for this item
17879      */
17880     html : '',
17881     
17882     getAutoCreate : function()
17883     {
17884         var cfg = {
17885             id: this.id,
17886             tag: this.tag,
17887             html: this.html,
17888             cls: 'x-form-item'
17889         };
17890         
17891         return cfg;
17892         
17893     },
17894     
17895     onRender : function(ct, position)
17896     {
17897         Roo.form.TextItem.superclass.onRender.call(this, ct, position);
17898         
17899         if(!this.el){
17900             var cfg = this.getAutoCreate();
17901             if(!cfg.name){
17902                 cfg.name = typeof(this.name) == 'undefined' ? this.id : this.name;
17903             }
17904             if (!cfg.name.length) {
17905                 delete cfg.name;
17906             }
17907             this.el = ct.createChild(cfg, position);
17908         }
17909     },
17910     /*
17911      * setHTML
17912      * @param {String} html update the Contents of the element.
17913      */
17914     setHTML : function(html)
17915     {
17916         this.fieldEl.dom.innerHTML = html;
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.Field
17932  * @extends Roo.BoxComponent
17933  * Base class for form fields that provides default event handling, sizing, value handling and other functionality.
17934  * @constructor
17935  * Creates a new Field
17936  * @param {Object} config Configuration options
17937  */
17938 Roo.form.Field = function(config){
17939     Roo.form.Field.superclass.constructor.call(this, config);
17940 };
17941
17942 Roo.extend(Roo.form.Field, Roo.BoxComponent,  {
17943     /**
17944      * @cfg {String} fieldLabel Label to use when rendering a form.
17945      */
17946         /**
17947      * @cfg {String} labelSeparator the ':' after a field label (default :)  = set it to empty string to hide the field label.
17948      */
17949        /**
17950      * @cfg {String} qtip Mouse over tip
17951      */
17952      
17953     /**
17954      * @cfg {String} invalidClass The CSS class to use when marking a field invalid (defaults to "x-form-invalid")
17955      */
17956     invalidClass : "x-form-invalid",
17957     /**
17958      * @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")
17959      */
17960     invalidText : "The value in this field is invalid",
17961     /**
17962      * @cfg {String} focusClass The CSS class to use when the field receives focus (defaults to "x-form-focus")
17963      */
17964     focusClass : "x-form-focus",
17965     /**
17966      * @cfg {String/Boolean} validationEvent The event that should initiate field validation. Set to false to disable
17967       automatic validation (defaults to "keyup").
17968      */
17969     validationEvent : "keyup",
17970     /**
17971      * @cfg {Boolean} validateOnBlur Whether the field should validate when it loses focus (defaults to true).
17972      */
17973     validateOnBlur : true,
17974     /**
17975      * @cfg {Number} validationDelay The length of time in milliseconds after user input begins until validation is initiated (defaults to 250)
17976      */
17977     validationDelay : 250,
17978     /**
17979      * @cfg {String/Object} autoCreate A DomHelper element spec, or true for a default element spec (defaults to
17980      * {tag: "input", type: "text", size: "20", autocomplete: "off"})
17981      */
17982     defaultAutoCreate : {tag: "input", type: "text", size: "20", autocomplete: "new-password"},
17983     /**
17984      * @cfg {String} fieldClass The default CSS class for the field (defaults to "x-form-field")
17985      */
17986     fieldClass : "x-form-field",
17987     /**
17988      * @cfg {String} msgTarget The location where error text should display.  Should be one of the following values (defaults to 'qtip'):
17989      *<pre>
17990 Value         Description
17991 -----------   ----------------------------------------------------------------------
17992 qtip          Display a quick tip when the user hovers over the field
17993 title         Display a default browser title attribute popup
17994 under         Add a block div beneath the field containing the error text
17995 side          Add an error icon to the right of the field with a popup on hover
17996 [element id]  Add the error text directly to the innerHTML of the specified element
17997 </pre>
17998      */
17999     msgTarget : 'qtip',
18000     /**
18001      * @cfg {String} msgFx <b>Experimental</b> The effect used when displaying a validation message under the field (defaults to 'normal').
18002      */
18003     msgFx : 'normal',
18004
18005     /**
18006      * @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.
18007      */
18008     readOnly : false,
18009
18010     /**
18011      * @cfg {Boolean} disabled True to disable the field (defaults to false).
18012      */
18013     disabled : false,
18014
18015     /**
18016      * @cfg {String} inputType The type attribute for input fields -- e.g. radio, text, password (defaults to "text").
18017      */
18018     inputType : undefined,
18019     
18020     /**
18021      * @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).
18022          */
18023         tabIndex : undefined,
18024         
18025     // private
18026     isFormField : true,
18027
18028     // private
18029     hasFocus : false,
18030     /**
18031      * @property {Roo.Element} fieldEl
18032      * Element Containing the rendered Field (with label etc.)
18033      */
18034     /**
18035      * @cfg {Mixed} value A value to initialize this field with.
18036      */
18037     value : undefined,
18038
18039     /**
18040      * @cfg {String} name The field's HTML name attribute.
18041      */
18042     /**
18043      * @cfg {String} cls A CSS class to apply to the field's underlying element.
18044      */
18045     // private
18046     loadedValue : false,
18047      
18048      
18049         // private ??
18050         initComponent : function(){
18051         Roo.form.Field.superclass.initComponent.call(this);
18052         this.addEvents({
18053             /**
18054              * @event focus
18055              * Fires when this field receives input focus.
18056              * @param {Roo.form.Field} this
18057              */
18058             focus : true,
18059             /**
18060              * @event blur
18061              * Fires when this field loses input focus.
18062              * @param {Roo.form.Field} this
18063              */
18064             blur : true,
18065             /**
18066              * @event specialkey
18067              * Fires when any key related to navigation (arrows, tab, enter, esc, etc.) is pressed.  You can check
18068              * {@link Roo.EventObject#getKey} to determine which key was pressed.
18069              * @param {Roo.form.Field} this
18070              * @param {Roo.EventObject} e The event object
18071              */
18072             specialkey : true,
18073             /**
18074              * @event change
18075              * Fires just before the field blurs if the field value has changed.
18076              * @param {Roo.form.Field} this
18077              * @param {Mixed} newValue The new value
18078              * @param {Mixed} oldValue The original value
18079              */
18080             change : true,
18081             /**
18082              * @event invalid
18083              * Fires after the field has been marked as invalid.
18084              * @param {Roo.form.Field} this
18085              * @param {String} msg The validation message
18086              */
18087             invalid : true,
18088             /**
18089              * @event valid
18090              * Fires after the field has been validated with no errors.
18091              * @param {Roo.form.Field} this
18092              */
18093             valid : true,
18094              /**
18095              * @event keyup
18096              * Fires after the key up
18097              * @param {Roo.form.Field} this
18098              * @param {Roo.EventObject}  e The event Object
18099              */
18100             keyup : true
18101         });
18102     },
18103
18104     /**
18105      * Returns the name attribute of the field if available
18106      * @return {String} name The field name
18107      */
18108     getName: function(){
18109          return this.rendered && this.el.dom.name ? this.el.dom.name : (this.hiddenName || '');
18110     },
18111
18112     // private
18113     onRender : function(ct, position){
18114         Roo.form.Field.superclass.onRender.call(this, ct, position);
18115         if(!this.el){
18116             var cfg = this.getAutoCreate();
18117             if(!cfg.name){
18118                 cfg.name = typeof(this.name) == 'undefined' ? this.id : this.name;
18119             }
18120             if (!cfg.name.length) {
18121                 delete cfg.name;
18122             }
18123             if(this.inputType){
18124                 cfg.type = this.inputType;
18125             }
18126             this.el = ct.createChild(cfg, position);
18127         }
18128         var type = this.el.dom.type;
18129         if(type){
18130             if(type == 'password'){
18131                 type = 'text';
18132             }
18133             this.el.addClass('x-form-'+type);
18134         }
18135         if(this.readOnly){
18136             this.el.dom.readOnly = true;
18137         }
18138         if(this.tabIndex !== undefined){
18139             this.el.dom.setAttribute('tabIndex', this.tabIndex);
18140         }
18141
18142         this.el.addClass([this.fieldClass, this.cls]);
18143         this.initValue();
18144     },
18145
18146     /**
18147      * Apply the behaviors of this component to an existing element. <b>This is used instead of render().</b>
18148      * @param {String/HTMLElement/Element} el The id of the node, a DOM node or an existing Element
18149      * @return {Roo.form.Field} this
18150      */
18151     applyTo : function(target){
18152         this.allowDomMove = false;
18153         this.el = Roo.get(target);
18154         this.render(this.el.dom.parentNode);
18155         return this;
18156     },
18157
18158     // private
18159     initValue : function(){
18160         if(this.value !== undefined){
18161             this.setValue(this.value);
18162         }else if(this.el.dom.value.length > 0){
18163             this.setValue(this.el.dom.value);
18164         }
18165     },
18166
18167     /**
18168      * Returns true if this field has been changed since it was originally loaded and is not disabled.
18169      * DEPRICATED  - it never worked well - use hasChanged/resetHasChanged.
18170      */
18171     isDirty : function() {
18172         if(this.disabled) {
18173             return false;
18174         }
18175         return String(this.getValue()) !== String(this.originalValue);
18176     },
18177
18178     /**
18179      * stores the current value in loadedValue
18180      */
18181     resetHasChanged : function()
18182     {
18183         this.loadedValue = String(this.getValue());
18184     },
18185     /**
18186      * checks the current value against the 'loaded' value.
18187      * Note - will return false if 'resetHasChanged' has not been called first.
18188      */
18189     hasChanged : function()
18190     {
18191         if(this.disabled || this.readOnly) {
18192             return false;
18193         }
18194         return this.loadedValue !== false && String(this.getValue()) !== this.loadedValue;
18195     },
18196     
18197     
18198     
18199     // private
18200     afterRender : function(){
18201         Roo.form.Field.superclass.afterRender.call(this);
18202         this.initEvents();
18203     },
18204
18205     // private
18206     fireKey : function(e){
18207         //Roo.log('field ' + e.getKey());
18208         if(e.isNavKeyPress()){
18209             this.fireEvent("specialkey", this, e);
18210         }
18211     },
18212
18213     /**
18214      * Resets the current field value to the originally loaded value and clears any validation messages
18215      */
18216     reset : function(){
18217         this.setValue(this.resetValue);
18218         this.originalValue = this.getValue();
18219         this.clearInvalid();
18220     },
18221
18222     // private
18223     initEvents : function(){
18224         // safari killled keypress - so keydown is now used..
18225         this.el.on("keydown" , this.fireKey,  this);
18226         this.el.on("focus", this.onFocus,  this);
18227         this.el.on("blur", this.onBlur,  this);
18228         this.el.relayEvent('keyup', this);
18229
18230         // reference to original value for reset
18231         this.originalValue = this.getValue();
18232         this.resetValue =  this.getValue();
18233     },
18234
18235     // private
18236     onFocus : function(){
18237         if(!Roo.isOpera && this.focusClass){ // don't touch in Opera
18238             this.el.addClass(this.focusClass);
18239         }
18240         if(!this.hasFocus){
18241             this.hasFocus = true;
18242             this.startValue = this.getValue();
18243             this.fireEvent("focus", this);
18244         }
18245     },
18246
18247     beforeBlur : Roo.emptyFn,
18248
18249     // private
18250     onBlur : function(){
18251         this.beforeBlur();
18252         if(!Roo.isOpera && this.focusClass){ // don't touch in Opera
18253             this.el.removeClass(this.focusClass);
18254         }
18255         this.hasFocus = false;
18256         if(this.validationEvent !== false && this.validateOnBlur && this.validationEvent != "blur"){
18257             this.validate();
18258         }
18259         var v = this.getValue();
18260         if(String(v) !== String(this.startValue)){
18261             this.fireEvent('change', this, v, this.startValue);
18262         }
18263         this.fireEvent("blur", this);
18264     },
18265
18266     /**
18267      * Returns whether or not the field value is currently valid
18268      * @param {Boolean} preventMark True to disable marking the field invalid
18269      * @return {Boolean} True if the value is valid, else false
18270      */
18271     isValid : function(preventMark){
18272         if(this.disabled){
18273             return true;
18274         }
18275         var restore = this.preventMark;
18276         this.preventMark = preventMark === true;
18277         var v = this.validateValue(this.processValue(this.getRawValue()));
18278         this.preventMark = restore;
18279         return v;
18280     },
18281
18282     /**
18283      * Validates the field value
18284      * @return {Boolean} True if the value is valid, else false
18285      */
18286     validate : function(){
18287         if(this.disabled || this.validateValue(this.processValue(this.getRawValue()))){
18288             this.clearInvalid();
18289             return true;
18290         }
18291         return false;
18292     },
18293
18294     processValue : function(value){
18295         return value;
18296     },
18297
18298     // private
18299     // Subclasses should provide the validation implementation by overriding this
18300     validateValue : function(value){
18301         return true;
18302     },
18303
18304     /**
18305      * Mark this field as invalid
18306      * @param {String} msg The validation message
18307      */
18308     markInvalid : function(msg){
18309         if(!this.rendered || this.preventMark){ // not rendered
18310             return;
18311         }
18312         
18313         var obj = (typeof(this.combo) != 'undefined') ? this.combo : this; // fix the combox array!!
18314         
18315         obj.el.addClass(this.invalidClass);
18316         msg = msg || this.invalidText;
18317         switch(this.msgTarget){
18318             case 'qtip':
18319                 obj.el.dom.qtip = msg;
18320                 obj.el.dom.qclass = 'x-form-invalid-tip';
18321                 if(Roo.QuickTips){ // fix for floating editors interacting with DND
18322                     Roo.QuickTips.enable();
18323                 }
18324                 break;
18325             case 'title':
18326                 this.el.dom.title = msg;
18327                 break;
18328             case 'under':
18329                 if(!this.errorEl){
18330                     var elp = this.el.findParent('.x-form-element', 5, true);
18331                     this.errorEl = elp.createChild({cls:'x-form-invalid-msg'});
18332                     this.errorEl.setWidth(elp.getWidth(true)-20);
18333                 }
18334                 this.errorEl.update(msg);
18335                 Roo.form.Field.msgFx[this.msgFx].show(this.errorEl, this);
18336                 break;
18337             case 'side':
18338                 if(!this.errorIcon){
18339                     var elp = this.el.findParent('.x-form-element', 5, true);
18340                     this.errorIcon = elp.createChild({cls:'x-form-invalid-icon'});
18341                 }
18342                 this.alignErrorIcon();
18343                 this.errorIcon.dom.qtip = msg;
18344                 this.errorIcon.dom.qclass = 'x-form-invalid-tip';
18345                 this.errorIcon.show();
18346                 this.on('resize', this.alignErrorIcon, this);
18347                 break;
18348             default:
18349                 var t = Roo.getDom(this.msgTarget);
18350                 t.innerHTML = msg;
18351                 t.style.display = this.msgDisplay;
18352                 break;
18353         }
18354         this.fireEvent('invalid', this, msg);
18355     },
18356
18357     // private
18358     alignErrorIcon : function(){
18359         this.errorIcon.alignTo(this.el, 'tl-tr', [2, 0]);
18360     },
18361
18362     /**
18363      * Clear any invalid styles/messages for this field
18364      */
18365     clearInvalid : function(){
18366         if(!this.rendered || this.preventMark){ // not rendered
18367             return;
18368         }
18369         var obj = (typeof(this.combo) != 'undefined') ? this.combo : this; // fix the combox array!!
18370         
18371         obj.el.removeClass(this.invalidClass);
18372         switch(this.msgTarget){
18373             case 'qtip':
18374                 obj.el.dom.qtip = '';
18375                 break;
18376             case 'title':
18377                 this.el.dom.title = '';
18378                 break;
18379             case 'under':
18380                 if(this.errorEl){
18381                     Roo.form.Field.msgFx[this.msgFx].hide(this.errorEl, this);
18382                 }
18383                 break;
18384             case 'side':
18385                 if(this.errorIcon){
18386                     this.errorIcon.dom.qtip = '';
18387                     this.errorIcon.hide();
18388                     this.un('resize', this.alignErrorIcon, this);
18389                 }
18390                 break;
18391             default:
18392                 var t = Roo.getDom(this.msgTarget);
18393                 t.innerHTML = '';
18394                 t.style.display = 'none';
18395                 break;
18396         }
18397         this.fireEvent('valid', this);
18398     },
18399
18400     /**
18401      * Returns the raw data value which may or may not be a valid, defined value.  To return a normalized value see {@link #getValue}.
18402      * @return {Mixed} value The field value
18403      */
18404     getRawValue : function(){
18405         var v = this.el.getValue();
18406         
18407         return v;
18408     },
18409
18410     /**
18411      * Returns the normalized data value (undefined or emptyText will be returned as '').  To return the raw value see {@link #getRawValue}.
18412      * @return {Mixed} value The field value
18413      */
18414     getValue : function(){
18415         var v = this.el.getValue();
18416          
18417         return v;
18418     },
18419
18420     /**
18421      * Sets the underlying DOM field's value directly, bypassing validation.  To set the value with validation see {@link #setValue}.
18422      * @param {Mixed} value The value to set
18423      */
18424     setRawValue : function(v){
18425         return this.el.dom.value = (v === null || v === undefined ? '' : v);
18426     },
18427
18428     /**
18429      * Sets a data value into the field and validates it.  To set the value directly without validation see {@link #setRawValue}.
18430      * @param {Mixed} value The value to set
18431      */
18432     setValue : function(v){
18433         this.value = v;
18434         if(this.rendered){
18435             this.el.dom.value = (v === null || v === undefined ? '' : v);
18436              this.validate();
18437         }
18438     },
18439
18440     adjustSize : function(w, h){
18441         var s = Roo.form.Field.superclass.adjustSize.call(this, w, h);
18442         s.width = this.adjustWidth(this.el.dom.tagName, s.width);
18443         return s;
18444     },
18445
18446     adjustWidth : function(tag, w){
18447         tag = tag.toLowerCase();
18448         if(typeof w == 'number' && Roo.isStrict && !Roo.isSafari){
18449             if(Roo.isIE && (tag == 'input' || tag == 'textarea')){
18450                 if(tag == 'input'){
18451                     return w + 2;
18452                 }
18453                 if(tag == 'textarea'){
18454                     return w-2;
18455                 }
18456             }else if(Roo.isOpera){
18457                 if(tag == 'input'){
18458                     return w + 2;
18459                 }
18460                 if(tag == 'textarea'){
18461                     return w-2;
18462                 }
18463             }
18464         }
18465         return w;
18466     }
18467 });
18468
18469
18470 // anything other than normal should be considered experimental
18471 Roo.form.Field.msgFx = {
18472     normal : {
18473         show: function(msgEl, f){
18474             msgEl.setDisplayed('block');
18475         },
18476
18477         hide : function(msgEl, f){
18478             msgEl.setDisplayed(false).update('');
18479         }
18480     },
18481
18482     slide : {
18483         show: function(msgEl, f){
18484             msgEl.slideIn('t', {stopFx:true});
18485         },
18486
18487         hide : function(msgEl, f){
18488             msgEl.slideOut('t', {stopFx:true,useDisplay:true});
18489         }
18490     },
18491
18492     slideRight : {
18493         show: function(msgEl, f){
18494             msgEl.fixDisplay();
18495             msgEl.alignTo(f.el, 'tl-tr');
18496             msgEl.slideIn('l', {stopFx:true});
18497         },
18498
18499         hide : function(msgEl, f){
18500             msgEl.slideOut('l', {stopFx:true,useDisplay:true});
18501         }
18502     }
18503 };/*
18504  * Based on:
18505  * Ext JS Library 1.1.1
18506  * Copyright(c) 2006-2007, Ext JS, LLC.
18507  *
18508  * Originally Released Under LGPL - original licence link has changed is not relivant.
18509  *
18510  * Fork - LGPL
18511  * <script type="text/javascript">
18512  */
18513  
18514
18515 /**
18516  * @class Roo.form.TextField
18517  * @extends Roo.form.Field
18518  * Basic text field.  Can be used as a direct replacement for traditional text inputs, or as the base
18519  * class for more sophisticated input controls (like {@link Roo.form.TextArea} and {@link Roo.form.ComboBox}).
18520  * @constructor
18521  * Creates a new TextField
18522  * @param {Object} config Configuration options
18523  */
18524 Roo.form.TextField = function(config){
18525     Roo.form.TextField.superclass.constructor.call(this, config);
18526     this.addEvents({
18527         /**
18528          * @event autosize
18529          * Fires when the autosize function is triggered.  The field may or may not have actually changed size
18530          * according to the default logic, but this event provides a hook for the developer to apply additional
18531          * logic at runtime to resize the field if needed.
18532              * @param {Roo.form.Field} this This text field
18533              * @param {Number} width The new field width
18534              */
18535         autosize : true
18536     });
18537 };
18538
18539 Roo.extend(Roo.form.TextField, Roo.form.Field,  {
18540     /**
18541      * @cfg {Boolean} grow True if this field should automatically grow and shrink to its content
18542      */
18543     grow : false,
18544     /**
18545      * @cfg {Number} growMin The minimum width to allow when grow = true (defaults to 30)
18546      */
18547     growMin : 30,
18548     /**
18549      * @cfg {Number} growMax The maximum width to allow when grow = true (defaults to 800)
18550      */
18551     growMax : 800,
18552     /**
18553      * @cfg {String} vtype A validation type name as defined in {@link Roo.form.VTypes} (defaults to null)
18554      */
18555     vtype : null,
18556     /**
18557      * @cfg {String} maskRe An input mask regular expression that will be used to filter keystrokes that don't match (defaults to null)
18558      */
18559     maskRe : null,
18560     /**
18561      * @cfg {Boolean} disableKeyFilter True to disable input keystroke filtering (defaults to false)
18562      */
18563     disableKeyFilter : false,
18564     /**
18565      * @cfg {Boolean} allowBlank False to validate that the value length > 0 (defaults to true)
18566      */
18567     allowBlank : true,
18568     /**
18569      * @cfg {Number} minLength Minimum input field length required (defaults to 0)
18570      */
18571     minLength : 0,
18572     /**
18573      * @cfg {Number} maxLength Maximum input field length allowed (defaults to Number.MAX_VALUE)
18574      */
18575     maxLength : Number.MAX_VALUE,
18576     /**
18577      * @cfg {String} minLengthText Error text to display if the minimum length validation fails (defaults to "The minimum length for this field is {minLength}")
18578      */
18579     minLengthText : "The minimum length for this field is {0}",
18580     /**
18581      * @cfg {String} maxLengthText Error text to display if the maximum length validation fails (defaults to "The maximum length for this field is {maxLength}")
18582      */
18583     maxLengthText : "The maximum length for this field is {0}",
18584     /**
18585      * @cfg {Boolean} selectOnFocus True to automatically select any existing field text when the field receives input focus (defaults to false)
18586      */
18587     selectOnFocus : false,
18588     /**
18589      * @cfg {Boolean} allowLeadingSpace True to prevent the stripping of leading white space 
18590      */    
18591     allowLeadingSpace : false,
18592     /**
18593      * @cfg {String} blankText Error text to display if the allow blank validation fails (defaults to "This field is required")
18594      */
18595     blankText : "This field is required",
18596     /**
18597      * @cfg {Function} validator A custom validation function to be called during field validation (defaults to null).
18598      * If available, this function will be called only after the basic validators all return true, and will be passed the
18599      * current field value and expected to return boolean true if the value is valid or a string error message if invalid.
18600      */
18601     validator : null,
18602     /**
18603      * @cfg {RegExp} regex A JavaScript RegExp object to be tested against the field value during validation (defaults to null).
18604      * If available, this regex will be evaluated only after the basic validators all return true, and will be passed the
18605      * current field value.  If the test fails, the field will be marked invalid using {@link #regexText}.
18606      */
18607     regex : null,
18608     /**
18609      * @cfg {String} regexText The error text to display if {@link #regex} is used and the test fails during validation (defaults to "")
18610      */
18611     regexText : "",
18612     /**
18613      * @cfg {String} emptyText The default text to display in an empty field - placeholder... (defaults to null).
18614      */
18615     emptyText : null,
18616    
18617
18618     // private
18619     initEvents : function()
18620     {
18621         if (this.emptyText) {
18622             this.el.attr('placeholder', this.emptyText);
18623         }
18624         
18625         Roo.form.TextField.superclass.initEvents.call(this);
18626         if(this.validationEvent == 'keyup'){
18627             this.validationTask = new Roo.util.DelayedTask(this.validate, this);
18628             this.el.on('keyup', this.filterValidation, this);
18629         }
18630         else if(this.validationEvent !== false){
18631             this.el.on(this.validationEvent, this.validate, this, {buffer: this.validationDelay});
18632         }
18633         
18634         if(this.selectOnFocus){
18635             this.on("focus", this.preFocus, this);
18636         }
18637                 if (!this.allowLeadingSpace) {
18638                         this.on('blur', this.cleanLeadingSpace, this);
18639                 }
18640         
18641         if(this.maskRe || (this.vtype && this.disableKeyFilter !== true && (this.maskRe = Roo.form.VTypes[this.vtype+'Mask']))){
18642             this.el.on("keypress", this.filterKeys, this);
18643         }
18644         if(this.grow){
18645             this.el.on("keyup", this.onKeyUp,  this, {buffer:50});
18646             this.el.on("click", this.autoSize,  this);
18647         }
18648         if(this.el.is('input[type=password]') && Roo.isSafari){
18649             this.el.on('keydown', this.SafariOnKeyDown, this);
18650         }
18651     },
18652
18653     processValue : function(value){
18654         if(this.stripCharsRe){
18655             var newValue = value.replace(this.stripCharsRe, '');
18656             if(newValue !== value){
18657                 this.setRawValue(newValue);
18658                 return newValue;
18659             }
18660         }
18661         return value;
18662     },
18663
18664     filterValidation : function(e){
18665         if(!e.isNavKeyPress()){
18666             this.validationTask.delay(this.validationDelay);
18667         }
18668     },
18669
18670     // private
18671     onKeyUp : function(e){
18672         if(!e.isNavKeyPress()){
18673             this.autoSize();
18674         }
18675     },
18676     // private - clean the leading white space
18677     cleanLeadingSpace : function(e)
18678     {
18679         if ( this.inputType == 'file') {
18680             return;
18681         }
18682         
18683         this.setValue((this.getValue() + '').replace(/^\s+/,''));
18684     },
18685     /**
18686      * Resets the current field value to the originally-loaded value and clears any validation messages.
18687      *  
18688      */
18689     reset : function(){
18690         Roo.form.TextField.superclass.reset.call(this);
18691        
18692     }, 
18693     // private
18694     preFocus : function(){
18695         
18696         if(this.selectOnFocus){
18697             this.el.dom.select();
18698         }
18699     },
18700
18701     
18702     // private
18703     filterKeys : function(e){
18704         var k = e.getKey();
18705         if(!Roo.isIE && (e.isNavKeyPress() || k == e.BACKSPACE || (k == e.DELETE && e.button == -1))){
18706             return;
18707         }
18708         var c = e.getCharCode(), cc = String.fromCharCode(c);
18709         if(Roo.isIE && (e.isSpecialKey() || !cc)){
18710             return;
18711         }
18712         if(!this.maskRe.test(cc)){
18713             e.stopEvent();
18714         }
18715     },
18716
18717     setValue : function(v){
18718         
18719         Roo.form.TextField.superclass.setValue.apply(this, arguments);
18720         
18721         this.autoSize();
18722     },
18723
18724     /**
18725      * Validates a value according to the field's validation rules and marks the field as invalid
18726      * if the validation fails
18727      * @param {Mixed} value The value to validate
18728      * @return {Boolean} True if the value is valid, else false
18729      */
18730     validateValue : function(value){
18731         if(value.length < 1)  { // if it's blank
18732              if(this.allowBlank){
18733                 this.clearInvalid();
18734                 return true;
18735              }else{
18736                 this.markInvalid(this.blankText);
18737                 return false;
18738              }
18739         }
18740         if(value.length < this.minLength){
18741             this.markInvalid(String.format(this.minLengthText, this.minLength));
18742             return false;
18743         }
18744         if(value.length > this.maxLength){
18745             this.markInvalid(String.format(this.maxLengthText, this.maxLength));
18746             return false;
18747         }
18748         if(this.vtype){
18749             var vt = Roo.form.VTypes;
18750                         if (value.trim() != value) { // trim before checking email (and other stuf??)
18751                                 value = value.trim();
18752                                 this.el.dom.value  = value;
18753                         }
18754                         
18755             if(!vt[this.vtype](value, this)){
18756                 this.markInvalid(this.vtypeText || vt[this.vtype +'Text']);
18757                 return false;
18758             }
18759         }
18760         if(typeof this.validator == "function"){
18761             var msg = this.validator(value);
18762             if(msg !== true){
18763                 this.markInvalid(msg);
18764                 return false;
18765             }
18766         }
18767         if(this.regex && !this.regex.test(value)){
18768             this.markInvalid(this.regexText);
18769             return false;
18770         }
18771         return true;
18772     },
18773
18774     /**
18775      * Selects text in this field
18776      * @param {Number} start (optional) The index where the selection should start (defaults to 0)
18777      * @param {Number} end (optional) The index where the selection should end (defaults to the text length)
18778      */
18779     selectText : function(start, end){
18780         var v = this.getRawValue();
18781         if(v.length > 0){
18782             start = start === undefined ? 0 : start;
18783             end = end === undefined ? v.length : end;
18784             var d = this.el.dom;
18785             if(d.setSelectionRange){
18786                 d.setSelectionRange(start, end);
18787             }else if(d.createTextRange){
18788                 var range = d.createTextRange();
18789                 range.moveStart("character", start);
18790                 range.moveEnd("character", v.length-end);
18791                 range.select();
18792             }
18793         }
18794     },
18795
18796     /**
18797      * Automatically grows the field to accomodate the width of the text up to the maximum field width allowed.
18798      * This only takes effect if grow = true, and fires the autosize event.
18799      */
18800     autoSize : function(){
18801         if(!this.grow || !this.rendered){
18802             return;
18803         }
18804         if(!this.metrics){
18805             this.metrics = Roo.util.TextMetrics.createInstance(this.el);
18806         }
18807         var el = this.el;
18808         var v = el.dom.value;
18809         var d = document.createElement('div');
18810         d.appendChild(document.createTextNode(v));
18811         v = d.innerHTML;
18812         d = null;
18813         v += "&#160;";
18814         var w = Math.min(this.growMax, Math.max(this.metrics.getWidth(v) + /* add extra padding */ 10, this.growMin));
18815         this.el.setWidth(w);
18816         this.fireEvent("autosize", this, w);
18817     },
18818     
18819     // private
18820     SafariOnKeyDown : function(event)
18821     {
18822         // this is a workaround for a password hang bug on chrome/ webkit.
18823         
18824         var isSelectAll = false;
18825         
18826         if(this.el.dom.selectionEnd > 0){
18827             isSelectAll = (this.el.dom.selectionEnd - this.el.dom.selectionStart - this.getValue().length == 0) ? true : false;
18828         }
18829         if(((event.getKey() == 8 || event.getKey() == 46) && this.getValue().length ==1)){ // backspace and delete key
18830             event.preventDefault();
18831             this.setValue('');
18832             return;
18833         }
18834         
18835         // skip handling paste
18836         if(isSelectAll && event.getCharCode() > 31 && !(event.ctrlKey && event.getCharCode() == 86)){ // backspace and delete key
18837             
18838             event.preventDefault();
18839             // this is very hacky as keydown always get's upper case.
18840             
18841             var cc = String.fromCharCode(event.getCharCode());
18842             
18843             
18844             this.setValue( event.shiftKey ?  cc : cc.toLowerCase());
18845             
18846         }
18847         
18848         
18849     }
18850 });Roo.form.Password = function(config){
18851     Roo.form.Password.superclass.constructor.call(this, config);
18852
18853     this.inputType = 'password';
18854 };
18855
18856 Roo.extend(Roo.form.Password, Roo.form.TextField,  {
18857     onRender : function(ct, position)
18858     {
18859         Roo.form.Password.superclass.onRender.call(this, ct, position);
18860
18861         this.parentEl().addClass('form-password');
18862
18863         this.wrap = this.el.wrap({
18864             cls : 'password-wrap'
18865         });
18866
18867         this.toggle = this.wrap.createChild({
18868             tag : 'Button',
18869             cls : 'password-toggle'
18870         });
18871
18872
18873         this.toggleEl().addClass('password-hidden');
18874
18875         this.toggleEl().on('click', this.onToggleClick, this);;
18876     },
18877     
18878     parentEl : function()
18879     {
18880         return this.el.findParent('.x-form-element', 5, true);
18881     },
18882
18883     toggleEl: function()
18884     {
18885         return this.parentEl().select('button.password-toggle',true).first();
18886     },
18887
18888     onToggleClick : function(e) 
18889     {
18890         var input = this.el;
18891         var toggle = this.toggleEl();
18892
18893         toggle.removeClass(['password-visible', 'password-hidden']);
18894
18895         if(input.attr('type') == 'password') {
18896             input.attr('type', 'text');
18897             toggle.addClass('password-visible');
18898         }
18899         else {
18900             input.attr('type', 'password');
18901             toggle.addClass('password-hidden');
18902         }
18903     }
18904 });/*
18905  * Based on:
18906  * Ext JS Library 1.1.1
18907  * Copyright(c) 2006-2007, Ext JS, LLC.
18908  *
18909  * Originally Released Under LGPL - original licence link has changed is not relivant.
18910  *
18911  * Fork - LGPL
18912  * <script type="text/javascript">
18913  */
18914  
18915 /**
18916  * @class Roo.form.Hidden
18917  * @extends Roo.form.TextField
18918  * Simple Hidden element used on forms 
18919  * 
18920  * usage: form.add(new Roo.form.HiddenField({ 'name' : 'test1' }));
18921  * 
18922  * @constructor
18923  * Creates a new Hidden form element.
18924  * @param {Object} config Configuration options
18925  */
18926
18927
18928
18929 // easy hidden field...
18930 Roo.form.Hidden = function(config){
18931     Roo.form.Hidden.superclass.constructor.call(this, config);
18932 };
18933   
18934 Roo.extend(Roo.form.Hidden, Roo.form.TextField, {
18935     fieldLabel:      '',
18936     inputType:      'hidden',
18937     width:          50,
18938     allowBlank:     true,
18939     labelSeparator: '',
18940     hidden:         true,
18941     itemCls :       'x-form-item-display-none'
18942
18943
18944 });
18945
18946
18947 /*
18948  * Based on:
18949  * Ext JS Library 1.1.1
18950  * Copyright(c) 2006-2007, Ext JS, LLC.
18951  *
18952  * Originally Released Under LGPL - original licence link has changed is not relivant.
18953  *
18954  * Fork - LGPL
18955  * <script type="text/javascript">
18956  */
18957  
18958 /**
18959  * @class Roo.form.TriggerField
18960  * @extends Roo.form.TextField
18961  * Provides a convenient wrapper for TextFields that adds a clickable trigger button (looks like a combobox by default).
18962  * The trigger has no default action, so you must assign a function to implement the trigger click handler by
18963  * overriding {@link #onTriggerClick}. You can create a TriggerField directly, as it renders exactly like a combobox
18964  * for which you can provide a custom implementation.  For example:
18965  * <pre><code>
18966 var trigger = new Roo.form.TriggerField();
18967 trigger.onTriggerClick = myTriggerFn;
18968 trigger.applyTo('my-field');
18969 </code></pre>
18970  *
18971  * However, in general you will most likely want to use TriggerField as the base class for a reusable component.
18972  * {@link Roo.form.DateField} and {@link Roo.form.ComboBox} are perfect examples of this.
18973  * @cfg {String} triggerClass An additional CSS class used to style the trigger button.  The trigger will always get the
18974  * class 'x-form-trigger' by default and triggerClass will be <b>appended</b> if specified.
18975  * @constructor
18976  * Create a new TriggerField.
18977  * @param {Object} config Configuration options (valid {@Roo.form.TextField} config options will also be applied
18978  * to the base TextField)
18979  */
18980 Roo.form.TriggerField = function(config){
18981     this.mimicing = false;
18982     Roo.form.TriggerField.superclass.constructor.call(this, config);
18983 };
18984
18985 Roo.extend(Roo.form.TriggerField, Roo.form.TextField,  {
18986     /**
18987      * @cfg {String} triggerClass A CSS class to apply to the trigger
18988      */
18989     /**
18990      * @cfg {String/Object} autoCreate A DomHelper element spec, or true for a default element spec (defaults to
18991      * {tag: "input", type: "text", size: "16", autocomplete: "off"})
18992      */
18993     defaultAutoCreate : {tag: "input", type: "text", size: "16", autocomplete: "new-password"},
18994     /**
18995      * @cfg {Boolean} hideTrigger True to hide the trigger element and display only the base text field (defaults to false)
18996      */
18997     hideTrigger:false,
18998
18999     /** @cfg {Boolean} grow @hide */
19000     /** @cfg {Number} growMin @hide */
19001     /** @cfg {Number} growMax @hide */
19002
19003     /**
19004      * @hide 
19005      * @method
19006      */
19007     autoSize: Roo.emptyFn,
19008     // private
19009     monitorTab : true,
19010     // private
19011     deferHeight : true,
19012
19013     
19014     actionMode : 'wrap',
19015     // private
19016     onResize : function(w, h){
19017         Roo.form.TriggerField.superclass.onResize.apply(this, arguments);
19018         if(typeof w == 'number'){
19019             var x = w - this.trigger.getWidth();
19020             this.el.setWidth(this.adjustWidth('input', x));
19021             this.trigger.setStyle('left', x+'px');
19022         }
19023     },
19024
19025     // private
19026     adjustSize : Roo.BoxComponent.prototype.adjustSize,
19027
19028     // private
19029     getResizeEl : function(){
19030         return this.wrap;
19031     },
19032
19033     // private
19034     getPositionEl : function(){
19035         return this.wrap;
19036     },
19037
19038     // private
19039     alignErrorIcon : function(){
19040         this.errorIcon.alignTo(this.wrap, 'tl-tr', [2, 0]);
19041     },
19042
19043     // private
19044     onRender : function(ct, position){
19045         Roo.form.TriggerField.superclass.onRender.call(this, ct, position);
19046         this.wrap = this.el.wrap({cls: "x-form-field-wrap"});
19047         this.trigger = this.wrap.createChild(this.triggerConfig ||
19048                 {tag: "img", src: Roo.BLANK_IMAGE_URL, cls: "x-form-trigger " + this.triggerClass});
19049         if(this.hideTrigger){
19050             this.trigger.setDisplayed(false);
19051         }
19052         this.initTrigger();
19053         if(!this.width){
19054             this.wrap.setWidth(this.el.getWidth()+this.trigger.getWidth());
19055         }
19056     },
19057
19058     // private
19059     initTrigger : function(){
19060         this.trigger.on("click", this.onTriggerClick, this, {preventDefault:true});
19061         this.trigger.addClassOnOver('x-form-trigger-over');
19062         this.trigger.addClassOnClick('x-form-trigger-click');
19063     },
19064
19065     // private
19066     onDestroy : function(){
19067         if(this.trigger){
19068             this.trigger.removeAllListeners();
19069             this.trigger.remove();
19070         }
19071         if(this.wrap){
19072             this.wrap.remove();
19073         }
19074         Roo.form.TriggerField.superclass.onDestroy.call(this);
19075     },
19076
19077     // private
19078     onFocus : function(){
19079         Roo.form.TriggerField.superclass.onFocus.call(this);
19080         if(!this.mimicing){
19081             this.wrap.addClass('x-trigger-wrap-focus');
19082             this.mimicing = true;
19083             Roo.get(Roo.isIE ? document.body : document).on("mousedown", this.mimicBlur, this);
19084             if(this.monitorTab){
19085                 this.el.on("keydown", this.checkTab, this);
19086             }
19087         }
19088     },
19089
19090     // private
19091     checkTab : function(e){
19092         if(e.getKey() == e.TAB){
19093             this.triggerBlur();
19094         }
19095     },
19096
19097     // private
19098     onBlur : function(){
19099         // do nothing
19100     },
19101
19102     // private
19103     mimicBlur : function(e, t){
19104         if(!this.wrap.contains(t) && this.validateBlur()){
19105             this.triggerBlur();
19106         }
19107     },
19108
19109     // private
19110     triggerBlur : function(){
19111         this.mimicing = false;
19112         Roo.get(Roo.isIE ? document.body : document).un("mousedown", this.mimicBlur);
19113         if(this.monitorTab){
19114             this.el.un("keydown", this.checkTab, this);
19115         }
19116         this.wrap.removeClass('x-trigger-wrap-focus');
19117         Roo.form.TriggerField.superclass.onBlur.call(this);
19118     },
19119
19120     // private
19121     // This should be overriden by any subclass that needs to check whether or not the field can be blurred.
19122     validateBlur : function(e, t){
19123         return true;
19124     },
19125
19126     // private
19127     onDisable : function(){
19128         Roo.form.TriggerField.superclass.onDisable.call(this);
19129         if(this.wrap){
19130             this.wrap.addClass('x-item-disabled');
19131         }
19132     },
19133
19134     // private
19135     onEnable : function(){
19136         Roo.form.TriggerField.superclass.onEnable.call(this);
19137         if(this.wrap){
19138             this.wrap.removeClass('x-item-disabled');
19139         }
19140     },
19141
19142     // private
19143     onShow : function(){
19144         var ae = this.getActionEl();
19145         
19146         if(ae){
19147             ae.dom.style.display = '';
19148             ae.dom.style.visibility = 'visible';
19149         }
19150     },
19151
19152     // private
19153     
19154     onHide : function(){
19155         var ae = this.getActionEl();
19156         ae.dom.style.display = 'none';
19157     },
19158
19159     /**
19160      * The function that should handle the trigger's click event.  This method does nothing by default until overridden
19161      * by an implementing function.
19162      * @method
19163      * @param {EventObject} e
19164      */
19165     onTriggerClick : Roo.emptyFn
19166 });
19167
19168 // TwinTriggerField is not a public class to be used directly.  It is meant as an abstract base class
19169 // to be extended by an implementing class.  For an example of implementing this class, see the custom
19170 // SearchField implementation here: http://extjs.com/deploy/ext/examples/form/custom.html
19171 Roo.form.TwinTriggerField = Roo.extend(Roo.form.TriggerField, {
19172     initComponent : function(){
19173         Roo.form.TwinTriggerField.superclass.initComponent.call(this);
19174
19175         this.triggerConfig = {
19176             tag:'span', cls:'x-form-twin-triggers', cn:[
19177             {tag: "img", src: Roo.BLANK_IMAGE_URL, cls: "x-form-trigger " + this.trigger1Class},
19178             {tag: "img", src: Roo.BLANK_IMAGE_URL, cls: "x-form-trigger " + this.trigger2Class}
19179         ]};
19180     },
19181
19182     getTrigger : function(index){
19183         return this.triggers[index];
19184     },
19185
19186     initTrigger : function(){
19187         var ts = this.trigger.select('.x-form-trigger', true);
19188         this.wrap.setStyle('overflow', 'hidden');
19189         var triggerField = this;
19190         ts.each(function(t, all, index){
19191             t.hide = function(){
19192                 var w = triggerField.wrap.getWidth();
19193                 this.dom.style.display = 'none';
19194                 triggerField.el.setWidth(w-triggerField.trigger.getWidth());
19195             };
19196             t.show = function(){
19197                 var w = triggerField.wrap.getWidth();
19198                 this.dom.style.display = '';
19199                 triggerField.el.setWidth(w-triggerField.trigger.getWidth());
19200             };
19201             var triggerIndex = 'Trigger'+(index+1);
19202
19203             if(this['hide'+triggerIndex]){
19204                 t.dom.style.display = 'none';
19205             }
19206             t.on("click", this['on'+triggerIndex+'Click'], this, {preventDefault:true});
19207             t.addClassOnOver('x-form-trigger-over');
19208             t.addClassOnClick('x-form-trigger-click');
19209         }, this);
19210         this.triggers = ts.elements;
19211     },
19212
19213     onTrigger1Click : Roo.emptyFn,
19214     onTrigger2Click : Roo.emptyFn
19215 });/*
19216  * Based on:
19217  * Ext JS Library 1.1.1
19218  * Copyright(c) 2006-2007, Ext JS, LLC.
19219  *
19220  * Originally Released Under LGPL - original licence link has changed is not relivant.
19221  *
19222  * Fork - LGPL
19223  * <script type="text/javascript">
19224  */
19225  
19226 /**
19227  * @class Roo.form.TextArea
19228  * @extends Roo.form.TextField
19229  * Multiline text field.  Can be used as a direct replacement for traditional textarea fields, plus adds
19230  * support for auto-sizing.
19231  * @constructor
19232  * Creates a new TextArea
19233  * @param {Object} config Configuration options
19234  */
19235 Roo.form.TextArea = function(config){
19236     Roo.form.TextArea.superclass.constructor.call(this, config);
19237     // these are provided exchanges for backwards compat
19238     // minHeight/maxHeight were replaced by growMin/growMax to be
19239     // compatible with TextField growing config values
19240     if(this.minHeight !== undefined){
19241         this.growMin = this.minHeight;
19242     }
19243     if(this.maxHeight !== undefined){
19244         this.growMax = this.maxHeight;
19245     }
19246 };
19247
19248 Roo.extend(Roo.form.TextArea, Roo.form.TextField,  {
19249     /**
19250      * @cfg {Number} growMin The minimum height to allow when grow = true (defaults to 60)
19251      */
19252     growMin : 60,
19253     /**
19254      * @cfg {Number} growMax The maximum height to allow when grow = true (defaults to 1000)
19255      */
19256     growMax: 1000,
19257     /**
19258      * @cfg {Boolean} preventScrollbars True to prevent scrollbars from appearing regardless of how much text is
19259      * in the field (equivalent to setting overflow: hidden, defaults to false)
19260      */
19261     preventScrollbars: false,
19262     /**
19263      * @cfg {String/Object} autoCreate A DomHelper element spec, or true for a default element spec (defaults to
19264      * {tag: "textarea", style: "width:300px;height:60px;", autocomplete: "off"})
19265      */
19266
19267     // private
19268     onRender : function(ct, position){
19269         if(!this.el){
19270             this.defaultAutoCreate = {
19271                 tag: "textarea",
19272                 style:"width:300px;height:60px;",
19273                 autocomplete: "new-password"
19274             };
19275         }
19276         Roo.form.TextArea.superclass.onRender.call(this, ct, position);
19277         if(this.grow){
19278             this.textSizeEl = Roo.DomHelper.append(document.body, {
19279                 tag: "pre", cls: "x-form-grow-sizer"
19280             });
19281             if(this.preventScrollbars){
19282                 this.el.setStyle("overflow", "hidden");
19283             }
19284             this.el.setHeight(this.growMin);
19285         }
19286     },
19287
19288     onDestroy : function(){
19289         if(this.textSizeEl){
19290             this.textSizeEl.parentNode.removeChild(this.textSizeEl);
19291         }
19292         Roo.form.TextArea.superclass.onDestroy.call(this);
19293     },
19294
19295     // private
19296     onKeyUp : function(e){
19297         if(!e.isNavKeyPress() || e.getKey() == e.ENTER){
19298             this.autoSize();
19299         }
19300     },
19301
19302     /**
19303      * Automatically grows the field to accomodate the height of the text up to the maximum field height allowed.
19304      * This only takes effect if grow = true, and fires the autosize event if the height changes.
19305      */
19306     autoSize : function(){
19307         if(!this.grow || !this.textSizeEl){
19308             return;
19309         }
19310         var el = this.el;
19311         var v = el.dom.value;
19312         var ts = this.textSizeEl;
19313
19314         ts.innerHTML = '';
19315         ts.appendChild(document.createTextNode(v));
19316         v = ts.innerHTML;
19317
19318         Roo.fly(ts).setWidth(this.el.getWidth());
19319         if(v.length < 1){
19320             v = "&#160;&#160;";
19321         }else{
19322             if(Roo.isIE){
19323                 v = v.replace(/\n/g, '<p>&#160;</p>');
19324             }
19325             v += "&#160;\n&#160;";
19326         }
19327         ts.innerHTML = v;
19328         var h = Math.min(this.growMax, Math.max(ts.offsetHeight, this.growMin));
19329         if(h != this.lastHeight){
19330             this.lastHeight = h;
19331             this.el.setHeight(h);
19332             this.fireEvent("autosize", this, h);
19333         }
19334     }
19335 });/*
19336  * Based on:
19337  * Ext JS Library 1.1.1
19338  * Copyright(c) 2006-2007, Ext JS, LLC.
19339  *
19340  * Originally Released Under LGPL - original licence link has changed is not relivant.
19341  *
19342  * Fork - LGPL
19343  * <script type="text/javascript">
19344  */
19345  
19346
19347 /**
19348  * @class Roo.form.NumberField
19349  * @extends Roo.form.TextField
19350  * Numeric text field that provides automatic keystroke filtering and numeric validation.
19351  * @constructor
19352  * Creates a new NumberField
19353  * @param {Object} config Configuration options
19354  */
19355 Roo.form.NumberField = function(config){
19356     Roo.form.NumberField.superclass.constructor.call(this, config);
19357 };
19358
19359 Roo.extend(Roo.form.NumberField, Roo.form.TextField,  {
19360     /**
19361      * @cfg {String} fieldClass The default CSS class for the field (defaults to "x-form-field x-form-num-field")
19362      */
19363     fieldClass: "x-form-field x-form-num-field",
19364     /**
19365      * @cfg {Boolean} allowDecimals False to disallow decimal values (defaults to true)
19366      */
19367     allowDecimals : true,
19368     /**
19369      * @cfg {String} decimalSeparator Character(s) to allow as the decimal separator (defaults to '.')
19370      */
19371     decimalSeparator : ".",
19372     /**
19373      * @cfg {String} thousandSeparator Character(s) to allow as the thousand separator (defaults to '') - set to ',' for example
19374      */
19375     thousandSeparator : "",
19376     /**
19377      * @cfg {Number} decimalPrecision The maximum precision to display after the decimal separator (defaults to 2)
19378      */
19379     decimalPrecision : 2,
19380     /**
19381      * @cfg {Boolean} allowNegative False to prevent entering a negative sign (defaults to true)
19382      */
19383     allowNegative : true,
19384     /**
19385      * @cfg {Number} minValue The minimum allowed value (defaults to Number.NEGATIVE_INFINITY)
19386      */
19387     minValue : Number.NEGATIVE_INFINITY,
19388     /**
19389      * @cfg {Number} maxValue The maximum allowed value (defaults to Number.MAX_VALUE)
19390      */
19391     maxValue : Number.MAX_VALUE,
19392     /**
19393      * @cfg {String} minText Error text to display if the minimum value validation fails (defaults to "The minimum value for this field is {minValue}")
19394      */
19395     minText : "The minimum value for this field is {0}",
19396     /**
19397      * @cfg {String} maxText Error text to display if the maximum value validation fails (defaults to "The maximum value for this field is {maxValue}")
19398      */
19399     maxText : "The maximum value for this field is {0}",
19400     /**
19401      * @cfg {String} nanText Error text to display if the value is not a valid number.  For example, this can happen
19402      * if a valid character like '.' or '-' is left in the field with no number (defaults to "{value} is not a valid number")
19403      */
19404     nanText : "{0} is not a valid number",
19405     
19406     hiddenField : false,
19407      
19408     onRender : function(ct, position)
19409     {
19410         Roo.form.TextField.superclass.onRender.call(this, ct, position);
19411     
19412             //this.el.dom.removeAttribute('name'); 
19413         Roo.log("Changing name?");
19414         if (this.thousandSeparator != '') {
19415             this.el.dom.setAttribute('name', this.name + '____hidden___' ); 
19416             this.hiddenField = this.el.insertSibling({ tag:'input', type:'hidden', name: this.name },
19417                         'before', true);
19418             this.hiddenField.value = this.value ? this.parseValue(this.value) : '';
19419             this.el.on('blur', this.onBlur, this);
19420         }
19421         
19422             // prevent input submission
19423         
19424             
19425             
19426     },
19427      onBlur : function(){
19428         this.beforeBlur();
19429         if(!Roo.isOpera && this.focusClass){ // don't touch in Opera
19430             this.el.removeClass(this.focusClass);
19431         }
19432         this.hasFocus = false;
19433         if(this.validationEvent !== false && this.validateOnBlur && this.validationEvent != "blur"){
19434             this.validate();
19435         }
19436         var v = this.getValue();
19437         if(String(v) !== String(this.startValue)){
19438             this.setValue( this.parseValue(v));
19439             this.fireEvent('change', this, v, this.startValue);
19440         }
19441         this.fireEvent("blur", this);
19442     },
19443     
19444     // override name, so that it works with hidden field.
19445     getName: function(){
19446         if (this.thousandSeparator != '') {
19447             return this.name;
19448         }
19449         return Roo.form.TextField.superclass.getName.call(this);
19450     },
19451     // private
19452     initEvents : function(){
19453           
19454         var allowed = "0123456789";
19455         if(this.allowDecimals){
19456             allowed += this.decimalSeparator;
19457         }
19458         allowed += this.thousandSeparator;
19459         if(this.allowNegative){
19460             allowed += "-";
19461         }
19462         this.stripCharsRe = new RegExp('[^'+allowed+']', 'gi');
19463         var keyPress = function(e){
19464             var k = e.getKey();
19465             if(!Roo.isIE && (e.isSpecialKey() || k == e.BACKSPACE || k == e.DELETE)){
19466                 return;
19467             }
19468             var c = e.getCharCode();
19469             if(allowed.indexOf(String.fromCharCode(c)) === -1){
19470                 e.stopEvent();
19471             }
19472         };
19473         this.el.on("keypress", keyPress, this);
19474     },
19475
19476     // private
19477     validateValue : function(value){
19478         if(!Roo.form.NumberField.superclass.validateValue.call(this, value)){
19479             return false;
19480         }
19481         if(value.length < 1){ // if it's blank and textfield didn't flag it then it's valid
19482              return true;
19483         }
19484         var num = this.parseValue(value);
19485         if(isNaN(num)){
19486             this.markInvalid(String.format(this.nanText, value));
19487             return false;
19488         }
19489         if(num < this.minValue){
19490             this.markInvalid(String.format(this.minText, this.minValue));
19491             return false;
19492         }
19493         if(num > this.maxValue){
19494             this.markInvalid(String.format(this.maxText, this.maxValue));
19495             return false;
19496         }
19497         return true;
19498     },
19499
19500     getValue : function(){
19501         return this.fixPrecision(this.parseValue(Roo.form.NumberField.superclass.getValue.call(this)));
19502     },
19503
19504     // private
19505     parseValue : function(value){
19506         value = parseFloat(String(value).replace(this.decimalSeparator, ".").split(this.thousandSeparator).join(''));
19507         return isNaN(value) ? '' : value;
19508     },
19509
19510     // private
19511     fixPrecision : function(value){
19512         var nan = isNaN(value);
19513         if(!this.allowDecimals || this.decimalPrecision == -1 || nan || !value){
19514             return nan ? '' : value;
19515         }
19516         return parseFloat(value).toFixed(this.decimalPrecision);
19517     },
19518
19519     setValue : function(v){
19520         v = this.fixPrecision(v);
19521         if(this.thousandSeparator != ''){
19522             v = Roo.util.Format.number(v, this.decimalPrecision, this.thousandSeparator);
19523         } 
19524         Roo.form.NumberField.superclass.setValue.call(this, String(v).replace(".", this.decimalSeparator));
19525         if (this.hiddenField !== false) {
19526             this.hiddenField.value = v ? this.parseValue(v) : '';
19527         }
19528         
19529
19530     },
19531
19532     // private
19533     decimalPrecisionFcn : function(v){
19534         return Math.floor(v);
19535     },
19536
19537     beforeBlur : function(){
19538         var v = this.parseValue(this.getRawValue());
19539         if(v){
19540             this.setValue(v);
19541         }
19542     }
19543 });/*
19544  * Based on:
19545  * Ext JS Library 1.1.1
19546  * Copyright(c) 2006-2007, Ext JS, LLC.
19547  *
19548  * Originally Released Under LGPL - original licence link has changed is not relivant.
19549  *
19550  * Fork - LGPL
19551  * <script type="text/javascript">
19552  */
19553  
19554 /**
19555  * @class Roo.form.DateField
19556  * @extends Roo.form.TriggerField
19557  * Provides a date input field with a {@link Roo.DatePicker} dropdown and automatic date validation.
19558 * @constructor
19559 * Create a new DateField
19560 * @param {Object} config
19561  */
19562 Roo.form.DateField = function(config)
19563 {
19564     Roo.form.DateField.superclass.constructor.call(this, config);
19565     
19566       this.addEvents({
19567          
19568         /**
19569          * @event select
19570          * Fires when a date is selected
19571              * @param {Roo.form.DateField} combo This combo box
19572              * @param {Date} date The date selected
19573              */
19574         'select' : true
19575          
19576     });
19577     
19578     
19579     if(typeof this.minValue == "string") {
19580         this.minValue = this.parseDate(this.minValue);
19581     }
19582     if(typeof this.maxValue == "string") {
19583         this.maxValue = this.parseDate(this.maxValue);
19584     }
19585     this.ddMatch = null;
19586     if(this.disabledDates){
19587         var dd = this.disabledDates;
19588         var re = "(?:";
19589         for(var i = 0; i < dd.length; i++){
19590             re += dd[i];
19591             if(i != dd.length-1) {
19592                 re += "|";
19593             }
19594         }
19595         this.ddMatch = new RegExp(re + ")");
19596     }
19597 };
19598
19599 Roo.extend(Roo.form.DateField, Roo.form.TriggerField,  {
19600     /**
19601      * @cfg {String} format
19602      * The default date format string which can be overriden for localization support.  The format must be
19603      * valid according to {@link Date#parseDate} (defaults to 'm/d/y').
19604      */
19605     format : "m/d/y",
19606     /**
19607      * @cfg {String} altFormats
19608      * Multiple date formats separated by "|" to try when parsing a user input value and it doesn't match the defined
19609      * format (defaults to 'm/d/Y|m-d-y|m-d-Y|m/d|m-d|d').
19610      */
19611     altFormats : "m/d/Y|m-d-y|m-d-Y|m/d|m-d|md|mdy|mdY|d",
19612     /**
19613      * @cfg {Array} disabledDays
19614      * An array of days to disable, 0 based. For example, [0, 6] disables Sunday and Saturday (defaults to null).
19615      */
19616     disabledDays : null,
19617     /**
19618      * @cfg {String} disabledDaysText
19619      * The tooltip to display when the date falls on a disabled day (defaults to 'Disabled')
19620      */
19621     disabledDaysText : "Disabled",
19622     /**
19623      * @cfg {Array} disabledDates
19624      * An array of "dates" to disable, as strings. These strings will be used to build a dynamic regular
19625      * expression so they are very powerful. Some examples:
19626      * <ul>
19627      * <li>["03/08/2003", "09/16/2003"] would disable those exact dates</li>
19628      * <li>["03/08", "09/16"] would disable those days for every year</li>
19629      * <li>["^03/08"] would only match the beginning (useful if you are using short years)</li>
19630      * <li>["03/../2006"] would disable every day in March 2006</li>
19631      * <li>["^03"] would disable every day in every March</li>
19632      * </ul>
19633      * In order to support regular expressions, if you are using a date format that has "." in it, you will have to
19634      * escape the dot when restricting dates. For example: ["03\\.08\\.03"].
19635      */
19636     disabledDates : null,
19637     /**
19638      * @cfg {String} disabledDatesText
19639      * The tooltip text to display when the date falls on a disabled date (defaults to 'Disabled')
19640      */
19641     disabledDatesText : "Disabled",
19642         
19643         
19644         /**
19645      * @cfg {Date/String} zeroValue
19646      * if the date is less that this number, then the field is rendered as empty
19647      * default is 1800
19648      */
19649         zeroValue : '1800-01-01',
19650         
19651         
19652     /**
19653      * @cfg {Date/String} minValue
19654      * The minimum allowed date. Can be either a Javascript date object or a string date in a
19655      * valid format (defaults to null).
19656      */
19657     minValue : null,
19658     /**
19659      * @cfg {Date/String} maxValue
19660      * The maximum allowed date. Can be either a Javascript date object or a string date in a
19661      * valid format (defaults to null).
19662      */
19663     maxValue : null,
19664     /**
19665      * @cfg {String} minText
19666      * The error text to display when the date in the cell is before minValue (defaults to
19667      * 'The date in this field must be after {minValue}').
19668      */
19669     minText : "The date in this field must be equal to or after {0}",
19670     /**
19671      * @cfg {String} maxText
19672      * The error text to display when the date in the cell is after maxValue (defaults to
19673      * 'The date in this field must be before {maxValue}').
19674      */
19675     maxText : "The date in this field must be equal to or before {0}",
19676     /**
19677      * @cfg {String} invalidText
19678      * The error text to display when the date in the field is invalid (defaults to
19679      * '{value} is not a valid date - it must be in the format {format}').
19680      */
19681     invalidText : "{0} is not a valid date - it must be in the format {1}",
19682     /**
19683      * @cfg {String} triggerClass
19684      * An additional CSS class used to style the trigger button.  The trigger will always get the
19685      * class 'x-form-trigger' and triggerClass will be <b>appended</b> if specified (defaults to 'x-form-date-trigger'
19686      * which displays a calendar icon).
19687      */
19688     triggerClass : 'x-form-date-trigger',
19689     
19690
19691     /**
19692      * @cfg {Boolean} useIso
19693      * if enabled, then the date field will use a hidden field to store the 
19694      * real value as iso formated date. default (false)
19695      */ 
19696     useIso : false,
19697     /**
19698      * @cfg {String/Object} autoCreate
19699      * A DomHelper element spec, or true for a default element spec (defaults to
19700      * {tag: "input", type: "text", size: "10", autocomplete: "off"})
19701      */ 
19702     // private
19703     defaultAutoCreate : {tag: "input", type: "text", size: "10", autocomplete: "off"},
19704     
19705     // private
19706     hiddenField: false,
19707     
19708     onRender : function(ct, position)
19709     {
19710         Roo.form.DateField.superclass.onRender.call(this, ct, position);
19711         if (this.useIso) {
19712             //this.el.dom.removeAttribute('name'); 
19713             Roo.log("Changing name?");
19714             this.el.dom.setAttribute('name', this.name + '____hidden___' ); 
19715             this.hiddenField = this.el.insertSibling({ tag:'input', type:'hidden', name: this.name },
19716                     'before', true);
19717             this.hiddenField.value = this.value ? this.formatDate(this.value, 'Y-m-d') : '';
19718             // prevent input submission
19719             this.hiddenName = this.name;
19720         }
19721             
19722             
19723     },
19724     
19725     // private
19726     validateValue : function(value)
19727     {
19728         value = this.formatDate(value);
19729         if(!Roo.form.DateField.superclass.validateValue.call(this, value)){
19730             Roo.log('super failed');
19731             return false;
19732         }
19733         if(value.length < 1){ // if it's blank and textfield didn't flag it then it's valid
19734              return true;
19735         }
19736         var svalue = value;
19737         value = this.parseDate(value);
19738         if(!value){
19739             Roo.log('parse date failed' + svalue);
19740             this.markInvalid(String.format(this.invalidText, svalue, this.format));
19741             return false;
19742         }
19743         var time = value.getTime();
19744         if(this.minValue && time < this.minValue.getTime()){
19745             this.markInvalid(String.format(this.minText, this.formatDate(this.minValue)));
19746             return false;
19747         }
19748         if(this.maxValue && time > this.maxValue.getTime()){
19749             this.markInvalid(String.format(this.maxText, this.formatDate(this.maxValue)));
19750             return false;
19751         }
19752         if(this.disabledDays){
19753             var day = value.getDay();
19754             for(var i = 0; i < this.disabledDays.length; i++) {
19755                 if(day === this.disabledDays[i]){
19756                     this.markInvalid(this.disabledDaysText);
19757                     return false;
19758                 }
19759             }
19760         }
19761         var fvalue = this.formatDate(value);
19762         if(this.ddMatch && this.ddMatch.test(fvalue)){
19763             this.markInvalid(String.format(this.disabledDatesText, fvalue));
19764             return false;
19765         }
19766         return true;
19767     },
19768
19769     // private
19770     // Provides logic to override the default TriggerField.validateBlur which just returns true
19771     validateBlur : function(){
19772         return !this.menu || !this.menu.isVisible();
19773     },
19774     
19775     getName: function()
19776     {
19777         // returns hidden if it's set..
19778         if (!this.rendered) {return ''};
19779         return !this.hiddenName && this.el.dom.name  ? this.el.dom.name : (this.hiddenName || '');
19780         
19781     },
19782
19783     /**
19784      * Returns the current date value of the date field.
19785      * @return {Date} The date value
19786      */
19787     getValue : function(){
19788         
19789         return  this.hiddenField ?
19790                 this.hiddenField.value :
19791                 this.parseDate(Roo.form.DateField.superclass.getValue.call(this)) || "";
19792     },
19793
19794     /**
19795      * Sets the value of the date field.  You can pass a date object or any string that can be parsed into a valid
19796      * date, using DateField.format as the date format, according to the same rules as {@link Date#parseDate}
19797      * (the default format used is "m/d/y").
19798      * <br />Usage:
19799      * <pre><code>
19800 //All of these calls set the same date value (May 4, 2006)
19801
19802 //Pass a date object:
19803 var dt = new Date('5/4/06');
19804 dateField.setValue(dt);
19805
19806 //Pass a date string (default format):
19807 dateField.setValue('5/4/06');
19808
19809 //Pass a date string (custom format):
19810 dateField.format = 'Y-m-d';
19811 dateField.setValue('2006-5-4');
19812 </code></pre>
19813      * @param {String/Date} date The date or valid date string
19814      */
19815     setValue : function(date){
19816         if (this.hiddenField) {
19817             this.hiddenField.value = this.formatDate(this.parseDate(date), 'Y-m-d');
19818         }
19819         Roo.form.DateField.superclass.setValue.call(this, this.formatDate(this.parseDate(date)));
19820         // make sure the value field is always stored as a date..
19821         this.value = this.parseDate(date);
19822         
19823         
19824     },
19825
19826     // private
19827     parseDate : function(value){
19828                 
19829                 if (value instanceof Date) {
19830                         if (value < Date.parseDate(this.zeroValue, 'Y-m-d') ) {
19831                                 return  '';
19832                         }
19833                         return value;
19834                 }
19835                 
19836                 
19837         if(!value || value instanceof Date){
19838             return value;
19839         }
19840         var v = Date.parseDate(value, this.format);
19841          if (!v && this.useIso) {
19842             v = Date.parseDate(value, 'Y-m-d');
19843         }
19844         if(!v && this.altFormats){
19845             if(!this.altFormatsArray){
19846                 this.altFormatsArray = this.altFormats.split("|");
19847             }
19848             for(var i = 0, len = this.altFormatsArray.length; i < len && !v; i++){
19849                 v = Date.parseDate(value, this.altFormatsArray[i]);
19850             }
19851         }
19852                 if (v < Date.parseDate(this.zeroValue, 'Y-m-d') ) {
19853                         v = '';
19854                 }
19855         return v;
19856     },
19857
19858     // private
19859     formatDate : function(date, fmt){
19860         return (!date || !(date instanceof Date)) ?
19861                date : date.dateFormat(fmt || this.format);
19862     },
19863
19864     // private
19865     menuListeners : {
19866         select: function(m, d){
19867             
19868             this.setValue(d);
19869             this.fireEvent('select', this, d);
19870         },
19871         show : function(){ // retain focus styling
19872             this.onFocus();
19873         },
19874         hide : function(){
19875             this.focus.defer(10, this);
19876             var ml = this.menuListeners;
19877             this.menu.un("select", ml.select,  this);
19878             this.menu.un("show", ml.show,  this);
19879             this.menu.un("hide", ml.hide,  this);
19880         }
19881     },
19882
19883     // private
19884     // Implements the default empty TriggerField.onTriggerClick function to display the DatePicker
19885     onTriggerClick : function(){
19886         if(this.disabled || this.readOnly){
19887             return;
19888         }
19889         if(this.menu == null){
19890             this.menu = new Roo.menu.DateMenu();
19891         }
19892         Roo.apply(this.menu.picker,  {
19893             showClear: this.allowBlank,
19894             minDate : this.minValue,
19895             maxDate : this.maxValue,
19896             disabledDatesRE : this.ddMatch,
19897             disabledDatesText : this.disabledDatesText,
19898             disabledDays : this.disabledDays,
19899             disabledDaysText : this.disabledDaysText,
19900             format : this.useIso ? 'Y-m-d' : this.format,
19901             minText : String.format(this.minText, this.formatDate(this.minValue)),
19902             maxText : String.format(this.maxText, this.formatDate(this.maxValue))
19903         });
19904         this.menu.on(Roo.apply({}, this.menuListeners, {
19905             scope:this
19906         }));
19907         this.menu.picker.setValue(this.getValue() || new Date());
19908         this.menu.show(this.el, "tl-bl?");
19909     },
19910
19911     beforeBlur : function(){
19912         var v = this.parseDate(this.getRawValue());
19913         if(v){
19914             this.setValue(v);
19915         }
19916     },
19917
19918     /*@
19919      * overide
19920      * 
19921      */
19922     isDirty : function() {
19923         if(this.disabled) {
19924             return false;
19925         }
19926         
19927         if(typeof(this.startValue) === 'undefined'){
19928             return false;
19929         }
19930         
19931         return String(this.getValue()) !== String(this.startValue);
19932         
19933     },
19934     // @overide
19935     cleanLeadingSpace : function(e)
19936     {
19937        return;
19938     }
19939     
19940 });/*
19941  * Based on:
19942  * Ext JS Library 1.1.1
19943  * Copyright(c) 2006-2007, Ext JS, LLC.
19944  *
19945  * Originally Released Under LGPL - original licence link has changed is not relivant.
19946  *
19947  * Fork - LGPL
19948  * <script type="text/javascript">
19949  */
19950  
19951 /**
19952  * @class Roo.form.MonthField
19953  * @extends Roo.form.TriggerField
19954  * Provides a date input field with a {@link Roo.DatePicker} dropdown and automatic date validation.
19955 * @constructor
19956 * Create a new MonthField
19957 * @param {Object} config
19958  */
19959 Roo.form.MonthField = function(config){
19960     
19961     Roo.form.MonthField.superclass.constructor.call(this, config);
19962     
19963       this.addEvents({
19964          
19965         /**
19966          * @event select
19967          * Fires when a date is selected
19968              * @param {Roo.form.MonthFieeld} combo This combo box
19969              * @param {Date} date The date selected
19970              */
19971         'select' : true
19972          
19973     });
19974     
19975     
19976     if(typeof this.minValue == "string") {
19977         this.minValue = this.parseDate(this.minValue);
19978     }
19979     if(typeof this.maxValue == "string") {
19980         this.maxValue = this.parseDate(this.maxValue);
19981     }
19982     this.ddMatch = null;
19983     if(this.disabledDates){
19984         var dd = this.disabledDates;
19985         var re = "(?:";
19986         for(var i = 0; i < dd.length; i++){
19987             re += dd[i];
19988             if(i != dd.length-1) {
19989                 re += "|";
19990             }
19991         }
19992         this.ddMatch = new RegExp(re + ")");
19993     }
19994 };
19995
19996 Roo.extend(Roo.form.MonthField, Roo.form.TriggerField,  {
19997     /**
19998      * @cfg {String} format
19999      * The default date format string which can be overriden for localization support.  The format must be
20000      * valid according to {@link Date#parseDate} (defaults to 'm/d/y').
20001      */
20002     format : "M Y",
20003     /**
20004      * @cfg {String} altFormats
20005      * Multiple date formats separated by "|" to try when parsing a user input value and it doesn't match the defined
20006      * format (defaults to 'm/d/Y|m-d-y|m-d-Y|m/d|m-d|d').
20007      */
20008     altFormats : "M Y|m/Y|m-y|m-Y|my|mY",
20009     /**
20010      * @cfg {Array} disabledDays
20011      * An array of days to disable, 0 based. For example, [0, 6] disables Sunday and Saturday (defaults to null).
20012      */
20013     disabledDays : [0,1,2,3,4,5,6],
20014     /**
20015      * @cfg {String} disabledDaysText
20016      * The tooltip to display when the date falls on a disabled day (defaults to 'Disabled')
20017      */
20018     disabledDaysText : "Disabled",
20019     /**
20020      * @cfg {Array} disabledDates
20021      * An array of "dates" to disable, as strings. These strings will be used to build a dynamic regular
20022      * expression so they are very powerful. Some examples:
20023      * <ul>
20024      * <li>["03/08/2003", "09/16/2003"] would disable those exact dates</li>
20025      * <li>["03/08", "09/16"] would disable those days for every year</li>
20026      * <li>["^03/08"] would only match the beginning (useful if you are using short years)</li>
20027      * <li>["03/../2006"] would disable every day in March 2006</li>
20028      * <li>["^03"] would disable every day in every March</li>
20029      * </ul>
20030      * In order to support regular expressions, if you are using a date format that has "." in it, you will have to
20031      * escape the dot when restricting dates. For example: ["03\\.08\\.03"].
20032      */
20033     disabledDates : null,
20034     /**
20035      * @cfg {String} disabledDatesText
20036      * The tooltip text to display when the date falls on a disabled date (defaults to 'Disabled')
20037      */
20038     disabledDatesText : "Disabled",
20039     /**
20040      * @cfg {Date/String} minValue
20041      * The minimum allowed date. Can be either a Javascript date object or a string date in a
20042      * valid format (defaults to null).
20043      */
20044     minValue : null,
20045     /**
20046      * @cfg {Date/String} maxValue
20047      * The maximum allowed date. Can be either a Javascript date object or a string date in a
20048      * valid format (defaults to null).
20049      */
20050     maxValue : null,
20051     /**
20052      * @cfg {String} minText
20053      * The error text to display when the date in the cell is before minValue (defaults to
20054      * 'The date in this field must be after {minValue}').
20055      */
20056     minText : "The date in this field must be equal to or after {0}",
20057     /**
20058      * @cfg {String} maxTextf
20059      * The error text to display when the date in the cell is after maxValue (defaults to
20060      * 'The date in this field must be before {maxValue}').
20061      */
20062     maxText : "The date in this field must be equal to or before {0}",
20063     /**
20064      * @cfg {String} invalidText
20065      * The error text to display when the date in the field is invalid (defaults to
20066      * '{value} is not a valid date - it must be in the format {format}').
20067      */
20068     invalidText : "{0} is not a valid date - it must be in the format {1}",
20069     /**
20070      * @cfg {String} triggerClass
20071      * An additional CSS class used to style the trigger button.  The trigger will always get the
20072      * class 'x-form-trigger' and triggerClass will be <b>appended</b> if specified (defaults to 'x-form-date-trigger'
20073      * which displays a calendar icon).
20074      */
20075     triggerClass : 'x-form-date-trigger',
20076     
20077
20078     /**
20079      * @cfg {Boolean} useIso
20080      * if enabled, then the date field will use a hidden field to store the 
20081      * real value as iso formated date. default (true)
20082      */ 
20083     useIso : true,
20084     /**
20085      * @cfg {String/Object} autoCreate
20086      * A DomHelper element spec, or true for a default element spec (defaults to
20087      * {tag: "input", type: "text", size: "10", autocomplete: "off"})
20088      */ 
20089     // private
20090     defaultAutoCreate : {tag: "input", type: "text", size: "10", autocomplete: "new-password"},
20091     
20092     // private
20093     hiddenField: false,
20094     
20095     hideMonthPicker : false,
20096     
20097     onRender : function(ct, position)
20098     {
20099         Roo.form.MonthField.superclass.onRender.call(this, ct, position);
20100         if (this.useIso) {
20101             this.el.dom.removeAttribute('name'); 
20102             this.hiddenField = this.el.insertSibling({ tag:'input', type:'hidden', name: this.name },
20103                     'before', true);
20104             this.hiddenField.value = this.value ? this.formatDate(this.value, 'Y-m-d') : '';
20105             // prevent input submission
20106             this.hiddenName = this.name;
20107         }
20108             
20109             
20110     },
20111     
20112     // private
20113     validateValue : function(value)
20114     {
20115         value = this.formatDate(value);
20116         if(!Roo.form.MonthField.superclass.validateValue.call(this, value)){
20117             return false;
20118         }
20119         if(value.length < 1){ // if it's blank and textfield didn't flag it then it's valid
20120              return true;
20121         }
20122         var svalue = value;
20123         value = this.parseDate(value);
20124         if(!value){
20125             this.markInvalid(String.format(this.invalidText, svalue, this.format));
20126             return false;
20127         }
20128         var time = value.getTime();
20129         if(this.minValue && time < this.minValue.getTime()){
20130             this.markInvalid(String.format(this.minText, this.formatDate(this.minValue)));
20131             return false;
20132         }
20133         if(this.maxValue && time > this.maxValue.getTime()){
20134             this.markInvalid(String.format(this.maxText, this.formatDate(this.maxValue)));
20135             return false;
20136         }
20137         /*if(this.disabledDays){
20138             var day = value.getDay();
20139             for(var i = 0; i < this.disabledDays.length; i++) {
20140                 if(day === this.disabledDays[i]){
20141                     this.markInvalid(this.disabledDaysText);
20142                     return false;
20143                 }
20144             }
20145         }
20146         */
20147         var fvalue = this.formatDate(value);
20148         /*if(this.ddMatch && this.ddMatch.test(fvalue)){
20149             this.markInvalid(String.format(this.disabledDatesText, fvalue));
20150             return false;
20151         }
20152         */
20153         return true;
20154     },
20155
20156     // private
20157     // Provides logic to override the default TriggerField.validateBlur which just returns true
20158     validateBlur : function(){
20159         return !this.menu || !this.menu.isVisible();
20160     },
20161
20162     /**
20163      * Returns the current date value of the date field.
20164      * @return {Date} The date value
20165      */
20166     getValue : function(){
20167         
20168         
20169         
20170         return  this.hiddenField ?
20171                 this.hiddenField.value :
20172                 this.parseDate(Roo.form.MonthField.superclass.getValue.call(this)) || "";
20173     },
20174
20175     /**
20176      * Sets the value of the date field.  You can pass a date object or any string that can be parsed into a valid
20177      * date, using MonthField.format as the date format, according to the same rules as {@link Date#parseDate}
20178      * (the default format used is "m/d/y").
20179      * <br />Usage:
20180      * <pre><code>
20181 //All of these calls set the same date value (May 4, 2006)
20182
20183 //Pass a date object:
20184 var dt = new Date('5/4/06');
20185 monthField.setValue(dt);
20186
20187 //Pass a date string (default format):
20188 monthField.setValue('5/4/06');
20189
20190 //Pass a date string (custom format):
20191 monthField.format = 'Y-m-d';
20192 monthField.setValue('2006-5-4');
20193 </code></pre>
20194      * @param {String/Date} date The date or valid date string
20195      */
20196     setValue : function(date){
20197         Roo.log('month setValue' + date);
20198         // can only be first of month..
20199         
20200         var val = this.parseDate(date);
20201         
20202         if (this.hiddenField) {
20203             this.hiddenField.value = this.formatDate(this.parseDate(date), 'Y-m-d');
20204         }
20205         Roo.form.MonthField.superclass.setValue.call(this, this.formatDate(this.parseDate(date)));
20206         this.value = this.parseDate(date);
20207     },
20208
20209     // private
20210     parseDate : function(value){
20211         if(!value || value instanceof Date){
20212             value = value ? Date.parseDate(value.format('Y-m') + '-01', 'Y-m-d') : null;
20213             return value;
20214         }
20215         var v = Date.parseDate(value, this.format);
20216         if (!v && this.useIso) {
20217             v = Date.parseDate(value, 'Y-m-d');
20218         }
20219         if (v) {
20220             // 
20221             v = Date.parseDate(v.format('Y-m') +'-01', 'Y-m-d');
20222         }
20223         
20224         
20225         if(!v && this.altFormats){
20226             if(!this.altFormatsArray){
20227                 this.altFormatsArray = this.altFormats.split("|");
20228             }
20229             for(var i = 0, len = this.altFormatsArray.length; i < len && !v; i++){
20230                 v = Date.parseDate(value, this.altFormatsArray[i]);
20231             }
20232         }
20233         return v;
20234     },
20235
20236     // private
20237     formatDate : function(date, fmt){
20238         return (!date || !(date instanceof Date)) ?
20239                date : date.dateFormat(fmt || this.format);
20240     },
20241
20242     // private
20243     menuListeners : {
20244         select: function(m, d){
20245             this.setValue(d);
20246             this.fireEvent('select', this, d);
20247         },
20248         show : function(){ // retain focus styling
20249             this.onFocus();
20250         },
20251         hide : function(){
20252             this.focus.defer(10, this);
20253             var ml = this.menuListeners;
20254             this.menu.un("select", ml.select,  this);
20255             this.menu.un("show", ml.show,  this);
20256             this.menu.un("hide", ml.hide,  this);
20257         }
20258     },
20259     // private
20260     // Implements the default empty TriggerField.onTriggerClick function to display the DatePicker
20261     onTriggerClick : function(){
20262         if(this.disabled){
20263             return;
20264         }
20265         if(this.menu == null){
20266             this.menu = new Roo.menu.DateMenu();
20267            
20268         }
20269         
20270         Roo.apply(this.menu.picker,  {
20271             
20272             showClear: this.allowBlank,
20273             minDate : this.minValue,
20274             maxDate : this.maxValue,
20275             disabledDatesRE : this.ddMatch,
20276             disabledDatesText : this.disabledDatesText,
20277             
20278             format : this.useIso ? 'Y-m-d' : this.format,
20279             minText : String.format(this.minText, this.formatDate(this.minValue)),
20280             maxText : String.format(this.maxText, this.formatDate(this.maxValue))
20281             
20282         });
20283          this.menu.on(Roo.apply({}, this.menuListeners, {
20284             scope:this
20285         }));
20286        
20287         
20288         var m = this.menu;
20289         var p = m.picker;
20290         
20291         // hide month picker get's called when we called by 'before hide';
20292         
20293         var ignorehide = true;
20294         p.hideMonthPicker  = function(disableAnim){
20295             if (ignorehide) {
20296                 return;
20297             }
20298              if(this.monthPicker){
20299                 Roo.log("hideMonthPicker called");
20300                 if(disableAnim === true){
20301                     this.monthPicker.hide();
20302                 }else{
20303                     this.monthPicker.slideOut('t', {duration:.2});
20304                     p.setValue(new Date(m.picker.mpSelYear, m.picker.mpSelMonth, 1));
20305                     p.fireEvent("select", this, this.value);
20306                     m.hide();
20307                 }
20308             }
20309         }
20310         
20311         Roo.log('picker set value');
20312         Roo.log(this.getValue());
20313         p.setValue(this.getValue() ? this.parseDate(this.getValue()) : new Date());
20314         m.show(this.el, 'tl-bl?');
20315         ignorehide  = false;
20316         // this will trigger hideMonthPicker..
20317         
20318         
20319         // hidden the day picker
20320         Roo.select('.x-date-picker table', true).first().dom.style.visibility = "hidden";
20321         
20322         
20323         
20324       
20325         
20326         p.showMonthPicker.defer(100, p);
20327     
20328         
20329        
20330     },
20331
20332     beforeBlur : function(){
20333         var v = this.parseDate(this.getRawValue());
20334         if(v){
20335             this.setValue(v);
20336         }
20337     }
20338
20339     /** @cfg {Boolean} grow @hide */
20340     /** @cfg {Number} growMin @hide */
20341     /** @cfg {Number} growMax @hide */
20342     /**
20343      * @hide
20344      * @method autoSize
20345      */
20346 });/*
20347  * Based on:
20348  * Ext JS Library 1.1.1
20349  * Copyright(c) 2006-2007, Ext JS, LLC.
20350  *
20351  * Originally Released Under LGPL - original licence link has changed is not relivant.
20352  *
20353  * Fork - LGPL
20354  * <script type="text/javascript">
20355  */
20356  
20357
20358 /**
20359  * @class Roo.form.ComboBox
20360  * @extends Roo.form.TriggerField
20361  * A combobox control with support for autocomplete, remote-loading, paging and many other features.
20362  * @constructor
20363  * Create a new ComboBox.
20364  * @param {Object} config Configuration options
20365  */
20366 Roo.form.ComboBox = function(config){
20367     Roo.form.ComboBox.superclass.constructor.call(this, config);
20368     this.addEvents({
20369         /**
20370          * @event expand
20371          * Fires when the dropdown list is expanded
20372              * @param {Roo.form.ComboBox} combo This combo box
20373              */
20374         'expand' : true,
20375         /**
20376          * @event collapse
20377          * Fires when the dropdown list is collapsed
20378              * @param {Roo.form.ComboBox} combo This combo box
20379              */
20380         'collapse' : true,
20381         /**
20382          * @event beforeselect
20383          * Fires before a list item is selected. Return false to cancel the selection.
20384              * @param {Roo.form.ComboBox} combo This combo box
20385              * @param {Roo.data.Record} record The data record returned from the underlying store
20386              * @param {Number} index The index of the selected item in the dropdown list
20387              */
20388         'beforeselect' : true,
20389         /**
20390          * @event select
20391          * Fires when a list item is selected
20392              * @param {Roo.form.ComboBox} combo This combo box
20393              * @param {Roo.data.Record} record The data record returned from the underlying store (or false on clear)
20394              * @param {Number} index The index of the selected item in the dropdown list
20395              */
20396         'select' : true,
20397         /**
20398          * @event beforequery
20399          * Fires before all queries are processed. Return false to cancel the query or set cancel to true.
20400          * The event object passed has these properties:
20401              * @param {Roo.form.ComboBox} combo This combo box
20402              * @param {String} query The query
20403              * @param {Boolean} forceAll true to force "all" query
20404              * @param {Boolean} cancel true to cancel the query
20405              * @param {Object} e The query event object
20406              */
20407         'beforequery': true,
20408          /**
20409          * @event add
20410          * Fires when the 'add' icon is pressed (add a listener to enable add button)
20411              * @param {Roo.form.ComboBox} combo This combo box
20412              */
20413         'add' : true,
20414         /**
20415          * @event edit
20416          * Fires when the 'edit' icon is pressed (add a listener to enable add button)
20417              * @param {Roo.form.ComboBox} combo This combo box
20418              * @param {Roo.data.Record|false} record The data record returned from the underlying store (or false on nothing selected)
20419              */
20420         'edit' : true
20421         
20422         
20423     });
20424     if(this.transform){
20425         this.allowDomMove = false;
20426         var s = Roo.getDom(this.transform);
20427         if(!this.hiddenName){
20428             this.hiddenName = s.name;
20429         }
20430         if(!this.store){
20431             this.mode = 'local';
20432             var d = [], opts = s.options;
20433             for(var i = 0, len = opts.length;i < len; i++){
20434                 var o = opts[i];
20435                 var value = (Roo.isIE ? o.getAttributeNode('value').specified : o.hasAttribute('value')) ? o.value : o.text;
20436                 if(o.selected) {
20437                     this.value = value;
20438                 }
20439                 d.push([value, o.text]);
20440             }
20441             this.store = new Roo.data.SimpleStore({
20442                 'id': 0,
20443                 fields: ['value', 'text'],
20444                 data : d
20445             });
20446             this.valueField = 'value';
20447             this.displayField = 'text';
20448         }
20449         s.name = Roo.id(); // wipe out the name in case somewhere else they have a reference
20450         if(!this.lazyRender){
20451             this.target = true;
20452             this.el = Roo.DomHelper.insertBefore(s, this.autoCreate || this.defaultAutoCreate);
20453             s.parentNode.removeChild(s); // remove it
20454             this.render(this.el.parentNode);
20455         }else{
20456             s.parentNode.removeChild(s); // remove it
20457         }
20458
20459     }
20460     if (this.store) {
20461         this.store = Roo.factory(this.store, Roo.data);
20462     }
20463     
20464     this.selectedIndex = -1;
20465     if(this.mode == 'local'){
20466         if(config.queryDelay === undefined){
20467             this.queryDelay = 10;
20468         }
20469         if(config.minChars === undefined){
20470             this.minChars = 0;
20471         }
20472     }
20473 };
20474
20475 Roo.extend(Roo.form.ComboBox, Roo.form.TriggerField, {
20476     /**
20477      * @cfg {String/HTMLElement/Element} transform The id, DOM node or element of an existing select to convert to a ComboBox
20478      */
20479     /**
20480      * @cfg {Boolean} lazyRender True to prevent the ComboBox from rendering until requested (should always be used when
20481      * rendering into an Roo.Editor, defaults to false)
20482      */
20483     /**
20484      * @cfg {Boolean/Object} autoCreate A DomHelper element spec, or true for a default element spec (defaults to:
20485      * {tag: "input", type: "text", size: "24", autocomplete: "off"})
20486      */
20487     /**
20488      * @cfg {Roo.data.Store} store The data store to which this combo is bound (defaults to undefined)
20489      */
20490     /**
20491      * @cfg {String} title If supplied, a header element is created containing this text and added into the top of
20492      * the dropdown list (defaults to undefined, with no header element)
20493      */
20494
20495      /**
20496      * @cfg {String/Roo.Template} tpl The template to use to render the output
20497      */
20498      
20499     // private
20500     defaultAutoCreate : {tag: "input", type: "text", size: "24", autocomplete: "off"},
20501     /**
20502      * @cfg {Number} listWidth The width in pixels of the dropdown list (defaults to the width of the ComboBox field)
20503      */
20504     listWidth: undefined,
20505     /**
20506      * @cfg {String} displayField The underlying data field name to bind to this CombBox (defaults to undefined if
20507      * mode = 'remote' or 'text' if mode = 'local')
20508      */
20509     displayField: undefined,
20510     /**
20511      * @cfg {String} valueField The underlying data value name to bind to this CombBox (defaults to undefined if
20512      * mode = 'remote' or 'value' if mode = 'local'). 
20513      * Note: use of a valueField requires the user make a selection
20514      * in order for a value to be mapped.
20515      */
20516     valueField: undefined,
20517     
20518     
20519     /**
20520      * @cfg {String} hiddenName If specified, a hidden form field with this name is dynamically generated to store the
20521      * field's data value (defaults to the underlying DOM element's name)
20522      */
20523     hiddenName: undefined,
20524     /**
20525      * @cfg {String} listClass CSS class to apply to the dropdown list element (defaults to '')
20526      */
20527     listClass: '',
20528     /**
20529      * @cfg {String} selectedClass CSS class to apply to the selected item in the dropdown list (defaults to 'x-combo-selected')
20530      */
20531     selectedClass: 'x-combo-selected',
20532     /**
20533      * @cfg {String} triggerClass An additional CSS class used to style the trigger button.  The trigger will always get the
20534      * class 'x-form-trigger' and triggerClass will be <b>appended</b> if specified (defaults to 'x-form-arrow-trigger'
20535      * which displays a downward arrow icon).
20536      */
20537     triggerClass : 'x-form-arrow-trigger',
20538     /**
20539      * @cfg {Boolean/String} shadow True or "sides" for the default effect, "frame" for 4-way shadow, and "drop" for bottom-right
20540      */
20541     shadow:'sides',
20542     /**
20543      * @cfg {String} listAlign A valid anchor position value. See {@link Roo.Element#alignTo} for details on supported
20544      * anchor positions (defaults to 'tl-bl')
20545      */
20546     listAlign: 'tl-bl?',
20547     /**
20548      * @cfg {Number} maxHeight The maximum height in pixels of the dropdown list before scrollbars are shown (defaults to 300)
20549      */
20550     maxHeight: 300,
20551     /**
20552      * @cfg {String} triggerAction The action to execute when the trigger field is activated.  Use 'all' to run the
20553      * query specified by the allQuery config option (defaults to 'query')
20554      */
20555     triggerAction: 'query',
20556     /**
20557      * @cfg {Number} minChars The minimum number of characters the user must type before autocomplete and typeahead activate
20558      * (defaults to 4, does not apply if editable = false)
20559      */
20560     minChars : 4,
20561     /**
20562      * @cfg {Boolean} typeAhead True to populate and autoselect the remainder of the text being typed after a configurable
20563      * delay (typeAheadDelay) if it matches a known value (defaults to false)
20564      */
20565     typeAhead: false,
20566     /**
20567      * @cfg {Number} queryDelay The length of time in milliseconds to delay between the start of typing and sending the
20568      * query to filter the dropdown list (defaults to 500 if mode = 'remote' or 10 if mode = 'local')
20569      */
20570     queryDelay: 500,
20571     /**
20572      * @cfg {Number} pageSize If greater than 0, a paging toolbar is displayed in the footer of the dropdown list and the
20573      * filter queries will execute with page start and limit parameters.  Only applies when mode = 'remote' (defaults to 0)
20574      */
20575     pageSize: 0,
20576     /**
20577      * @cfg {Boolean} selectOnFocus True to select any existing text in the field immediately on focus.  Only applies
20578      * when editable = true (defaults to false)
20579      */
20580     selectOnFocus:false,
20581     /**
20582      * @cfg {String} queryParam Name of the query as it will be passed on the querystring (defaults to 'query')
20583      */
20584     queryParam: 'query',
20585     /**
20586      * @cfg {String} loadingText The text to display in the dropdown list while data is loading.  Only applies
20587      * when mode = 'remote' (defaults to 'Loading...')
20588      */
20589     loadingText: 'Loading...',
20590     /**
20591      * @cfg {Boolean} resizable True to add a resize handle to the bottom of the dropdown list (defaults to false)
20592      */
20593     resizable: false,
20594     /**
20595      * @cfg {Number} handleHeight The height in pixels of the dropdown list resize handle if resizable = true (defaults to 8)
20596      */
20597     handleHeight : 8,
20598     /**
20599      * @cfg {Boolean} editable False to prevent the user from typing text directly into the field, just like a
20600      * traditional select (defaults to true)
20601      */
20602     editable: true,
20603     /**
20604      * @cfg {String} allQuery The text query to send to the server to return all records for the list with no filtering (defaults to '')
20605      */
20606     allQuery: '',
20607     /**
20608      * @cfg {String} mode Set to 'local' if the ComboBox loads local data (defaults to 'remote' which loads from the server)
20609      */
20610     mode: 'remote',
20611     /**
20612      * @cfg {Number} minListWidth The minimum width of the dropdown list in pixels (defaults to 70, will be ignored if
20613      * listWidth has a higher value)
20614      */
20615     minListWidth : 70,
20616     /**
20617      * @cfg {Boolean} forceSelection True to restrict the selected value to one of the values in the list, false to
20618      * allow the user to set arbitrary text into the field (defaults to false)
20619      */
20620     forceSelection:false,
20621     /**
20622      * @cfg {Number} typeAheadDelay The length of time in milliseconds to wait until the typeahead text is displayed
20623      * if typeAhead = true (defaults to 250)
20624      */
20625     typeAheadDelay : 250,
20626     /**
20627      * @cfg {String} valueNotFoundText When using a name/value combo, if the value passed to setValue is not found in
20628      * the store, valueNotFoundText will be displayed as the field text if defined (defaults to undefined)
20629      */
20630     valueNotFoundText : undefined,
20631     /**
20632      * @cfg {Boolean} blockFocus Prevents all focus calls, so it can work with things like HTML edtor bar
20633      */
20634     blockFocus : false,
20635     
20636     /**
20637      * @cfg {Boolean} disableClear Disable showing of clear button.
20638      */
20639     disableClear : false,
20640     /**
20641      * @cfg {Boolean} alwaysQuery  Disable caching of results, and always send query
20642      */
20643     alwaysQuery : false,
20644     
20645     //private
20646     addicon : false,
20647     editicon: false,
20648     
20649     // element that contains real text value.. (when hidden is used..)
20650      
20651     // private
20652     onRender : function(ct, position)
20653     {
20654         Roo.form.ComboBox.superclass.onRender.call(this, ct, position);
20655         
20656                 if(this.hiddenName){
20657             this.hiddenField = this.el.insertSibling({tag:'input', type:'hidden', name: this.hiddenName, id:  (this.hiddenId||this.hiddenName)},
20658                     'before', true);
20659             this.hiddenField.value =
20660                 this.hiddenValue !== undefined ? this.hiddenValue :
20661                 this.value !== undefined ? this.value : '';
20662
20663             // prevent input submission
20664             this.el.dom.removeAttribute('name');
20665              
20666              
20667         }
20668         
20669         if(Roo.isGecko){
20670             this.el.dom.setAttribute('autocomplete', 'off');
20671         }
20672
20673         var cls = 'x-combo-list';
20674
20675         this.list = new Roo.Layer({
20676             shadow: this.shadow, cls: [cls, this.listClass].join(' '), constrain:false
20677         });
20678
20679         var lw = this.listWidth || Math.max(this.wrap.getWidth(), this.minListWidth);
20680         this.list.setWidth(lw);
20681         this.list.swallowEvent('mousewheel');
20682         this.assetHeight = 0;
20683
20684         if(this.title){
20685             this.header = this.list.createChild({cls:cls+'-hd', html: this.title});
20686             this.assetHeight += this.header.getHeight();
20687         }
20688
20689         this.innerList = this.list.createChild({cls:cls+'-inner'});
20690         this.innerList.on('mouseover', this.onViewOver, this);
20691         this.innerList.on('mousemove', this.onViewMove, this);
20692         this.innerList.setWidth(lw - this.list.getFrameWidth('lr'));
20693         
20694         if(this.allowBlank && !this.pageSize && !this.disableClear){
20695             this.footer = this.list.createChild({cls:cls+'-ft'});
20696             this.pageTb = new Roo.Toolbar(this.footer);
20697            
20698         }
20699         if(this.pageSize){
20700             this.footer = this.list.createChild({cls:cls+'-ft'});
20701             this.pageTb = new Roo.PagingToolbar(this.footer, this.store,
20702                     {pageSize: this.pageSize});
20703             
20704         }
20705         
20706         if (this.pageTb && this.allowBlank && !this.disableClear) {
20707             var _this = this;
20708             this.pageTb.add(new Roo.Toolbar.Fill(), {
20709                 cls: 'x-btn-icon x-btn-clear',
20710                 text: '&#160;',
20711                 handler: function()
20712                 {
20713                     _this.collapse();
20714                     _this.clearValue();
20715                     _this.onSelect(false, -1);
20716                 }
20717             });
20718         }
20719         if (this.footer) {
20720             this.assetHeight += this.footer.getHeight();
20721         }
20722         
20723
20724         if(!this.tpl){
20725             this.tpl = '<div class="'+cls+'-item">{' + this.displayField + '}</div>';
20726         }
20727
20728         this.view = new Roo.View(this.innerList, this.tpl, {
20729             singleSelect:true,
20730             store: this.store,
20731             selectedClass: this.selectedClass
20732         });
20733
20734         this.view.on('click', this.onViewClick, this);
20735
20736         this.store.on('beforeload', this.onBeforeLoad, this);
20737         this.store.on('load', this.onLoad, this);
20738         this.store.on('loadexception', this.onLoadException, this);
20739
20740         if(this.resizable){
20741             this.resizer = new Roo.Resizable(this.list,  {
20742                pinned:true, handles:'se'
20743             });
20744             this.resizer.on('resize', function(r, w, h){
20745                 this.maxHeight = h-this.handleHeight-this.list.getFrameWidth('tb')-this.assetHeight;
20746                 this.listWidth = w;
20747                 this.innerList.setWidth(w - this.list.getFrameWidth('lr'));
20748                 this.restrictHeight();
20749             }, this);
20750             this[this.pageSize?'footer':'innerList'].setStyle('margin-bottom', this.handleHeight+'px');
20751         }
20752         if(!this.editable){
20753             this.editable = true;
20754             this.setEditable(false);
20755         }  
20756         
20757         
20758         if (typeof(this.events.add.listeners) != 'undefined') {
20759             
20760             this.addicon = this.wrap.createChild(
20761                 {tag: 'img', src: Roo.BLANK_IMAGE_URL, cls: 'x-form-combo-add' });  
20762        
20763             this.addicon.on('click', function(e) {
20764                 this.fireEvent('add', this);
20765             }, this);
20766         }
20767         if (typeof(this.events.edit.listeners) != 'undefined') {
20768             
20769             this.editicon = this.wrap.createChild(
20770                 {tag: 'img', src: Roo.BLANK_IMAGE_URL, cls: 'x-form-combo-edit' });  
20771             if (this.addicon) {
20772                 this.editicon.setStyle('margin-left', '40px');
20773             }
20774             this.editicon.on('click', function(e) {
20775                 
20776                 // we fire even  if inothing is selected..
20777                 this.fireEvent('edit', this, this.lastData );
20778                 
20779             }, this);
20780         }
20781         
20782         
20783         
20784     },
20785
20786     // private
20787     initEvents : function(){
20788         Roo.form.ComboBox.superclass.initEvents.call(this);
20789
20790         this.keyNav = new Roo.KeyNav(this.el, {
20791             "up" : function(e){
20792                 this.inKeyMode = true;
20793                 this.selectPrev();
20794             },
20795
20796             "down" : function(e){
20797                 if(!this.isExpanded()){
20798                     this.onTriggerClick();
20799                 }else{
20800                     this.inKeyMode = true;
20801                     this.selectNext();
20802                 }
20803             },
20804
20805             "enter" : function(e){
20806                 this.onViewClick();
20807                 //return true;
20808             },
20809
20810             "esc" : function(e){
20811                 this.collapse();
20812             },
20813
20814             "tab" : function(e){
20815                 this.onViewClick(false);
20816                 this.fireEvent("specialkey", this, e);
20817                 return true;
20818             },
20819
20820             scope : this,
20821
20822             doRelay : function(foo, bar, hname){
20823                 if(hname == 'down' || this.scope.isExpanded()){
20824                    return Roo.KeyNav.prototype.doRelay.apply(this, arguments);
20825                 }
20826                 return true;
20827             },
20828
20829             forceKeyDown: true
20830         });
20831         this.queryDelay = Math.max(this.queryDelay || 10,
20832                 this.mode == 'local' ? 10 : 250);
20833         this.dqTask = new Roo.util.DelayedTask(this.initQuery, this);
20834         if(this.typeAhead){
20835             this.taTask = new Roo.util.DelayedTask(this.onTypeAhead, this);
20836         }
20837         if(this.editable !== false){
20838             this.el.on("keyup", this.onKeyUp, this);
20839         }
20840         if(this.forceSelection){
20841             this.on('blur', this.doForce, this);
20842         }
20843     },
20844
20845     onDestroy : function(){
20846         if(this.view){
20847             this.view.setStore(null);
20848             this.view.el.removeAllListeners();
20849             this.view.el.remove();
20850             this.view.purgeListeners();
20851         }
20852         if(this.list){
20853             this.list.destroy();
20854         }
20855         if(this.store){
20856             this.store.un('beforeload', this.onBeforeLoad, this);
20857             this.store.un('load', this.onLoad, this);
20858             this.store.un('loadexception', this.onLoadException, this);
20859         }
20860         Roo.form.ComboBox.superclass.onDestroy.call(this);
20861     },
20862
20863     // private
20864     fireKey : function(e){
20865         if(e.isNavKeyPress() && !this.list.isVisible()){
20866             this.fireEvent("specialkey", this, e);
20867         }
20868     },
20869
20870     // private
20871     onResize: function(w, h){
20872         Roo.form.ComboBox.superclass.onResize.apply(this, arguments);
20873         
20874         if(typeof w != 'number'){
20875             // we do not handle it!?!?
20876             return;
20877         }
20878         var tw = this.trigger.getWidth();
20879         tw += this.addicon ? this.addicon.getWidth() : 0;
20880         tw += this.editicon ? this.editicon.getWidth() : 0;
20881         var x = w - tw;
20882         this.el.setWidth( this.adjustWidth('input', x));
20883             
20884         this.trigger.setStyle('left', x+'px');
20885         
20886         if(this.list && this.listWidth === undefined){
20887             var lw = Math.max(x + this.trigger.getWidth(), this.minListWidth);
20888             this.list.setWidth(lw);
20889             this.innerList.setWidth(lw - this.list.getFrameWidth('lr'));
20890         }
20891         
20892     
20893         
20894     },
20895
20896     /**
20897      * Allow or prevent the user from directly editing the field text.  If false is passed,
20898      * the user will only be able to select from the items defined in the dropdown list.  This method
20899      * is the runtime equivalent of setting the 'editable' config option at config time.
20900      * @param {Boolean} value True to allow the user to directly edit the field text
20901      */
20902     setEditable : function(value){
20903         if(value == this.editable){
20904             return;
20905         }
20906         this.editable = value;
20907         if(!value){
20908             this.el.dom.setAttribute('readOnly', true);
20909             this.el.on('mousedown', this.onTriggerClick,  this);
20910             this.el.addClass('x-combo-noedit');
20911         }else{
20912             this.el.dom.setAttribute('readOnly', false);
20913             this.el.un('mousedown', this.onTriggerClick,  this);
20914             this.el.removeClass('x-combo-noedit');
20915         }
20916     },
20917
20918     // private
20919     onBeforeLoad : function(){
20920         if(!this.hasFocus){
20921             return;
20922         }
20923         this.innerList.update(this.loadingText ?
20924                '<div class="loading-indicator">'+this.loadingText+'</div>' : '');
20925         this.restrictHeight();
20926         this.selectedIndex = -1;
20927     },
20928
20929     // private
20930     onLoad : function(){
20931         if(!this.hasFocus){
20932             return;
20933         }
20934         if(this.store.getCount() > 0){
20935             this.expand();
20936             this.restrictHeight();
20937             if(this.lastQuery == this.allQuery){
20938                 if(this.editable){
20939                     this.el.dom.select();
20940                 }
20941                 if(!this.selectByValue(this.value, true)){
20942                     this.select(0, true);
20943                 }
20944             }else{
20945                 this.selectNext();
20946                 if(this.typeAhead && this.lastKey != Roo.EventObject.BACKSPACE && this.lastKey != Roo.EventObject.DELETE){
20947                     this.taTask.delay(this.typeAheadDelay);
20948                 }
20949             }
20950         }else{
20951             this.onEmptyResults();
20952         }
20953         //this.el.focus();
20954     },
20955     // private
20956     onLoadException : function()
20957     {
20958         this.collapse();
20959         Roo.log(this.store.reader.jsonData);
20960         if (this.store && typeof(this.store.reader.jsonData.errorMsg) != 'undefined') {
20961             Roo.MessageBox.alert("Error loading",this.store.reader.jsonData.errorMsg);
20962         }
20963         
20964         
20965     },
20966     // private
20967     onTypeAhead : function(){
20968         if(this.store.getCount() > 0){
20969             var r = this.store.getAt(0);
20970             var newValue = r.data[this.displayField];
20971             var len = newValue.length;
20972             var selStart = this.getRawValue().length;
20973             if(selStart != len){
20974                 this.setRawValue(newValue);
20975                 this.selectText(selStart, newValue.length);
20976             }
20977         }
20978     },
20979
20980     // private
20981     onSelect : function(record, index){
20982         if(this.fireEvent('beforeselect', this, record, index) !== false){
20983             this.setFromData(index > -1 ? record.data : false);
20984             this.collapse();
20985             this.fireEvent('select', this, record, index);
20986         }
20987     },
20988
20989     /**
20990      * Returns the currently selected field value or empty string if no value is set.
20991      * @return {String} value The selected value
20992      */
20993     getValue : function(){
20994         if(this.valueField){
20995             return typeof this.value != 'undefined' ? this.value : '';
20996         }
20997         return Roo.form.ComboBox.superclass.getValue.call(this);
20998     },
20999
21000     /**
21001      * Clears any text/value currently set in the field
21002      */
21003     clearValue : function(){
21004         if(this.hiddenField){
21005             this.hiddenField.value = '';
21006         }
21007         this.value = '';
21008         this.setRawValue('');
21009         this.lastSelectionText = '';
21010         
21011     },
21012
21013     /**
21014      * Sets the specified value into the field.  If the value finds a match, the corresponding record text
21015      * will be displayed in the field.  If the value does not match the data value of an existing item,
21016      * and the valueNotFoundText config option is defined, it will be displayed as the default field text.
21017      * Otherwise the field will be blank (although the value will still be set).
21018      * @param {String} value The value to match
21019      */
21020     setValue : function(v){
21021         var text = v;
21022         if(this.valueField){
21023             var r = this.findRecord(this.valueField, v);
21024             if(r){
21025                 text = r.data[this.displayField];
21026             }else if(this.valueNotFoundText !== undefined){
21027                 text = this.valueNotFoundText;
21028             }
21029         }
21030         this.lastSelectionText = text;
21031         if(this.hiddenField){
21032             this.hiddenField.value = v;
21033         }
21034         Roo.form.ComboBox.superclass.setValue.call(this, text);
21035         this.value = v;
21036     },
21037     /**
21038      * @property {Object} the last set data for the element
21039      */
21040     
21041     lastData : false,
21042     /**
21043      * Sets the value of the field based on a object which is related to the record format for the store.
21044      * @param {Object} value the value to set as. or false on reset?
21045      */
21046     setFromData : function(o){
21047         var dv = ''; // display value
21048         var vv = ''; // value value..
21049         this.lastData = o;
21050         if (this.displayField) {
21051             dv = !o || typeof(o[this.displayField]) == 'undefined' ? '' : o[this.displayField];
21052         } else {
21053             // this is an error condition!!!
21054             Roo.log('no  displayField value set for '+ (this.name ? this.name : this.id));
21055         }
21056         
21057         if(this.valueField){
21058             vv = !o || typeof(o[this.valueField]) == 'undefined' ? dv : o[this.valueField];
21059         }
21060         if(this.hiddenField){
21061             this.hiddenField.value = vv;
21062             
21063             this.lastSelectionText = dv;
21064             Roo.form.ComboBox.superclass.setValue.call(this, dv);
21065             this.value = vv;
21066             return;
21067         }
21068         // no hidden field.. - we store the value in 'value', but still display
21069         // display field!!!!
21070         this.lastSelectionText = dv;
21071         Roo.form.ComboBox.superclass.setValue.call(this, dv);
21072         this.value = vv;
21073         
21074         
21075     },
21076     // private
21077     reset : function(){
21078         // overridden so that last data is reset..
21079         this.setValue(this.resetValue);
21080         this.originalValue = this.getValue();
21081         this.clearInvalid();
21082         this.lastData = false;
21083         if (this.view) {
21084             this.view.clearSelections();
21085         }
21086     },
21087     // private
21088     findRecord : function(prop, value){
21089         var record;
21090         if(this.store.getCount() > 0){
21091             this.store.each(function(r){
21092                 if(r.data[prop] == value){
21093                     record = r;
21094                     return false;
21095                 }
21096                 return true;
21097             });
21098         }
21099         return record;
21100     },
21101     
21102     getName: function()
21103     {
21104         // returns hidden if it's set..
21105         if (!this.rendered) {return ''};
21106         return !this.hiddenName && this.el.dom.name  ? this.el.dom.name : (this.hiddenName || '');
21107         
21108     },
21109     // private
21110     onViewMove : function(e, t){
21111         this.inKeyMode = false;
21112     },
21113
21114     // private
21115     onViewOver : function(e, t){
21116         if(this.inKeyMode){ // prevent key nav and mouse over conflicts
21117             return;
21118         }
21119         var item = this.view.findItemFromChild(t);
21120         if(item){
21121             var index = this.view.indexOf(item);
21122             this.select(index, false);
21123         }
21124     },
21125
21126     // private
21127     onViewClick : function(doFocus)
21128     {
21129         var index = this.view.getSelectedIndexes()[0];
21130         var r = this.store.getAt(index);
21131         if(r){
21132             this.onSelect(r, index);
21133         }
21134         if(doFocus !== false && !this.blockFocus){
21135             this.el.focus();
21136         }
21137     },
21138
21139     // private
21140     restrictHeight : function(){
21141         this.innerList.dom.style.height = '';
21142         var inner = this.innerList.dom;
21143         var h = Math.max(inner.clientHeight, inner.offsetHeight, inner.scrollHeight);
21144         this.innerList.setHeight(h < this.maxHeight ? 'auto' : this.maxHeight);
21145         this.list.beginUpdate();
21146         this.list.setHeight(this.innerList.getHeight()+this.list.getFrameWidth('tb')+(this.resizable?this.handleHeight:0)+this.assetHeight);
21147         this.list.alignTo(this.el, this.listAlign);
21148         this.list.endUpdate();
21149     },
21150
21151     // private
21152     onEmptyResults : function(){
21153         this.collapse();
21154     },
21155
21156     /**
21157      * Returns true if the dropdown list is expanded, else false.
21158      */
21159     isExpanded : function(){
21160         return this.list.isVisible();
21161     },
21162
21163     /**
21164      * Select an item in the dropdown list by its data value. This function does NOT cause the select event to fire.
21165      * The store must be loaded and the list expanded for this function to work, otherwise use setValue.
21166      * @param {String} value The data value of the item to select
21167      * @param {Boolean} scrollIntoView False to prevent the dropdown list from autoscrolling to display the
21168      * selected item if it is not currently in view (defaults to true)
21169      * @return {Boolean} True if the value matched an item in the list, else false
21170      */
21171     selectByValue : function(v, scrollIntoView){
21172         if(v !== undefined && v !== null){
21173             var r = this.findRecord(this.valueField || this.displayField, v);
21174             if(r){
21175                 this.select(this.store.indexOf(r), scrollIntoView);
21176                 return true;
21177             }
21178         }
21179         return false;
21180     },
21181
21182     /**
21183      * Select an item in the dropdown list by its numeric index in the list. This function does NOT cause the select event to fire.
21184      * The store must be loaded and the list expanded for this function to work, otherwise use setValue.
21185      * @param {Number} index The zero-based index of the list item to select
21186      * @param {Boolean} scrollIntoView False to prevent the dropdown list from autoscrolling to display the
21187      * selected item if it is not currently in view (defaults to true)
21188      */
21189     select : function(index, scrollIntoView){
21190         this.selectedIndex = index;
21191         this.view.select(index);
21192         if(scrollIntoView !== false){
21193             var el = this.view.getNode(index);
21194             if(el){
21195                 this.innerList.scrollChildIntoView(el, false);
21196             }
21197         }
21198     },
21199
21200     // private
21201     selectNext : function(){
21202         var ct = this.store.getCount();
21203         if(ct > 0){
21204             if(this.selectedIndex == -1){
21205                 this.select(0);
21206             }else if(this.selectedIndex < ct-1){
21207                 this.select(this.selectedIndex+1);
21208             }
21209         }
21210     },
21211
21212     // private
21213     selectPrev : function(){
21214         var ct = this.store.getCount();
21215         if(ct > 0){
21216             if(this.selectedIndex == -1){
21217                 this.select(0);
21218             }else if(this.selectedIndex != 0){
21219                 this.select(this.selectedIndex-1);
21220             }
21221         }
21222     },
21223
21224     // private
21225     onKeyUp : function(e){
21226         if(this.editable !== false && !e.isSpecialKey()){
21227             this.lastKey = e.getKey();
21228             this.dqTask.delay(this.queryDelay);
21229         }
21230     },
21231
21232     // private
21233     validateBlur : function(){
21234         return !this.list || !this.list.isVisible();   
21235     },
21236
21237     // private
21238     initQuery : function(){
21239         this.doQuery(this.getRawValue());
21240     },
21241
21242     // private
21243     doForce : function(){
21244         if(this.el.dom.value.length > 0){
21245             this.el.dom.value =
21246                 this.lastSelectionText === undefined ? '' : this.lastSelectionText;
21247              
21248         }
21249     },
21250
21251     /**
21252      * Execute a query to filter the dropdown list.  Fires the beforequery event prior to performing the
21253      * query allowing the query action to be canceled if needed.
21254      * @param {String} query The SQL query to execute
21255      * @param {Boolean} forceAll True to force the query to execute even if there are currently fewer characters
21256      * in the field than the minimum specified by the minChars config option.  It also clears any filter previously
21257      * saved in the current store (defaults to false)
21258      */
21259     doQuery : function(q, forceAll){
21260         if(q === undefined || q === null){
21261             q = '';
21262         }
21263         var qe = {
21264             query: q,
21265             forceAll: forceAll,
21266             combo: this,
21267             cancel:false
21268         };
21269         if(this.fireEvent('beforequery', qe)===false || qe.cancel){
21270             return false;
21271         }
21272         q = qe.query;
21273         forceAll = qe.forceAll;
21274         if(forceAll === true || (q.length >= this.minChars)){
21275             if(this.lastQuery != q || this.alwaysQuery){
21276                 this.lastQuery = q;
21277                 if(this.mode == 'local'){
21278                     this.selectedIndex = -1;
21279                     if(forceAll){
21280                         this.store.clearFilter();
21281                     }else{
21282                         this.store.filter(this.displayField, q);
21283                     }
21284                     this.onLoad();
21285                 }else{
21286                     this.store.baseParams[this.queryParam] = q;
21287                     this.store.load({
21288                         params: this.getParams(q)
21289                     });
21290                     this.expand();
21291                 }
21292             }else{
21293                 this.selectedIndex = -1;
21294                 this.onLoad();   
21295             }
21296         }
21297     },
21298
21299     // private
21300     getParams : function(q){
21301         var p = {};
21302         //p[this.queryParam] = q;
21303         if(this.pageSize){
21304             p.start = 0;
21305             p.limit = this.pageSize;
21306         }
21307         return p;
21308     },
21309
21310     /**
21311      * Hides the dropdown list if it is currently expanded. Fires the 'collapse' event on completion.
21312      */
21313     collapse : function(){
21314         if(!this.isExpanded()){
21315             return;
21316         }
21317         this.list.hide();
21318         Roo.get(document).un('mousedown', this.collapseIf, this);
21319         Roo.get(document).un('mousewheel', this.collapseIf, this);
21320         if (!this.editable) {
21321             Roo.get(document).un('keydown', this.listKeyPress, this);
21322         }
21323         this.fireEvent('collapse', this);
21324     },
21325
21326     // private
21327     collapseIf : function(e){
21328         if(!e.within(this.wrap) && !e.within(this.list)){
21329             this.collapse();
21330         }
21331     },
21332
21333     /**
21334      * Expands the dropdown list if it is currently hidden. Fires the 'expand' event on completion.
21335      */
21336     expand : function(){
21337         if(this.isExpanded() || !this.hasFocus){
21338             return;
21339         }
21340         this.list.alignTo(this.el, this.listAlign);
21341         this.list.show();
21342         Roo.get(document).on('mousedown', this.collapseIf, this);
21343         Roo.get(document).on('mousewheel', this.collapseIf, this);
21344         if (!this.editable) {
21345             Roo.get(document).on('keydown', this.listKeyPress, this);
21346         }
21347         
21348         this.fireEvent('expand', this);
21349     },
21350
21351     // private
21352     // Implements the default empty TriggerField.onTriggerClick function
21353     onTriggerClick : function(){
21354         if(this.disabled){
21355             return;
21356         }
21357         if(this.isExpanded()){
21358             this.collapse();
21359             if (!this.blockFocus) {
21360                 this.el.focus();
21361             }
21362             
21363         }else {
21364             this.hasFocus = true;
21365             if(this.triggerAction == 'all') {
21366                 this.doQuery(this.allQuery, true);
21367             } else {
21368                 this.doQuery(this.getRawValue());
21369             }
21370             if (!this.blockFocus) {
21371                 this.el.focus();
21372             }
21373         }
21374     },
21375     listKeyPress : function(e)
21376     {
21377         //Roo.log('listkeypress');
21378         // scroll to first matching element based on key pres..
21379         if (e.isSpecialKey()) {
21380             return false;
21381         }
21382         var k = String.fromCharCode(e.getKey()).toUpperCase();
21383         //Roo.log(k);
21384         var match  = false;
21385         var csel = this.view.getSelectedNodes();
21386         var cselitem = false;
21387         if (csel.length) {
21388             var ix = this.view.indexOf(csel[0]);
21389             cselitem  = this.store.getAt(ix);
21390             if (!cselitem.get(this.displayField) || cselitem.get(this.displayField).substring(0,1).toUpperCase() != k) {
21391                 cselitem = false;
21392             }
21393             
21394         }
21395         
21396         this.store.each(function(v) { 
21397             if (cselitem) {
21398                 // start at existing selection.
21399                 if (cselitem.id == v.id) {
21400                     cselitem = false;
21401                 }
21402                 return;
21403             }
21404                 
21405             if (v.get(this.displayField) && v.get(this.displayField).substring(0,1).toUpperCase() == k) {
21406                 match = this.store.indexOf(v);
21407                 return false;
21408             }
21409         }, this);
21410         
21411         if (match === false) {
21412             return true; // no more action?
21413         }
21414         // scroll to?
21415         this.view.select(match);
21416         var sn = Roo.get(this.view.getSelectedNodes()[0]);
21417         sn.scrollIntoView(sn.dom.parentNode, false);
21418     },
21419         cleanLeadingSpace : function()
21420         {
21421                 // override textfield strip white space (trigers set on blur)
21422         }
21423
21424     /** 
21425     * @cfg {Boolean} grow 
21426     * @hide 
21427     */
21428     /** 
21429     * @cfg {Number} growMin 
21430     * @hide 
21431     */
21432     /** 
21433     * @cfg {Number} growMax 
21434     * @hide 
21435     */
21436     /**
21437      * @hide
21438      * @method autoSize
21439      */
21440 });/*
21441  * Copyright(c) 2010-2012, Roo J Solutions Limited
21442  *
21443  * Licence LGPL
21444  *
21445  */
21446
21447 /**
21448  * @class Roo.form.ComboBoxArray
21449  * @extends Roo.form.TextField
21450  * A facebook style adder... for lists of email / people / countries  etc...
21451  * pick multiple items from a combo box, and shows each one.
21452  *
21453  *  Fred [x]  Brian [x]  [Pick another |v]
21454  *
21455  *
21456  *  For this to work: it needs various extra information
21457  *    - normal combo problay has
21458  *      name, hiddenName
21459  *    + displayField, valueField
21460  *
21461  *    For our purpose...
21462  *
21463  *
21464  *   If we change from 'extends' to wrapping...
21465  *   
21466  *  
21467  *
21468  
21469  
21470  * @constructor
21471  * Create a new ComboBoxArray.
21472  * @param {Object} config Configuration options
21473  */
21474  
21475
21476 Roo.form.ComboBoxArray = function(config)
21477 {
21478     this.addEvents({
21479         /**
21480          * @event beforeremove
21481          * Fires before remove the value from the list
21482              * @param {Roo.form.ComboBoxArray} _self This combo box array
21483              * @param {Roo.form.ComboBoxArray.Item} item removed item
21484              */
21485         'beforeremove' : true,
21486         /**
21487          * @event remove
21488          * Fires when remove the value from the list
21489              * @param {Roo.form.ComboBoxArray} _self This combo box array
21490              * @param {Roo.form.ComboBoxArray.Item} item removed item
21491              */
21492         'remove' : true
21493         
21494         
21495     });
21496     
21497     Roo.form.ComboBoxArray.superclass.constructor.call(this, config);
21498     
21499     this.items = new Roo.util.MixedCollection(false);
21500     
21501     // construct the child combo...
21502     
21503     
21504     
21505     
21506    
21507     
21508 }
21509
21510  
21511 Roo.extend(Roo.form.ComboBoxArray, Roo.form.TextField,
21512
21513     /**
21514      * @cfg {Roo.form.ComboBox} combo [required] The combo box that is wrapped
21515      */
21516     
21517     lastData : false,
21518     
21519     // behavies liek a hiddne field
21520     inputType:      'hidden',
21521     /**
21522      * @cfg {Number} width The width of the box that displays the selected element
21523      */ 
21524     width:          300,
21525
21526     
21527     
21528     /**
21529      * @cfg {String} name    The name of the visable items on this form (eg. titles not ids)
21530      */
21531     name : false,
21532     /**
21533      * @cfg {String} hiddenName    The hidden name of the field, often contains an comma seperated list of names
21534      */
21535     hiddenName : false,
21536       /**
21537      * @cfg {String} seperator    The value seperator normally ',' 
21538      */
21539     seperator : ',',
21540     
21541     
21542         // private the array of items that are displayed..
21543     items  : false,
21544     // private - the hidden field el.
21545     hiddenEl : false,
21546     // private - the filed el..
21547     el : false,
21548     
21549     //validateValue : function() { return true; }, // all values are ok!
21550     //onAddClick: function() { },
21551     
21552     onRender : function(ct, position) 
21553     {
21554         
21555         // create the standard hidden element
21556         //Roo.form.ComboBoxArray.superclass.onRender.call(this, ct, position);
21557         
21558         
21559         // give fake names to child combo;
21560         this.combo.hiddenName = this.hiddenName ? (this.hiddenName+'-subcombo') : this.hiddenName;
21561         this.combo.name = this.name ? (this.name+'-subcombo') : this.name;
21562         
21563         this.combo = Roo.factory(this.combo, Roo.form);
21564         this.combo.onRender(ct, position);
21565         if (typeof(this.combo.width) != 'undefined') {
21566             this.combo.onResize(this.combo.width,0);
21567         }
21568         
21569         this.combo.initEvents();
21570         
21571         // assigned so form know we need to do this..
21572         this.store          = this.combo.store;
21573         this.valueField     = this.combo.valueField;
21574         this.displayField   = this.combo.displayField ;
21575         
21576         
21577         this.combo.wrap.addClass('x-cbarray-grp');
21578         
21579         var cbwrap = this.combo.wrap.createChild(
21580             {tag: 'div', cls: 'x-cbarray-cb'},
21581             this.combo.el.dom
21582         );
21583         
21584              
21585         this.hiddenEl = this.combo.wrap.createChild({
21586             tag: 'input',  type:'hidden' , name: this.hiddenName, value : ''
21587         });
21588         this.el = this.combo.wrap.createChild({
21589             tag: 'input',  type:'hidden' , name: this.name, value : ''
21590         });
21591          //   this.el.dom.removeAttribute("name");
21592         
21593         
21594         this.outerWrap = this.combo.wrap;
21595         this.wrap = cbwrap;
21596         
21597         this.outerWrap.setWidth(this.width);
21598         this.outerWrap.dom.removeChild(this.el.dom);
21599         
21600         this.wrap.dom.appendChild(this.el.dom);
21601         this.outerWrap.dom.removeChild(this.combo.trigger.dom);
21602         this.combo.wrap.dom.appendChild(this.combo.trigger.dom);
21603         
21604         this.combo.trigger.setStyle('position','relative');
21605         this.combo.trigger.setStyle('left', '0px');
21606         this.combo.trigger.setStyle('top', '2px');
21607         
21608         this.combo.el.setStyle('vertical-align', 'text-bottom');
21609         
21610         //this.trigger.setStyle('vertical-align', 'top');
21611         
21612         // this should use the code from combo really... on('add' ....)
21613         if (this.adder) {
21614             
21615         
21616             this.adder = this.outerWrap.createChild(
21617                 {tag: 'img', src: Roo.BLANK_IMAGE_URL, cls: 'x-form-adder', style: 'margin-left:2px'});  
21618             var _t = this;
21619             this.adder.on('click', function(e) {
21620                 _t.fireEvent('adderclick', this, e);
21621             }, _t);
21622         }
21623         //var _t = this;
21624         //this.adder.on('click', this.onAddClick, _t);
21625         
21626         
21627         this.combo.on('select', function(cb, rec, ix) {
21628             this.addItem(rec.data);
21629             
21630             cb.setValue('');
21631             cb.el.dom.value = '';
21632             //cb.lastData = rec.data;
21633             // add to list
21634             
21635         }, this);
21636          
21637         
21638         
21639             
21640     },
21641     
21642     
21643     getName: function()
21644     {
21645         // returns hidden if it's set..
21646         if (!this.rendered) {return ''};
21647         return  this.hiddenName ? this.hiddenName : this.name;
21648         
21649     },
21650     
21651     
21652     onResize: function(w, h){
21653         
21654         return;
21655         // not sure if this is needed..
21656         //this.combo.onResize(w,h);
21657         
21658         if(typeof w != 'number'){
21659             // we do not handle it!?!?
21660             return;
21661         }
21662         var tw = this.combo.trigger.getWidth();
21663         tw += this.addicon ? this.addicon.getWidth() : 0;
21664         tw += this.editicon ? this.editicon.getWidth() : 0;
21665         var x = w - tw;
21666         this.combo.el.setWidth( this.combo.adjustWidth('input', x));
21667             
21668         this.combo.trigger.setStyle('left', '0px');
21669         
21670         if(this.list && this.listWidth === undefined){
21671             var lw = Math.max(x + this.combo.trigger.getWidth(), this.combo.minListWidth);
21672             this.list.setWidth(lw);
21673             this.innerList.setWidth(lw - this.list.getFrameWidth('lr'));
21674         }
21675         
21676     
21677         
21678     },
21679     
21680     addItem: function(rec)
21681     {
21682         var valueField = this.combo.valueField;
21683         var displayField = this.combo.displayField;
21684         
21685         if (this.items.indexOfKey(rec[valueField]) > -1) {
21686             //console.log("GOT " + rec.data.id);
21687             return;
21688         }
21689         
21690         var x = new Roo.form.ComboBoxArray.Item({
21691             //id : rec[this.idField],
21692             data : rec,
21693             displayField : displayField ,
21694             tipField : displayField ,
21695             cb : this
21696         });
21697         // use the 
21698         this.items.add(rec[valueField],x);
21699         // add it before the element..
21700         this.updateHiddenEl();
21701         x.render(this.outerWrap, this.wrap.dom);
21702         // add the image handler..
21703     },
21704     
21705     updateHiddenEl : function()
21706     {
21707         this.validate();
21708         if (!this.hiddenEl) {
21709             return;
21710         }
21711         var ar = [];
21712         var idField = this.combo.valueField;
21713         
21714         this.items.each(function(f) {
21715             ar.push(f.data[idField]);
21716         });
21717         this.hiddenEl.dom.value = ar.join(this.seperator);
21718         this.validate();
21719     },
21720     
21721     reset : function()
21722     {
21723         this.items.clear();
21724         
21725         Roo.each(this.outerWrap.select('.x-cbarray-item', true).elements, function(el){
21726            el.remove();
21727         });
21728         
21729         this.el.dom.value = '';
21730         if (this.hiddenEl) {
21731             this.hiddenEl.dom.value = '';
21732         }
21733         
21734     },
21735     getValue: function()
21736     {
21737         return this.hiddenEl ? this.hiddenEl.dom.value : '';
21738     },
21739     setValue: function(v) // not a valid action - must use addItems..
21740     {
21741         
21742         this.reset();
21743          
21744         if (this.store.isLocal && (typeof(v) == 'string')) {
21745             // then we can use the store to find the values..
21746             // comma seperated at present.. this needs to allow JSON based encoding..
21747             this.hiddenEl.value  = v;
21748             var v_ar = [];
21749             Roo.each(v.split(this.seperator), function(k) {
21750                 Roo.log("CHECK " + this.valueField + ',' + k);
21751                 var li = this.store.query(this.valueField, k);
21752                 if (!li.length) {
21753                     return;
21754                 }
21755                 var add = {};
21756                 add[this.valueField] = k;
21757                 add[this.displayField] = li.item(0).data[this.displayField];
21758                 
21759                 this.addItem(add);
21760             }, this) 
21761              
21762         }
21763         if (typeof(v) == 'object' ) {
21764             // then let's assume it's an array of objects..
21765             Roo.each(v, function(l) {
21766                 var add = l;
21767                 if (typeof(l) == 'string') {
21768                     add = {};
21769                     add[this.valueField] = l;
21770                     add[this.displayField] = l
21771                 }
21772                 this.addItem(add);
21773             }, this);
21774              
21775         }
21776         
21777         
21778     },
21779     setFromData: function(v)
21780     {
21781         // this recieves an object, if setValues is called.
21782         this.reset();
21783         this.el.dom.value = v[this.displayField];
21784         this.hiddenEl.dom.value = v[this.valueField];
21785         if (typeof(v[this.valueField]) != 'string' || !v[this.valueField].length) {
21786             return;
21787         }
21788         var kv = v[this.valueField];
21789         var dv = v[this.displayField];
21790         kv = typeof(kv) != 'string' ? '' : kv;
21791         dv = typeof(dv) != 'string' ? '' : dv;
21792         
21793         
21794         var keys = kv.split(this.seperator);
21795         var display = dv.split(this.seperator);
21796         for (var i = 0 ; i < keys.length; i++) {
21797             add = {};
21798             add[this.valueField] = keys[i];
21799             add[this.displayField] = display[i];
21800             this.addItem(add);
21801         }
21802       
21803         
21804     },
21805     
21806     /**
21807      * Validates the combox array value
21808      * @return {Boolean} True if the value is valid, else false
21809      */
21810     validate : function(){
21811         if(this.disabled || this.validateValue(this.processValue(this.getValue()))){
21812             this.clearInvalid();
21813             return true;
21814         }
21815         return false;
21816     },
21817     
21818     validateValue : function(value){
21819         return Roo.form.ComboBoxArray.superclass.validateValue.call(this, this.getValue());
21820         
21821     },
21822     
21823     /*@
21824      * overide
21825      * 
21826      */
21827     isDirty : function() {
21828         if(this.disabled) {
21829             return false;
21830         }
21831         
21832         try {
21833             var d = Roo.decode(String(this.originalValue));
21834         } catch (e) {
21835             return String(this.getValue()) !== String(this.originalValue);
21836         }
21837         
21838         var originalValue = [];
21839         
21840         for (var i = 0; i < d.length; i++){
21841             originalValue.push(d[i][this.valueField]);
21842         }
21843         
21844         return String(this.getValue()) !== String(originalValue.join(this.seperator));
21845         
21846     }
21847     
21848 });
21849
21850
21851
21852 /**
21853  * @class Roo.form.ComboBoxArray.Item
21854  * @extends Roo.BoxComponent
21855  * A selected item in the list
21856  *  Fred [x]  Brian [x]  [Pick another |v]
21857  * 
21858  * @constructor
21859  * Create a new item.
21860  * @param {Object} config Configuration options
21861  */
21862  
21863 Roo.form.ComboBoxArray.Item = function(config) {
21864     config.id = Roo.id();
21865     Roo.form.ComboBoxArray.Item.superclass.constructor.call(this, config);
21866 }
21867
21868 Roo.extend(Roo.form.ComboBoxArray.Item, Roo.BoxComponent, {
21869     data : {},
21870     cb: false,
21871     displayField : false,
21872     tipField : false,
21873      
21874     
21875     defaultAutoCreate : {
21876         tag: 'div',
21877         cls: 'x-cbarray-item',
21878         cn : [ 
21879             { tag: 'div' },
21880             {
21881                 tag: 'img',
21882                 width:16,
21883                 height : 16,
21884                 src : Roo.BLANK_IMAGE_URL ,
21885                 align: 'center'
21886             }
21887         ]
21888         
21889     },
21890     
21891  
21892     onRender : function(ct, position)
21893     {
21894         Roo.form.Field.superclass.onRender.call(this, ct, position);
21895         
21896         if(!this.el){
21897             var cfg = this.getAutoCreate();
21898             this.el = ct.createChild(cfg, position);
21899         }
21900         
21901         this.el.child('img').dom.setAttribute('src', Roo.BLANK_IMAGE_URL);
21902         
21903         this.el.child('div').dom.innerHTML = this.cb.renderer ? 
21904             this.cb.renderer(this.data) :
21905             String.format('{0}',this.data[this.displayField]);
21906         
21907             
21908         this.el.child('div').dom.setAttribute('qtip',
21909                         String.format('{0}',this.data[this.tipField])
21910         );
21911         
21912         this.el.child('img').on('click', this.remove, this);
21913         
21914     },
21915    
21916     remove : function()
21917     {
21918         if(this.cb.disabled){
21919             return;
21920         }
21921         
21922         if(false !== this.cb.fireEvent('beforeremove', this.cb, this)){
21923             this.cb.items.remove(this);
21924             this.el.child('img').un('click', this.remove, this);
21925             this.el.remove();
21926             this.cb.updateHiddenEl();
21927
21928             this.cb.fireEvent('remove', this.cb, this);
21929         }
21930         
21931     }
21932 });/*
21933  * RooJS Library 1.1.1
21934  * Copyright(c) 2008-2011  Alan Knowles
21935  *
21936  * License - LGPL
21937  */
21938  
21939
21940 /**
21941  * @class Roo.form.ComboNested
21942  * @extends Roo.form.ComboBox
21943  * A combobox for that allows selection of nested items in a list,
21944  * eg.
21945  *
21946  *  Book
21947  *    -> red
21948  *    -> green
21949  *  Table
21950  *    -> square
21951  *      ->red
21952  *      ->green
21953  *    -> rectangle
21954  *      ->green
21955  *      
21956  * 
21957  * @constructor
21958  * Create a new ComboNested
21959  * @param {Object} config Configuration options
21960  */
21961 Roo.form.ComboNested = function(config){
21962     Roo.form.ComboCheck.superclass.constructor.call(this, config);
21963     // should verify some data...
21964     // like
21965     // hiddenName = required..
21966     // displayField = required
21967     // valudField == required
21968     var req= [ 'hiddenName', 'displayField', 'valueField' ];
21969     var _t = this;
21970     Roo.each(req, function(e) {
21971         if ((typeof(_t[e]) == 'undefined' ) || !_t[e].length) {
21972             throw "Roo.form.ComboNested : missing value for: " + e;
21973         }
21974     });
21975      
21976     
21977 };
21978
21979 Roo.extend(Roo.form.ComboNested, Roo.form.ComboBox, {
21980    
21981     /*
21982      * @config {Number} max Number of columns to show
21983      */
21984     
21985     maxColumns : 3,
21986    
21987     list : null, // the outermost div..
21988     innerLists : null, // the
21989     views : null,
21990     stores : null,
21991     // private
21992     loadingChildren : false,
21993     
21994     onRender : function(ct, position)
21995     {
21996         Roo.form.ComboBox.superclass.onRender.call(this, ct, position); // skip parent call - got to above..
21997         
21998         if(this.hiddenName){
21999             this.hiddenField = this.el.insertSibling({tag:'input', type:'hidden', name: this.hiddenName, id:  (this.hiddenId||this.hiddenName)},
22000                     'before', true);
22001             this.hiddenField.value =
22002                 this.hiddenValue !== undefined ? this.hiddenValue :
22003                 this.value !== undefined ? this.value : '';
22004
22005             // prevent input submission
22006             this.el.dom.removeAttribute('name');
22007              
22008              
22009         }
22010         
22011         if(Roo.isGecko){
22012             this.el.dom.setAttribute('autocomplete', 'off');
22013         }
22014
22015         var cls = 'x-combo-list';
22016
22017         this.list = new Roo.Layer({
22018             shadow: this.shadow, cls: [cls, this.listClass].join(' '), constrain:false
22019         });
22020
22021         var lw = this.listWidth || Math.max(this.wrap.getWidth(), this.minListWidth);
22022         this.list.setWidth(lw);
22023         this.list.swallowEvent('mousewheel');
22024         this.assetHeight = 0;
22025
22026         if(this.title){
22027             this.header = this.list.createChild({cls:cls+'-hd', html: this.title});
22028             this.assetHeight += this.header.getHeight();
22029         }
22030         this.innerLists = [];
22031         this.views = [];
22032         this.stores = [];
22033         for (var i =0 ; i < this.maxColumns; i++) {
22034             this.onRenderList( cls, i);
22035         }
22036         
22037         // always needs footer, as we are going to have an 'OK' button.
22038         this.footer = this.list.createChild({cls:cls+'-ft'});
22039         this.pageTb = new Roo.Toolbar(this.footer);  
22040         var _this = this;
22041         this.pageTb.add(  {
22042             
22043             text: 'Done',
22044             handler: function()
22045             {
22046                 _this.collapse();
22047             }
22048         });
22049         
22050         if ( this.allowBlank && !this.disableClear) {
22051             
22052             this.pageTb.add(new Roo.Toolbar.Fill(), {
22053                 cls: 'x-btn-icon x-btn-clear',
22054                 text: '&#160;',
22055                 handler: function()
22056                 {
22057                     _this.collapse();
22058                     _this.clearValue();
22059                     _this.onSelect(false, -1);
22060                 }
22061             });
22062         }
22063         if (this.footer) {
22064             this.assetHeight += this.footer.getHeight();
22065         }
22066         
22067     },
22068     onRenderList : function (  cls, i)
22069     {
22070         
22071         var lw = Math.floor(
22072                 ((this.listWidth * this.maxColumns || Math.max(this.wrap.getWidth(), this.minListWidth)) - this.list.getFrameWidth('lr')) / this.maxColumns
22073         );
22074         
22075         this.list.setWidth(lw); // default to '1'
22076
22077         var il = this.innerLists[i] = this.list.createChild({cls:cls+'-inner'});
22078         //il.on('mouseover', this.onViewOver, this, { list:  i });
22079         //il.on('mousemove', this.onViewMove, this, { list:  i });
22080         il.setWidth(lw);
22081         il.setStyle({ 'overflow-x' : 'hidden'});
22082
22083         if(!this.tpl){
22084             this.tpl = new Roo.Template({
22085                 html :  '<div class="'+cls+'-item '+cls+'-item-{cn:this.isEmpty}">{' + this.displayField + '}</div>',
22086                 isEmpty: function (value, allValues) {
22087                     //Roo.log(value);
22088                     var dl = typeof(value.data) != 'undefined' ? value.data.length : value.length; ///json is a nested response..
22089                     return dl ? 'has-children' : 'no-children'
22090                 }
22091             });
22092         }
22093         
22094         var store  = this.store;
22095         if (i > 0) {
22096             store  = new Roo.data.SimpleStore({
22097                 //fields : this.store.reader.meta.fields,
22098                 reader : this.store.reader,
22099                 data : [ ]
22100             });
22101         }
22102         this.stores[i]  = store;
22103                   
22104         var view = this.views[i] = new Roo.View(
22105             il,
22106             this.tpl,
22107             {
22108                 singleSelect:true,
22109                 store: store,
22110                 selectedClass: this.selectedClass
22111             }
22112         );
22113         view.getEl().setWidth(lw);
22114         view.getEl().setStyle({
22115             position: i < 1 ? 'relative' : 'absolute',
22116             top: 0,
22117             left: (i * lw ) + 'px',
22118             display : i > 0 ? 'none' : 'block'
22119         });
22120         view.on('selectionchange', this.onSelectChange.createDelegate(this, {list : i }, true));
22121         view.on('dblclick', this.onDoubleClick.createDelegate(this, {list : i }, true));
22122         //view.on('click', this.onViewClick, this, { list : i });
22123
22124         store.on('beforeload', this.onBeforeLoad, this);
22125         store.on('load',  this.onLoad, this, { list  : i});
22126         store.on('loadexception', this.onLoadException, this);
22127
22128         // hide the other vies..
22129         
22130         
22131         
22132     },
22133       
22134     restrictHeight : function()
22135     {
22136         var mh = 0;
22137         Roo.each(this.innerLists, function(il,i) {
22138             var el = this.views[i].getEl();
22139             el.dom.style.height = '';
22140             var inner = el.dom;
22141             var h = Math.max(il.clientHeight, il.offsetHeight, il.scrollHeight);
22142             // only adjust heights on other ones..
22143             mh = Math.max(h, mh);
22144             if (i < 1) {
22145                 
22146                 el.setHeight(h < this.maxHeight ? 'auto' : this.maxHeight);
22147                 il.setHeight(h < this.maxHeight ? 'auto' : this.maxHeight);
22148                
22149             }
22150             
22151             
22152         }, this);
22153         
22154         this.list.beginUpdate();
22155         this.list.setHeight(mh+this.list.getFrameWidth('tb')+this.assetHeight);
22156         this.list.alignTo(this.el, this.listAlign);
22157         this.list.endUpdate();
22158         
22159     },
22160      
22161     
22162     // -- store handlers..
22163     // private
22164     onBeforeLoad : function()
22165     {
22166         if(!this.hasFocus){
22167             return;
22168         }
22169         this.innerLists[0].update(this.loadingText ?
22170                '<div class="loading-indicator">'+this.loadingText+'</div>' : '');
22171         this.restrictHeight();
22172         this.selectedIndex = -1;
22173     },
22174     // private
22175     onLoad : function(a,b,c,d)
22176     {
22177         if (!this.loadingChildren) {
22178             // then we are loading the top level. - hide the children
22179             for (var i = 1;i < this.views.length; i++) {
22180                 this.views[i].getEl().setStyle({ display : 'none' });
22181             }
22182             var lw = Math.floor(
22183                 ((this.listWidth * this.maxColumns || Math.max(this.wrap.getWidth(), this.minListWidth)) - this.list.getFrameWidth('lr')) / this.maxColumns
22184             );
22185         
22186              this.list.setWidth(lw); // default to '1'
22187
22188             
22189         }
22190         if(!this.hasFocus){
22191             return;
22192         }
22193         
22194         if(this.store.getCount() > 0) {
22195             this.expand();
22196             this.restrictHeight();   
22197         } else {
22198             this.onEmptyResults();
22199         }
22200         
22201         if (!this.loadingChildren) {
22202             this.selectActive();
22203         }
22204         /*
22205         this.stores[1].loadData([]);
22206         this.stores[2].loadData([]);
22207         this.views
22208         */    
22209     
22210         //this.el.focus();
22211     },
22212     
22213     
22214     // private
22215     onLoadException : function()
22216     {
22217         this.collapse();
22218         Roo.log(this.store.reader.jsonData);
22219         if (this.store && typeof(this.store.reader.jsonData.errorMsg) != 'undefined') {
22220             Roo.MessageBox.alert("Error loading",this.store.reader.jsonData.errorMsg);
22221         }
22222         
22223         
22224     },
22225     // no cleaning of leading spaces on blur here.
22226     cleanLeadingSpace : function(e) { },
22227     
22228
22229     onSelectChange : function (view, sels, opts )
22230     {
22231         var ix = view.getSelectedIndexes();
22232          
22233         if (opts.list > this.maxColumns - 2) {
22234             if (view.store.getCount()<  1) {
22235                 this.views[opts.list ].getEl().setStyle({ display :   'none' });
22236
22237             } else  {
22238                 if (ix.length) {
22239                     // used to clear ?? but if we are loading unselected 
22240                     this.setFromData(view.store.getAt(ix[0]).data);
22241                 }
22242                 
22243             }
22244             
22245             return;
22246         }
22247         
22248         if (!ix.length) {
22249             // this get's fired when trigger opens..
22250            // this.setFromData({});
22251             var str = this.stores[opts.list+1];
22252             str.data.clear(); // removeall wihtout the fire events..
22253             return;
22254         }
22255         
22256         var rec = view.store.getAt(ix[0]);
22257          
22258         this.setFromData(rec.data);
22259         this.fireEvent('select', this, rec, ix[0]);
22260         
22261         var lw = Math.floor(
22262              (
22263                 (this.listWidth * this.maxColumns || Math.max(this.wrap.getWidth(), this.minListWidth)) - this.list.getFrameWidth('lr')
22264              ) / this.maxColumns
22265         );
22266         this.loadingChildren = true;
22267         this.stores[opts.list+1].loadDataFromChildren( rec );
22268         this.loadingChildren = false;
22269         var dl = this.stores[opts.list+1]. getTotalCount();
22270         
22271         this.views[opts.list+1].getEl().setHeight( this.innerLists[0].getHeight());
22272         
22273         this.views[opts.list+1].getEl().setStyle({ display : dl ? 'block' : 'none' });
22274         for (var i = opts.list+2; i < this.views.length;i++) {
22275             this.views[i].getEl().setStyle({ display : 'none' });
22276         }
22277         
22278         this.innerLists[opts.list+1].setHeight( this.innerLists[0].getHeight());
22279         this.list.setWidth(lw * (opts.list + (dl ? 2 : 1)));
22280         
22281         if (this.isLoading) {
22282            // this.selectActive(opts.list);
22283         }
22284          
22285     },
22286     
22287     
22288     
22289     
22290     onDoubleClick : function()
22291     {
22292         this.collapse(); //??
22293     },
22294     
22295      
22296     
22297     
22298     
22299     // private
22300     recordToStack : function(store, prop, value, stack)
22301     {
22302         var cstore = new Roo.data.SimpleStore({
22303             //fields : this.store.reader.meta.fields, // we need array reader.. for
22304             reader : this.store.reader,
22305             data : [ ]
22306         });
22307         var _this = this;
22308         var record  = false;
22309         var srec = false;
22310         if(store.getCount() < 1){
22311             return false;
22312         }
22313         store.each(function(r){
22314             if(r.data[prop] == value){
22315                 record = r;
22316             srec = r;
22317                 return false;
22318             }
22319             if (r.data.cn && r.data.cn.length) {
22320                 cstore.loadDataFromChildren( r);
22321                 var cret = _this.recordToStack(cstore, prop, value, stack);
22322                 if (cret !== false) {
22323                     record = cret;
22324                     srec = r;
22325                     return false;
22326                 }
22327             }
22328              
22329             return true;
22330         });
22331         if (record == false) {
22332             return false
22333         }
22334         stack.unshift(srec);
22335         return record;
22336     },
22337     
22338     /*
22339      * find the stack of stores that match our value.
22340      *
22341      * 
22342      */
22343     
22344     selectActive : function ()
22345     {
22346         // if store is not loaded, then we will need to wait for that to happen first.
22347         var stack = [];
22348         this.recordToStack(this.store, this.valueField, this.getValue(), stack);
22349         for (var i = 0; i < stack.length; i++ ) {
22350             this.views[i].select(stack[i].store.indexOf(stack[i]), false, false );
22351         }
22352         
22353     }
22354         
22355          
22356     
22357     
22358     
22359     
22360 });/*
22361  * Based on:
22362  * Ext JS Library 1.1.1
22363  * Copyright(c) 2006-2007, Ext JS, LLC.
22364  *
22365  * Originally Released Under LGPL - original licence link has changed is not relivant.
22366  *
22367  * Fork - LGPL
22368  * <script type="text/javascript">
22369  */
22370 /**
22371  * @class Roo.form.Checkbox
22372  * @extends Roo.form.Field
22373  * Single checkbox field.  Can be used as a direct replacement for traditional checkbox fields.
22374  * @constructor
22375  * Creates a new Checkbox
22376  * @param {Object} config Configuration options
22377  */
22378 Roo.form.Checkbox = function(config){
22379     Roo.form.Checkbox.superclass.constructor.call(this, config);
22380     this.addEvents({
22381         /**
22382          * @event check
22383          * Fires when the checkbox is checked or unchecked.
22384              * @param {Roo.form.Checkbox} this This checkbox
22385              * @param {Boolean} checked The new checked value
22386              */
22387         check : true
22388     });
22389 };
22390
22391 Roo.extend(Roo.form.Checkbox, Roo.form.Field,  {
22392     /**
22393      * @cfg {String} focusClass The CSS class to use when the checkbox receives focus (defaults to undefined)
22394      */
22395     focusClass : undefined,
22396     /**
22397      * @cfg {String} fieldClass The default CSS class for the checkbox (defaults to "x-form-field")
22398      */
22399     fieldClass: "x-form-field",
22400     /**
22401      * @cfg {Boolean} checked True if the the checkbox should render already checked (defaults to false)
22402      */
22403     checked: false,
22404     /**
22405      * @cfg {String/Object} autoCreate A DomHelper element spec, or true for a default element spec (defaults to
22406      * {tag: "input", type: "checkbox", autocomplete: "off"})
22407      */
22408     defaultAutoCreate : { tag: "input", type: 'hidden', autocomplete: "off"},
22409     /**
22410      * @cfg {String} boxLabel The text that appears beside the checkbox
22411      */
22412     boxLabel : "",
22413     /**
22414      * @cfg {String} inputValue The value that should go into the generated input element's value attribute
22415      */  
22416     inputValue : '1',
22417     /**
22418      * @cfg {String} valueOff The value that should go into the generated input element's value when unchecked.
22419      */
22420      valueOff: '0', // value when not checked..
22421
22422     actionMode : 'viewEl', 
22423     //
22424     // private
22425     itemCls : 'x-menu-check-item x-form-item',
22426     groupClass : 'x-menu-group-item',
22427     inputType : 'hidden',
22428     
22429     
22430     inSetChecked: false, // check that we are not calling self...
22431     
22432     inputElement: false, // real input element?
22433     basedOn: false, // ????
22434     
22435     isFormField: true, // not sure where this is needed!!!!
22436
22437     onResize : function(){
22438         Roo.form.Checkbox.superclass.onResize.apply(this, arguments);
22439         if(!this.boxLabel){
22440             this.el.alignTo(this.wrap, 'c-c');
22441         }
22442     },
22443
22444     initEvents : function(){
22445         Roo.form.Checkbox.superclass.initEvents.call(this);
22446         this.el.on("click", this.onClick,  this);
22447         this.el.on("change", this.onClick,  this);
22448     },
22449
22450
22451     getResizeEl : function(){
22452         return this.wrap;
22453     },
22454
22455     getPositionEl : function(){
22456         return this.wrap;
22457     },
22458
22459     // private
22460     onRender : function(ct, position){
22461         Roo.form.Checkbox.superclass.onRender.call(this, ct, position);
22462         /*
22463         if(this.inputValue !== undefined){
22464             this.el.dom.value = this.inputValue;
22465         }
22466         */
22467         //this.wrap = this.el.wrap({cls: "x-form-check-wrap"});
22468         this.wrap = this.el.wrap({cls: 'x-menu-check-item '});
22469         var viewEl = this.wrap.createChild({ 
22470             tag: 'img', cls: 'x-menu-item-icon', style: 'margin: 0px;' ,src : Roo.BLANK_IMAGE_URL });
22471         this.viewEl = viewEl;   
22472         this.wrap.on('click', this.onClick,  this); 
22473         
22474         this.el.on('DOMAttrModified', this.setFromHidden,  this); //ff
22475         this.el.on('propertychange', this.setFromHidden,  this);  //ie
22476         
22477         
22478         
22479         if(this.boxLabel){
22480             this.wrap.createChild({tag: 'label', htmlFor: this.el.id, cls: 'x-form-cb-label', html: this.boxLabel});
22481         //    viewEl.on('click', this.onClick,  this); 
22482         }
22483         //if(this.checked){
22484             this.setChecked(this.checked);
22485         //}else{
22486             //this.checked = this.el.dom;
22487         //}
22488
22489     },
22490
22491     // private
22492     initValue : Roo.emptyFn,
22493
22494     /**
22495      * Returns the checked state of the checkbox.
22496      * @return {Boolean} True if checked, else false
22497      */
22498     getValue : function(){
22499         if(this.el){
22500             return String(this.el.dom.value) == String(this.inputValue ) ? this.inputValue : this.valueOff;
22501         }
22502         return this.valueOff;
22503         
22504     },
22505
22506         // private
22507     onClick : function(){ 
22508         if (this.disabled) {
22509             return;
22510         }
22511         this.setChecked(!this.checked);
22512
22513         //if(this.el.dom.checked != this.checked){
22514         //    this.setValue(this.el.dom.checked);
22515        // }
22516     },
22517
22518     /**
22519      * Sets the checked state of the checkbox.
22520      * On is always based on a string comparison between inputValue and the param.
22521      * @param {Boolean/String} value - the value to set 
22522      * @param {Boolean/String} suppressEvent - whether to suppress the checkchange event.
22523      */
22524     setValue : function(v,suppressEvent){
22525         
22526         
22527         //this.checked = (v === true || v === 'true' || v == '1' || String(v).toLowerCase() == 'on');
22528         //if(this.el && this.el.dom){
22529         //    this.el.dom.checked = this.checked;
22530         //    this.el.dom.defaultChecked = this.checked;
22531         //}
22532         this.setChecked(String(v) === String(this.inputValue), suppressEvent);
22533         //this.fireEvent("check", this, this.checked);
22534     },
22535     // private..
22536     setChecked : function(state,suppressEvent)
22537     {
22538         if (this.inSetChecked) {
22539             this.checked = state;
22540             return;
22541         }
22542         
22543     
22544         if(this.wrap){
22545             this.wrap[state ? 'addClass' : 'removeClass']('x-menu-item-checked');
22546         }
22547         this.checked = state;
22548         if(suppressEvent !== true){
22549             this.fireEvent('check', this, state);
22550         }
22551         this.inSetChecked = true;
22552                  
22553                 this.el.dom.value = state ? this.inputValue : this.valueOff;
22554                  
22555         this.inSetChecked = false;
22556         
22557     },
22558     // handle setting of hidden value by some other method!!?!?
22559     setFromHidden: function()
22560     {
22561         if(!this.el){
22562             return;
22563         }
22564         //console.log("SET FROM HIDDEN");
22565         //alert('setFrom hidden');
22566         this.setValue(this.el.dom.value);
22567     },
22568     
22569     onDestroy : function()
22570     {
22571         if(this.viewEl){
22572             Roo.get(this.viewEl).remove();
22573         }
22574          
22575         Roo.form.Checkbox.superclass.onDestroy.call(this);
22576     },
22577     
22578     setBoxLabel : function(str)
22579     {
22580         this.wrap.select('.x-form-cb-label', true).first().dom.innerHTML = str;
22581     }
22582
22583 });/*
22584  * Based on:
22585  * Ext JS Library 1.1.1
22586  * Copyright(c) 2006-2007, Ext JS, LLC.
22587  *
22588  * Originally Released Under LGPL - original licence link has changed is not relivant.
22589  *
22590  * Fork - LGPL
22591  * <script type="text/javascript">
22592  */
22593  
22594 /**
22595  * @class Roo.form.Radio
22596  * @extends Roo.form.Checkbox
22597  * Single radio field.  Same as Checkbox, but provided as a convenience for automatically setting the input type.
22598  * Radio grouping is handled automatically by the browser if you give each radio in a group the same name.
22599  * @constructor
22600  * Creates a new Radio
22601  * @param {Object} config Configuration options
22602  */
22603 Roo.form.Radio = function(){
22604     Roo.form.Radio.superclass.constructor.apply(this, arguments);
22605 };
22606 Roo.extend(Roo.form.Radio, Roo.form.Checkbox, {
22607     inputType: 'radio',
22608
22609     /**
22610      * If this radio is part of a group, it will return the selected value
22611      * @return {String}
22612      */
22613     getGroupValue : function(){
22614         return this.el.up('form').child('input[name='+this.el.dom.name+']:checked', true).value;
22615     },
22616     
22617     
22618     onRender : function(ct, position){
22619         Roo.form.Checkbox.superclass.onRender.call(this, ct, position);
22620         
22621         if(this.inputValue !== undefined){
22622             this.el.dom.value = this.inputValue;
22623         }
22624          
22625         this.wrap = this.el.wrap({cls: "x-form-check-wrap"});
22626         //this.wrap = this.el.wrap({cls: 'x-menu-check-item '});
22627         //var viewEl = this.wrap.createChild({ 
22628         //    tag: 'img', cls: 'x-menu-item-icon', style: 'margin: 0px;' ,src : Roo.BLANK_IMAGE_URL });
22629         //this.viewEl = viewEl;   
22630         //this.wrap.on('click', this.onClick,  this); 
22631         
22632         //this.el.on('DOMAttrModified', this.setFromHidden,  this); //ff
22633         //this.el.on('propertychange', this.setFromHidden,  this);  //ie
22634         
22635         
22636         
22637         if(this.boxLabel){
22638             this.wrap.createChild({tag: 'label', htmlFor: this.el.id, cls: 'x-form-cb-label', html: this.boxLabel});
22639         //    viewEl.on('click', this.onClick,  this); 
22640         }
22641          if(this.checked){
22642             this.el.dom.checked =   'checked' ;
22643         }
22644          
22645     },
22646     /**
22647      * Sets the checked state of the checkbox.
22648      * On is always based on a string comparison between inputValue and the param.
22649      * @param {Boolean/String} value - the value to set 
22650      * @param {Boolean/String} suppressEvent - whether to suppress the checkchange event.
22651      */
22652     setValue : function(v,suppressEvent){
22653         
22654         
22655         //this.checked = (v === true || v === 'true' || v == '1' || String(v).toLowerCase() == 'on');
22656         //if(this.el && this.el.dom){
22657         //    this.el.dom.checked = this.checked;
22658         //    this.el.dom.defaultChecked = this.checked;
22659         //}
22660         this.setChecked(String(v) === String(this.inputValue), suppressEvent);
22661         
22662         this.el.dom.form[this.name].value = v;
22663      
22664         //this.fireEvent("check", this, this.checked);
22665     },
22666     // private..
22667     setChecked : function(state,suppressEvent)
22668     {
22669          
22670         if(this.wrap){
22671             this.wrap[state ? 'addClass' : 'removeClass']('x-menu-item-checked');
22672         }
22673         this.checked = state;
22674         if(suppressEvent !== true){
22675             this.fireEvent('check', this, state);
22676         }
22677                  
22678                   
22679        
22680         
22681     },
22682     reset : function(){
22683         // this.setValue(this.resetValue);
22684         //this.originalValue = this.getValue();
22685         this.clearInvalid();
22686     } 
22687     
22688 });Roo.rtf = {}; // namespace
22689 Roo.rtf.Hex = function(hex)
22690 {
22691     this.hexstr = hex;
22692 };
22693 Roo.rtf.Paragraph = function(opts)
22694 {
22695     this.content = []; ///??? is that used?
22696 };Roo.rtf.Span = function(opts)
22697 {
22698     this.value = opts.value;
22699 };
22700
22701 Roo.rtf.Group = function(parent)
22702 {
22703     // we dont want to acutally store parent - it will make debug a nightmare..
22704     this.content = [];
22705     this.cn  = [];
22706      
22707        
22708     
22709 };
22710
22711 Roo.rtf.Group.prototype = {
22712     ignorable : false,
22713     content: false,
22714     cn: false,
22715     addContent : function(node) {
22716         // could set styles...
22717         this.content.push(node);
22718     },
22719     addChild : function(cn)
22720     {
22721         this.cn.push(cn);
22722     },
22723     // only for images really...
22724     toDataURL : function()
22725     {
22726         var mimetype = false;
22727         switch(true) {
22728             case this.content.filter(function(a) { return a.value == 'pngblip' } ).length > 0: 
22729                 mimetype = "image/png";
22730                 break;
22731              case this.content.filter(function(a) { return a.value == 'jpegblip' } ).length > 0:
22732                 mimetype = "image/jpeg";
22733                 break;
22734             default :
22735                 return 'about:blank'; // ?? error?
22736         }
22737         
22738         
22739         var hexstring = this.content[this.content.length-1].value;
22740         
22741         return 'data:' + mimetype + ';base64,' + btoa(hexstring.match(/\w{2}/g).map(function(a) {
22742             return String.fromCharCode(parseInt(a, 16));
22743         }).join(""));
22744     }
22745     
22746 };
22747 // this looks like it's normally the {rtf{ .... }}
22748 Roo.rtf.Document = function()
22749 {
22750     // we dont want to acutally store parent - it will make debug a nightmare..
22751     this.rtlch  = [];
22752     this.content = [];
22753     this.cn = [];
22754     
22755 };
22756 Roo.extend(Roo.rtf.Document, Roo.rtf.Group, { 
22757     addChild : function(cn)
22758     {
22759         this.cn.push(cn);
22760         switch(cn.type) {
22761             case 'rtlch': // most content seems to be inside this??
22762             case 'listtext':
22763             case 'shpinst':
22764                 this.rtlch.push(cn);
22765                 return;
22766             default:
22767                 this[cn.type] = cn;
22768         }
22769         
22770     },
22771     
22772     getElementsByType : function(type)
22773     {
22774         var ret =  [];
22775         this._getElementsByType(type, ret, this.cn, 'rtf');
22776         return ret;
22777     },
22778     _getElementsByType : function (type, ret, search_array, path)
22779     {
22780         search_array.forEach(function(n,i) {
22781             if (n.type == type) {
22782                 n.path = path + '/' + n.type + ':' + i;
22783                 ret.push(n);
22784             }
22785             if (n.cn.length > 0) {
22786                 this._getElementsByType(type, ret, n.cn, path + '/' + n.type+':'+i);
22787             }
22788         },this);
22789     }
22790     
22791 });
22792  
22793 Roo.rtf.Ctrl = function(opts)
22794 {
22795     this.value = opts.value;
22796     this.param = opts.param;
22797 };
22798 /**
22799  *
22800  *
22801  * based on this https://github.com/iarna/rtf-parser
22802  * it's really only designed to extract pict from pasted RTF 
22803  *
22804  * usage:
22805  *
22806  *  var images = new Roo.rtf.Parser().parse(a_string).filter(function(g) { return g.type == 'pict'; });
22807  *  
22808  *
22809  */
22810
22811  
22812
22813
22814
22815 Roo.rtf.Parser = function(text) {
22816     //super({objectMode: true})
22817     this.text = '';
22818     this.parserState = this.parseText;
22819     
22820     // these are for interpeter...
22821     this.doc = {};
22822     ///this.parserState = this.parseTop
22823     this.groupStack = [];
22824     this.hexStore = [];
22825     this.doc = false;
22826     
22827     this.groups = []; // where we put the return.
22828     
22829     for (var ii = 0; ii < text.length; ++ii) {
22830         ++this.cpos;
22831         
22832         if (text[ii] === '\n') {
22833             ++this.row;
22834             this.col = 1;
22835         } else {
22836             ++this.col;
22837         }
22838         this.parserState(text[ii]);
22839     }
22840     
22841     
22842     
22843 };
22844 Roo.rtf.Parser.prototype = {
22845     text : '', // string being parsed..
22846     controlWord : '',
22847     controlWordParam :  '',
22848     hexChar : '',
22849     doc : false,
22850     group: false,
22851     groupStack : false,
22852     hexStore : false,
22853     
22854     
22855     cpos : 0, 
22856     row : 1, // reportin?
22857     col : 1, //
22858
22859      
22860     push : function (el)
22861     {
22862         var m = 'cmd'+ el.type;
22863         if (typeof(this[m]) == 'undefined') {
22864             Roo.log('invalid cmd:' + el.type);
22865             return;
22866         }
22867         this[m](el);
22868         //Roo.log(el);
22869     },
22870     flushHexStore : function()
22871     {
22872         if (this.hexStore.length < 1) {
22873             return;
22874         }
22875         var hexstr = this.hexStore.map(
22876             function(cmd) {
22877                 return cmd.value;
22878         }).join('');
22879         
22880         this.group.addContent( new Roo.rtf.Hex( hexstr ));
22881               
22882             
22883         this.hexStore.splice(0)
22884         
22885     },
22886     
22887     cmdgroupstart : function()
22888     {
22889         this.flushHexStore();
22890         if (this.group) {
22891             this.groupStack.push(this.group);
22892         }
22893          // parent..
22894         if (this.doc === false) {
22895             this.group = this.doc = new Roo.rtf.Document();
22896             return;
22897             
22898         }
22899         this.group = new Roo.rtf.Group(this.group);
22900     },
22901     cmdignorable : function()
22902     {
22903         this.flushHexStore();
22904         this.group.ignorable = true;
22905     },
22906     cmdendparagraph : function()
22907     {
22908         this.flushHexStore();
22909         this.group.addContent(new Roo.rtf.Paragraph());
22910     },
22911     cmdgroupend : function ()
22912     {
22913         this.flushHexStore();
22914         var endingGroup = this.group;
22915         
22916         
22917         this.group = this.groupStack.pop();
22918         if (this.group) {
22919             this.group.addChild(endingGroup);
22920         }
22921         
22922         
22923         
22924         var doc = this.group || this.doc;
22925         //if (endingGroup instanceof FontTable) {
22926         //  doc.fonts = endingGroup.table
22927         //} else if (endingGroup instanceof ColorTable) {
22928         //  doc.colors = endingGroup.table
22929         //} else if (endingGroup !== this.doc && !endingGroup.get('ignorable')) {
22930         if (endingGroup.ignorable === false) {
22931             //code
22932             this.groups.push(endingGroup);
22933            // Roo.log( endingGroup );
22934         }
22935             //Roo.each(endingGroup.content, function(item)) {
22936             //    doc.addContent(item);
22937             //}
22938             //process.emit('debug', 'GROUP END', endingGroup.type, endingGroup.get('ignorable'))
22939         //}
22940     },
22941     cmdtext : function (cmd)
22942     {
22943         this.flushHexStore();
22944         if (!this.group) { // an RTF fragment, missing the {\rtf1 header
22945             //this.group = this.doc
22946             return;  // we really don't care about stray text...
22947         }
22948         this.group.addContent(new Roo.rtf.Span(cmd));
22949     },
22950     cmdcontrolword : function (cmd)
22951     {
22952         this.flushHexStore();
22953         if (!this.group.type) {
22954             this.group.type = cmd.value;
22955             return;
22956         }
22957         this.group.addContent(new Roo.rtf.Ctrl(cmd));
22958         // we actually don't care about ctrl words...
22959         return ;
22960         /*
22961         var method = 'ctrl$' + cmd.value.replace(/-(.)/g, (_, char) => char.toUpperCase())
22962         if (this[method]) {
22963             this[method](cmd.param)
22964         } else {
22965             if (!this.group.get('ignorable')) process.emit('debug', method, cmd.param)
22966         }
22967         */
22968     },
22969     cmdhexchar : function(cmd) {
22970         this.hexStore.push(cmd);
22971     },
22972     cmderror : function(cmd) {
22973         throw cmd.value;
22974     },
22975     
22976     /*
22977       _flush (done) {
22978         if (this.text !== '\u0000') this.emitText()
22979         done()
22980       }
22981       */
22982       
22983       
22984     parseText : function(c)
22985     {
22986         if (c === '\\') {
22987             this.parserState = this.parseEscapes;
22988         } else if (c === '{') {
22989             this.emitStartGroup();
22990         } else if (c === '}') {
22991             this.emitEndGroup();
22992         } else if (c === '\x0A' || c === '\x0D') {
22993             // cr/lf are noise chars
22994         } else {
22995             this.text += c;
22996         }
22997     },
22998     
22999     parseEscapes: function (c)
23000     {
23001         if (c === '\\' || c === '{' || c === '}') {
23002             this.text += c;
23003             this.parserState = this.parseText;
23004         } else {
23005             this.parserState = this.parseControlSymbol;
23006             this.parseControlSymbol(c);
23007         }
23008     },
23009     parseControlSymbol: function(c)
23010     {
23011         if (c === '~') {
23012             this.text += '\u00a0'; // nbsp
23013             this.parserState = this.parseText
23014         } else if (c === '-') {
23015              this.text += '\u00ad'; // soft hyphen
23016         } else if (c === '_') {
23017             this.text += '\u2011'; // non-breaking hyphen
23018         } else if (c === '*') {
23019             this.emitIgnorable();
23020             this.parserState = this.parseText;
23021         } else if (c === "'") {
23022             this.parserState = this.parseHexChar;
23023         } else if (c === '|') { // formula cacter
23024             this.emitFormula();
23025             this.parserState = this.parseText;
23026         } else if (c === ':') { // subentry in an index entry
23027             this.emitIndexSubEntry();
23028             this.parserState = this.parseText;
23029         } else if (c === '\x0a') {
23030             this.emitEndParagraph();
23031             this.parserState = this.parseText;
23032         } else if (c === '\x0d') {
23033             this.emitEndParagraph();
23034             this.parserState = this.parseText;
23035         } else {
23036             this.parserState = this.parseControlWord;
23037             this.parseControlWord(c);
23038         }
23039     },
23040     parseHexChar: function (c)
23041     {
23042         if (/^[A-Fa-f0-9]$/.test(c)) {
23043             this.hexChar += c;
23044             if (this.hexChar.length >= 2) {
23045               this.emitHexChar();
23046               this.parserState = this.parseText;
23047             }
23048             return;
23049         }
23050         this.emitError("Invalid character \"" + c + "\" in hex literal.");
23051         this.parserState = this.parseText;
23052         
23053     },
23054     parseControlWord : function(c)
23055     {
23056         if (c === ' ') {
23057             this.emitControlWord();
23058             this.parserState = this.parseText;
23059         } else if (/^[-\d]$/.test(c)) {
23060             this.parserState = this.parseControlWordParam;
23061             this.controlWordParam += c;
23062         } else if (/^[A-Za-z]$/.test(c)) {
23063           this.controlWord += c;
23064         } else {
23065           this.emitControlWord();
23066           this.parserState = this.parseText;
23067           this.parseText(c);
23068         }
23069     },
23070     parseControlWordParam : function (c) {
23071         if (/^\d$/.test(c)) {
23072           this.controlWordParam += c;
23073         } else if (c === ' ') {
23074           this.emitControlWord();
23075           this.parserState = this.parseText;
23076         } else {
23077           this.emitControlWord();
23078           this.parserState = this.parseText;
23079           this.parseText(c);
23080         }
23081     },
23082     
23083     
23084     
23085     
23086     emitText : function () {
23087         if (this.text === '') {
23088             return;
23089         }
23090         this.push({
23091             type: 'text',
23092             value: this.text,
23093             pos: this.cpos,
23094             row: this.row,
23095             col: this.col
23096         });
23097         this.text = ''
23098     },
23099     emitControlWord : function ()
23100     {
23101         this.emitText();
23102         if (this.controlWord === '') {
23103             // do we want to track this - it seems just to cause problems.
23104             //this.emitError('empty control word');
23105         } else {
23106             this.push({
23107                   type: 'controlword',
23108                   value: this.controlWord,
23109                   param: this.controlWordParam !== '' && Number(this.controlWordParam),
23110                   pos: this.cpos,
23111                   row: this.row,
23112                   col: this.col
23113             });
23114         }
23115         this.controlWord = '';
23116         this.controlWordParam = '';
23117     },
23118     emitStartGroup : function ()
23119     {
23120         this.emitText();
23121         this.push({
23122             type: 'groupstart',
23123             pos: this.cpos,
23124             row: this.row,
23125             col: this.col
23126         });
23127     },
23128     emitEndGroup : function ()
23129     {
23130         this.emitText();
23131         this.push({
23132             type: 'groupend',
23133             pos: this.cpos,
23134             row: this.row,
23135             col: this.col
23136         });
23137     },
23138     emitIgnorable : function ()
23139     {
23140         this.emitText();
23141         this.push({
23142             type: 'ignorable',
23143             pos: this.cpos,
23144             row: this.row,
23145             col: this.col
23146         });
23147     },
23148     emitHexChar : function ()
23149     {
23150         this.emitText();
23151         this.push({
23152             type: 'hexchar',
23153             value: this.hexChar,
23154             pos: this.cpos,
23155             row: this.row,
23156             col: this.col
23157         });
23158         this.hexChar = ''
23159     },
23160     emitError : function (message)
23161     {
23162       this.emitText();
23163       this.push({
23164             type: 'error',
23165             value: message,
23166             row: this.row,
23167             col: this.col,
23168             char: this.cpos //,
23169             //stack: new Error().stack
23170         });
23171     },
23172     emitEndParagraph : function () {
23173         this.emitText();
23174         this.push({
23175             type: 'endparagraph',
23176             pos: this.cpos,
23177             row: this.row,
23178             col: this.col
23179         });
23180     }
23181      
23182 } ;
23183 Roo.htmleditor = {};
23184  
23185 /**
23186  * @class Roo.htmleditor.Filter
23187  * Base Class for filtering htmleditor stuff. - do not use this directly - extend it.
23188  * @cfg {DomElement} node The node to iterate and filter
23189  * @cfg {boolean|String|Array} tag Tags to replace 
23190  * @constructor
23191  * Create a new Filter.
23192  * @param {Object} config Configuration options
23193  */
23194
23195
23196
23197 Roo.htmleditor.Filter = function(cfg) {
23198     Roo.apply(this.cfg);
23199     // this does not actually call walk as it's really just a abstract class
23200 }
23201
23202
23203 Roo.htmleditor.Filter.prototype = {
23204     
23205     node: false,
23206     
23207     tag: false,
23208
23209     // overrride to do replace comments.
23210     replaceComment : false,
23211     
23212     // overrride to do replace or do stuff with tags..
23213     replaceTag : false,
23214     
23215     walk : function(dom)
23216     {
23217         Roo.each( Array.from(dom.childNodes), function( e ) {
23218             switch(true) {
23219                 
23220                 case e.nodeType == 8 &&  this.replaceComment  !== false: // comment
23221                     this.replaceComment(e);
23222                     return;
23223                 
23224                 case e.nodeType != 1: //not a node.
23225                     return;
23226                 
23227                 case this.tag === true: // everything
23228                 case e.tagName.indexOf(":") > -1 && typeof(this.tag) == 'object' && this.tag.indexOf(":") > -1:
23229                 case e.tagName.indexOf(":") > -1 && typeof(this.tag) == 'string' && this.tag == ":":
23230                 case typeof(this.tag) == 'object' && this.tag.indexOf(e.tagName) > -1: // array and it matches.
23231                 case typeof(this.tag) == 'string' && this.tag == e.tagName: // array and it matches.
23232                     if (this.replaceTag && false === this.replaceTag(e)) {
23233                         return;
23234                     }
23235                     if (e.hasChildNodes()) {
23236                         this.walk(e);
23237                     }
23238                     return;
23239                 
23240                 default:    // tags .. that do not match.
23241                     if (e.hasChildNodes()) {
23242                         this.walk(e);
23243                     }
23244             }
23245             
23246         }, this);
23247         
23248     },
23249     
23250     
23251     removeNodeKeepChildren : function( node)
23252     {
23253     
23254         ar = Array.from(node.childNodes);
23255         for (var i = 0; i < ar.length; i++) {
23256          
23257             node.removeChild(ar[i]);
23258             // what if we need to walk these???
23259             node.parentNode.insertBefore(ar[i], node);
23260            
23261         }
23262         node.parentNode.removeChild(node);
23263     },
23264
23265     searchTag : function(dom)
23266     {
23267         if(this.tag === false) {
23268             return;
23269         }
23270
23271         var els = dom.getElementsByTagName(this.tag);
23272
23273         Roo.each(Array.from(els), function(e){
23274             if(e.parentNode == null) {
23275                 return;
23276             }
23277             if(this.replaceTag) {
23278                 this.replaceTag(e);
23279             }
23280         }, this);
23281     }
23282 }; 
23283
23284 /**
23285  * @class Roo.htmleditor.FilterAttributes
23286  * clean attributes and  styles including http:// etc.. in attribute
23287  * @constructor
23288 * Run a new Attribute Filter
23289 * @param {Object} config Configuration options
23290  */
23291 Roo.htmleditor.FilterAttributes = function(cfg)
23292 {
23293     Roo.apply(this, cfg);
23294     this.attrib_black = this.attrib_black || [];
23295     this.attrib_white = this.attrib_white || [];
23296
23297     this.attrib_clean = this.attrib_clean || [];
23298     this.style_white = this.style_white || [];
23299     this.style_black = this.style_black || [];
23300     this.walk(cfg.node);
23301 }
23302
23303 Roo.extend(Roo.htmleditor.FilterAttributes, Roo.htmleditor.Filter,
23304 {
23305     tag: true, // all tags
23306     
23307     attrib_black : false, // array
23308     attrib_clean : false,
23309     attrib_white : false,
23310
23311     style_white : false,
23312     style_black : false,
23313      
23314      
23315     replaceTag : function(node)
23316     {
23317         if (!node.attributes || !node.attributes.length) {
23318             return true;
23319         }
23320         
23321         for (var i = node.attributes.length-1; i > -1 ; i--) {
23322             var a = node.attributes[i];
23323             //console.log(a);
23324             if (this.attrib_white.length && this.attrib_white.indexOf(a.name.toLowerCase()) < 0) {
23325                 node.removeAttribute(a.name);
23326                 continue;
23327             }
23328             
23329             
23330             
23331             if (a.name.toLowerCase().substr(0,2)=='on')  {
23332                 node.removeAttribute(a.name);
23333                 continue;
23334             }
23335             
23336             
23337             if (this.attrib_black.indexOf(a.name.toLowerCase()) > -1) {
23338                 node.removeAttribute(a.name);
23339                 continue;
23340             }
23341             if (this.attrib_clean.indexOf(a.name.toLowerCase()) > -1) {
23342                 this.cleanAttr(node,a.name,a.value); // fixme..
23343                 continue;
23344             }
23345             if (a.name == 'style') {
23346                 this.cleanStyle(node,a.name,a.value);
23347                 continue;
23348             }
23349             /// clean up MS crap..
23350             // tecnically this should be a list of valid class'es..
23351             
23352             
23353             if (a.name == 'class') {
23354                 if (a.value.match(/^Mso/)) {
23355                     node.removeAttribute('class');
23356                 }
23357                 
23358                 if (a.value.match(/^body$/)) {
23359                     node.removeAttribute('class');
23360                 }
23361                 continue;
23362             }
23363             
23364             
23365             // style cleanup!?
23366             // class cleanup?
23367             
23368         }
23369         return true; // clean children
23370     },
23371         
23372     cleanAttr: function(node, n,v)
23373     {
23374         
23375         if (v.match(/^\./) || v.match(/^\//)) {
23376             return;
23377         }
23378         if (v.match(/^(http|https):\/\//)
23379             || v.match(/^mailto:/) 
23380             || v.match(/^ftp:/)
23381             || v.match(/^data:/)
23382             ) {
23383             return;
23384         }
23385         if (v.match(/^#/)) {
23386             return;
23387         }
23388         if (v.match(/^\{/)) { // allow template editing.
23389             return;
23390         }
23391 //            Roo.log("(REMOVE TAG)"+ node.tagName +'.' + n + '=' + v);
23392         node.removeAttribute(n);
23393         
23394     },
23395     cleanStyle : function(node,  n,v)
23396     {
23397         if (v.match(/expression/)) { //XSS?? should we even bother..
23398             node.removeAttribute(n);
23399             return;
23400         }
23401         
23402         var parts = v.split(/;/);
23403         var clean = [];
23404         
23405         Roo.each(parts, function(p) {
23406             p = p.replace(/^\s+/g,'').replace(/\s+$/g,'');
23407             if (!p.length) {
23408                 return true;
23409             }
23410             var l = p.split(':').shift().replace(/\s+/g,'');
23411             l = l.replace(/^\s+/g,'').replace(/\s+$/g,'');
23412             
23413             if ( this.style_black.length && (this.style_black.indexOf(l) > -1 || this.style_black.indexOf(l.toLowerCase()) > -1)) {
23414                 return true;
23415             }
23416             //Roo.log()
23417             // only allow 'c whitelisted system attributes'
23418             if ( this.style_white.length &&  style_white.indexOf(l) < 0 && style_white.indexOf(l.toLowerCase()) < 0 ) {
23419                 return true;
23420             }
23421             
23422             
23423             clean.push(p);
23424             return true;
23425         },this);
23426         if (clean.length) { 
23427             node.setAttribute(n, clean.join(';'));
23428         } else {
23429             node.removeAttribute(n);
23430         }
23431         
23432     }
23433         
23434         
23435         
23436     
23437 });/**
23438  * @class Roo.htmleditor.FilterBlack
23439  * remove blacklisted elements.
23440  * @constructor
23441  * Run a new Blacklisted Filter
23442  * @param {Object} config Configuration options
23443  */
23444
23445 Roo.htmleditor.FilterBlack = function(cfg)
23446 {
23447     Roo.apply(this, cfg);
23448     this.walk(cfg.node);
23449 }
23450
23451 Roo.extend(Roo.htmleditor.FilterBlack, Roo.htmleditor.Filter,
23452 {
23453     tag : true, // all elements.
23454    
23455     replaceTag : function(n)
23456     {
23457         n.parentNode.removeChild(n);
23458     }
23459 });
23460 /**
23461  * @class Roo.htmleditor.FilterComment
23462  * remove comments.
23463  * @constructor
23464 * Run a new Comments Filter
23465 * @param {Object} config Configuration options
23466  */
23467 Roo.htmleditor.FilterComment = function(cfg)
23468 {
23469     this.walk(cfg.node);
23470 }
23471
23472 Roo.extend(Roo.htmleditor.FilterComment, Roo.htmleditor.Filter,
23473 {
23474   
23475     replaceComment : function(n)
23476     {
23477         n.parentNode.removeChild(n);
23478     }
23479 });/**
23480  * @class Roo.htmleditor.FilterEmpty
23481  * filter empty elements
23482  * @constructor
23483  * Run a new Empty Filter
23484  * @param {Object} config Configuration options
23485  */
23486
23487 Roo.htmleditor.FilterEmpty = function(cfg)
23488 {
23489     // no need to apply config.
23490     this.walk(cfg.node);
23491 }
23492
23493 Roo.extend(Roo.htmleditor.FilterEmpty, Roo.htmleditor.FilterBlack,
23494 {
23495      
23496     tag : true,
23497      
23498  
23499     replaceTag : function(node)
23500     {
23501         // start from leaf node
23502         if(node.hasChildNodes()) {
23503             this.walk(node);
23504         }
23505
23506         // only filter empty leaf element with certain tags
23507         if(
23508             ['B', 'I', 'U', 'S'].indexOf(node.tagName) < 0
23509             ||
23510             node.attributes && node.attributes.length > 0
23511             ||
23512             node.hasChildNodes()
23513         ) {
23514             return false; // don't walk
23515         }
23516
23517         Roo.htmleditor.FilterBlack.prototype.replaceTag.call(this, node);
23518         return false; // don't walk
23519      
23520     }
23521     
23522 });/**
23523  * @class Roo.htmleditor.FilterKeepChildren
23524  * remove tags but keep children
23525  * @constructor
23526  * Run a new Keep Children Filter
23527  * @param {Object} config Configuration options
23528  */
23529
23530 Roo.htmleditor.FilterKeepChildren = function(cfg)
23531 {
23532     Roo.apply(this, cfg);
23533     if (this.tag === false) {
23534         return; // dont walk.. (you can use this to use this just to do a child removal on a single tag )
23535     }
23536     // hacky?
23537     if ((typeof(this.tag) == 'object' && this.tag.indexOf(":") > -1)) {
23538         this.cleanNamespace = true;
23539     }
23540         
23541     this.walk(cfg.node);
23542 }
23543
23544 Roo.extend(Roo.htmleditor.FilterKeepChildren, Roo.htmleditor.FilterBlack,
23545 {
23546     cleanNamespace : false, // should really be an option, rather than using ':' inside of this tag.
23547   
23548     replaceTag : function(node)
23549     {
23550         // walk children...
23551         //Roo.log(node.tagName);
23552         var ar = Array.from(node.childNodes);
23553         //remove first..
23554         
23555         for (var i = 0; i < ar.length; i++) {
23556             var e = ar[i];
23557             if (e.nodeType == 1) {
23558                 if (
23559                     (typeof(this.tag) == 'object' && this.tag.indexOf(e.tagName) > -1)
23560                     || // array and it matches
23561                     (typeof(this.tag) == 'string' && this.tag == e.tagName)
23562                     ||
23563                     (e.tagName.indexOf(":") > -1 && typeof(this.tag) == 'object' && this.tag.indexOf(":") > -1)
23564                     ||
23565                     (e.tagName.indexOf(":") > -1 && typeof(this.tag) == 'string' && this.tag == ":")
23566                 ) {
23567                     this.replaceTag(ar[i]); // child is blacklisted as well...
23568                     continue;
23569                 }
23570             }
23571         }  
23572         ar = Array.from(node.childNodes);
23573         for (var i = 0; i < ar.length; i++) {
23574          
23575             node.removeChild(ar[i]);
23576             // what if we need to walk these???
23577             node.parentNode.insertBefore(ar[i], node);
23578             if (this.tag !== false) {
23579                 this.walk(ar[i]);
23580                 
23581             }
23582         }
23583         //Roo.log("REMOVE:" + node.tagName);
23584         node.parentNode.removeChild(node);
23585         return false; // don't walk children
23586         
23587         
23588     }
23589 });/**
23590  * @class Roo.htmleditor.FilterParagraph
23591  * paragraphs cause a nightmare for shared content - this filter is designed to be called ? at various points when editing
23592  * like on 'push' to remove the <p> tags and replace them with line breaks.
23593  * @constructor
23594  * Run a new Paragraph Filter
23595  * @param {Object} config Configuration options
23596  */
23597
23598 Roo.htmleditor.FilterParagraph = function(cfg)
23599 {
23600     // no need to apply config.
23601     this.searchTag(cfg.node);
23602 }
23603
23604 Roo.extend(Roo.htmleditor.FilterParagraph, Roo.htmleditor.Filter,
23605 {
23606     
23607      
23608     tag : 'P',
23609     
23610      
23611     replaceTag : function(node)
23612     {
23613         
23614         if (node.childNodes.length == 1 &&
23615             node.childNodes[0].nodeType == 3 &&
23616             node.childNodes[0].textContent.trim().length < 1
23617             ) {
23618             // remove and replace with '<BR>';
23619             node.parentNode.replaceChild(node.ownerDocument.createElement('BR'),node);
23620             return false; // no need to walk..
23621         }
23622
23623         var ar = Array.from(node.childNodes);
23624         for (var i = 0; i < ar.length; i++) {
23625             node.removeChild(ar[i]);
23626             // what if we need to walk these???
23627             node.parentNode.insertBefore(ar[i], node);
23628         }
23629         // now what about this?
23630         // <p> &nbsp; </p>
23631         
23632         // double BR.
23633         node.parentNode.insertBefore(node.ownerDocument.createElement('BR'), node);
23634         node.parentNode.insertBefore(node.ownerDocument.createElement('BR'), node);
23635         node.parentNode.removeChild(node);
23636         
23637         return false;
23638
23639     }
23640     
23641 });/**
23642  * @class Roo.htmleditor.FilterHashLink
23643  * remove hash link
23644  * @constructor
23645  * Run a new Hash Link Filter
23646  * @param {Object} config Configuration options
23647  */
23648
23649  Roo.htmleditor.FilterHashLink = function(cfg)
23650  {
23651      // no need to apply config.
23652     //  this.walk(cfg.node);
23653     this.searchTag(cfg.node);
23654  }
23655  
23656  Roo.extend(Roo.htmleditor.FilterHashLink, Roo.htmleditor.Filter,
23657  {
23658       
23659      tag : 'A',
23660      
23661       
23662      replaceTag : function(node)
23663      {
23664          for(var i = 0; i < node.attributes.length; i ++) {
23665              var a = node.attributes[i];
23666
23667              if(a.name.toLowerCase() == 'href' && a.value.startsWith('#')) {
23668                  this.removeNodeKeepChildren(node);
23669              }
23670          }
23671          
23672          return false;
23673  
23674      }
23675      
23676  });/**
23677  * @class Roo.htmleditor.FilterSpan
23678  * filter span's with no attributes out..
23679  * @constructor
23680  * Run a new Span Filter
23681  * @param {Object} config Configuration options
23682  */
23683
23684 Roo.htmleditor.FilterSpan = function(cfg)
23685 {
23686     // no need to apply config.
23687     this.searchTag(cfg.node);
23688 }
23689
23690 Roo.extend(Roo.htmleditor.FilterSpan, Roo.htmleditor.FilterKeepChildren,
23691 {
23692      
23693     tag : 'SPAN',
23694      
23695  
23696     replaceTag : function(node)
23697     {
23698         if (node.attributes && node.attributes.length > 0) {
23699             return true; // walk if there are any.
23700         }
23701         Roo.htmleditor.FilterKeepChildren.prototype.replaceTag.call(this, node);
23702         return false;
23703      
23704     }
23705     
23706 });/**
23707  * @class Roo.htmleditor.FilterTableWidth
23708   try and remove table width data - as that frequently messes up other stuff.
23709  * 
23710  *      was cleanTableWidths.
23711  *
23712  * Quite often pasting from word etc.. results in tables with column and widths.
23713  * This does not work well on fluid HTML layouts - like emails. - so this code should hunt an destroy them..
23714  *
23715  * @constructor
23716  * Run a new Table Filter
23717  * @param {Object} config Configuration options
23718  */
23719
23720 Roo.htmleditor.FilterTableWidth = function(cfg)
23721 {
23722     // no need to apply config.
23723     this.tag = ['TABLE', 'TD', 'TR', 'TH', 'THEAD', 'TBODY' ];
23724     this.walk(cfg.node);
23725 }
23726
23727 Roo.extend(Roo.htmleditor.FilterTableWidth, Roo.htmleditor.Filter,
23728 {
23729      
23730      
23731     
23732     replaceTag: function(node) {
23733         
23734         
23735       
23736         if (node.hasAttribute('width')) {
23737             node.removeAttribute('width');
23738         }
23739         
23740          
23741         if (node.hasAttribute("style")) {
23742             // pretty basic...
23743             
23744             var styles = node.getAttribute("style").split(";");
23745             var nstyle = [];
23746             Roo.each(styles, function(s) {
23747                 if (!s.match(/:/)) {
23748                     return;
23749                 }
23750                 var kv = s.split(":");
23751                 if (kv[0].match(/^\s*(width|min-width)\s*$/)) {
23752                     return;
23753                 }
23754                 // what ever is left... we allow.
23755                 nstyle.push(s);
23756             });
23757             node.setAttribute("style", nstyle.length ? nstyle.join(';') : '');
23758             if (!nstyle.length) {
23759                 node.removeAttribute('style');
23760             }
23761         }
23762         
23763         return true; // continue doing children..
23764     }
23765 });/**
23766  * @class Roo.htmleditor.FilterWord
23767  * try and clean up all the mess that Word generates.
23768  * 
23769  * This is the 'nice version' - see 'Heavy' that white lists a very short list of elements, and multi-filters 
23770  
23771  * @constructor
23772  * Run a new Span Filter
23773  * @param {Object} config Configuration options
23774  */
23775
23776 Roo.htmleditor.FilterWord = function(cfg)
23777 {
23778     // no need to apply config.
23779     this.replaceDocBullets(cfg.node);
23780     
23781     this.replaceAname(cfg.node);
23782     // this is disabled as the removal is done by other filters;
23783    // this.walk(cfg.node);
23784     this.replaceImageTable(cfg.node);
23785     
23786 }
23787
23788 Roo.extend(Roo.htmleditor.FilterWord, Roo.htmleditor.Filter,
23789 {
23790     tag: true,
23791      
23792     
23793     /**
23794      * Clean up MS wordisms...
23795      */
23796     replaceTag : function(node)
23797     {
23798          
23799         // no idea what this does - span with text, replaceds with just text.
23800         if(
23801                 node.nodeName == 'SPAN' &&
23802                 !node.hasAttributes() &&
23803                 node.childNodes.length == 1 &&
23804                 node.firstChild.nodeName == "#text"  
23805         ) {
23806             var textNode = node.firstChild;
23807             node.removeChild(textNode);
23808             if (node.getAttribute('lang') != 'zh-CN') {   // do not space pad on chinese characters..
23809                 node.parentNode.insertBefore(node.ownerDocument.createTextNode(" "), node);
23810             }
23811             node.parentNode.insertBefore(textNode, node);
23812             if (node.getAttribute('lang') != 'zh-CN') {   // do not space pad on chinese characters..
23813                 node.parentNode.insertBefore(node.ownerDocument.createTextNode(" ") , node);
23814             }
23815             
23816             node.parentNode.removeChild(node);
23817             return false; // dont do chidren - we have remove our node - so no need to do chdhilren?
23818         }
23819         
23820    
23821         
23822         if (node.tagName.toLowerCase().match(/^(style|script|applet|embed|noframes|noscript)$/)) {
23823             node.parentNode.removeChild(node);
23824             return false; // dont do chidlren
23825         }
23826         //Roo.log(node.tagName);
23827         // remove - but keep children..
23828         if (node.tagName.toLowerCase().match(/^(meta|link|\\?xml:|st1:|o:|v:|font)/)) {
23829             //Roo.log('-- removed');
23830             while (node.childNodes.length) {
23831                 var cn = node.childNodes[0];
23832                 node.removeChild(cn);
23833                 node.parentNode.insertBefore(cn, node);
23834                 // move node to parent - and clean it..
23835                 if (cn.nodeType == 1) {
23836                     this.replaceTag(cn);
23837                 }
23838                 
23839             }
23840             node.parentNode.removeChild(node);
23841             /// no need to iterate chidlren = it's got none..
23842             //this.iterateChildren(node, this.cleanWord);
23843             return false; // no need to iterate children.
23844         }
23845         // clean styles
23846         if (node.className.length) {
23847             
23848             var cn = node.className.split(/\W+/);
23849             var cna = [];
23850             Roo.each(cn, function(cls) {
23851                 if (cls.match(/Mso[a-zA-Z]+/)) {
23852                     return;
23853                 }
23854                 cna.push(cls);
23855             });
23856             node.className = cna.length ? cna.join(' ') : '';
23857             if (!cna.length) {
23858                 node.removeAttribute("class");
23859             }
23860         }
23861         
23862         if (node.hasAttribute("lang")) {
23863             node.removeAttribute("lang");
23864         }
23865         
23866         if (node.hasAttribute("style")) {
23867             
23868             var styles = node.getAttribute("style").split(";");
23869             var nstyle = [];
23870             Roo.each(styles, function(s) {
23871                 if (!s.match(/:/)) {
23872                     return;
23873                 }
23874                 var kv = s.split(":");
23875                 if (kv[0].match(/^(mso-|line|font|background|margin|padding|color)/)) {
23876                     return;
23877                 }
23878                 // what ever is left... we allow.
23879                 nstyle.push(s);
23880             });
23881             node.setAttribute("style", nstyle.length ? nstyle.join(';') : '');
23882             if (!nstyle.length) {
23883                 node.removeAttribute('style');
23884             }
23885         }
23886         return true; // do children
23887         
23888         
23889         
23890     },
23891     
23892     styleToObject: function(node)
23893     {
23894         var styles = (node.getAttribute("style") || '').split(";");
23895         var ret = {};
23896         Roo.each(styles, function(s) {
23897             if (!s.match(/:/)) {
23898                 return;
23899             }
23900             var kv = s.split(":");
23901              
23902             // what ever is left... we allow.
23903             ret[kv[0].trim()] = kv[1];
23904         });
23905         return ret;
23906     },
23907     
23908     
23909     replaceAname : function (doc)
23910     {
23911         // replace all the a/name without..
23912         var aa = Array.from(doc.getElementsByTagName('a'));
23913         for (var i = 0; i  < aa.length; i++) {
23914             var a = aa[i];
23915             if (a.hasAttribute("name")) {
23916                 a.removeAttribute("name");
23917             }
23918             if (a.hasAttribute("href")) {
23919                 continue;
23920             }
23921             // reparent children.
23922             this.removeNodeKeepChildren(a);
23923             
23924         }
23925         
23926         
23927         
23928     },
23929
23930     
23931     
23932     replaceDocBullets : function(doc)
23933     {
23934         // this is a bit odd - but it appears some indents use ql-indent-1
23935          //Roo.log(doc.innerHTML);
23936         
23937         var listpara = Array.from(doc.getElementsByClassName('MsoListParagraphCxSpFirst'));
23938         for( var i = 0; i < listpara.length; i ++) {
23939             listpara[i].className = "MsoListParagraph";
23940         }
23941         
23942         listpara =  Array.from(doc.getElementsByClassName('MsoListParagraphCxSpMiddle'));
23943         for( var i = 0; i < listpara.length; i ++) {
23944             listpara[i].className = "MsoListParagraph";
23945         }
23946         listpara =  Array.from(doc.getElementsByClassName('MsoListParagraphCxSpLast'));
23947         for( var i = 0; i < listpara.length; i ++) {
23948             listpara[i].className = "MsoListParagraph";
23949         }
23950         listpara =  Array.from(doc.getElementsByClassName('ql-indent-1'));
23951         for( var i = 0; i < listpara.length; i ++) {
23952             listpara[i].className = "MsoListParagraph";
23953         }
23954         
23955         // this is a bit hacky - we had one word document where h2 had a miso-list attribute.
23956         var htwo =  Array.from(doc.getElementsByTagName('h2'));
23957         for( var i = 0; i < htwo.length; i ++) {
23958             if (htwo[i].hasAttribute('style') && htwo[i].getAttribute('style').match(/mso-list:/)) {
23959                 htwo[i].className = "MsoListParagraph";
23960             }
23961         }
23962         listpara =  Array.from(doc.getElementsByClassName('MsoNormal'));
23963         for( var i = 0; i < listpara.length; i ++) {
23964             if (listpara[i].hasAttribute('style') && listpara[i].getAttribute('style').match(/mso-list:/)) {
23965                 listpara[i].className = "MsoListParagraph";
23966             } else {
23967                 listpara[i].className = "MsoNormalx";
23968             }
23969         }
23970        
23971         listpara = doc.getElementsByClassName('MsoListParagraph');
23972         // Roo.log(doc.innerHTML);
23973         
23974         
23975         
23976         while(listpara.length) {
23977             
23978             this.replaceDocBullet(listpara.item(0));
23979         }
23980       
23981     },
23982     
23983      
23984     
23985     replaceDocBullet : function(p)
23986     {
23987         // gather all the siblings.
23988         var ns = p,
23989             parent = p.parentNode,
23990             doc = parent.ownerDocument,
23991             items = [];
23992          
23993         //Roo.log("Parsing: " + p.innerText)    ;
23994         var listtype = 'ul';   
23995         while (ns) {
23996             if (ns.nodeType != 1) {
23997                 ns = ns.nextSibling;
23998                 continue;
23999             }
24000             if (!ns.className.match(/(MsoListParagraph|ql-indent-1)/i)) {
24001                 //Roo.log("Missing para r q1indent - got:" + ns.className);
24002                 break;
24003             }
24004             var spans = ns.getElementsByTagName('span');
24005             
24006             if (ns.hasAttribute('style') && ns.getAttribute('style').match(/mso-list/)) {
24007                 items.push(ns);
24008                 ns = ns.nextSibling;
24009                 has_list = true;
24010                 if (!spans.length) {
24011                     continue;
24012                 }
24013                 var ff = '';
24014                 var se = spans[0];
24015                 for (var i = 0; i < spans.length;i++) {
24016                     se = spans[i];
24017                     if (se.hasAttribute('style')  && se.hasAttribute('style') && se.style.fontFamily != '') {
24018                         ff = se.style.fontFamily;
24019                         break;
24020                     }
24021                 }
24022                  
24023                     
24024                 //Roo.log("got font family: " + ff);
24025                 if (typeof(ff) != 'undefined' && !ff.match(/(Symbol|Wingdings)/) && "·o".indexOf(se.innerText.trim()) < 0) {
24026                     listtype = 'ol';
24027                 }
24028                 
24029                 continue;
24030             }
24031             //Roo.log("no mso-list?");
24032             
24033             var spans = ns.getElementsByTagName('span');
24034             if (!spans.length) {
24035                 break;
24036             }
24037             var has_list  = false;
24038             for(var i = 0; i < spans.length; i++) {
24039                 if (spans[i].hasAttribute('style') && spans[i].getAttribute('style').match(/mso-list/)) {
24040                     has_list = true;
24041                     break;
24042                 }
24043             }
24044             if (!has_list) {
24045                 break;
24046             }
24047             items.push(ns);
24048             ns = ns.nextSibling;
24049             
24050             
24051         }
24052         if (!items.length) {
24053             ns.className = "";
24054             return;
24055         }
24056         
24057         var ul = parent.ownerDocument.createElement(listtype); // what about number lists...
24058         parent.insertBefore(ul, p);
24059         var lvl = 0;
24060         var stack = [ ul ];
24061         var last_li = false;
24062         
24063         var margin_to_depth = {};
24064         max_margins = -1;
24065         
24066         items.forEach(function(n, ipos) {
24067             //Roo.log("got innertHMLT=" + n.innerHTML);
24068             
24069             var spans = n.getElementsByTagName('span');
24070             if (!spans.length) {
24071                 //Roo.log("No spans found");
24072                  
24073                 parent.removeChild(n);
24074                 
24075                 
24076                 return; // skip it...
24077             }
24078            
24079                 
24080             var num = 1;
24081             var style = {};
24082             for(var i = 0; i < spans.length; i++) {
24083             
24084                 style = this.styleToObject(spans[i]);
24085                 if (typeof(style['mso-list']) == 'undefined') {
24086                     continue;
24087                 }
24088                 if (listtype == 'ol') {
24089                    num = spans[i].innerText.replace(/[^0-9]+]/g,'')  * 1;
24090                 }
24091                 spans[i].parentNode.removeChild(spans[i]); // remove the fake bullet.
24092                 break;
24093             }
24094             //Roo.log("NOW GOT innertHMLT=" + n.innerHTML);
24095             style = this.styleToObject(n); // mo-list is from the parent node.
24096             if (typeof(style['mso-list']) == 'undefined') {
24097                 //Roo.log("parent is missing level");
24098                   
24099                 parent.removeChild(n);
24100                  
24101                 return;
24102             }
24103             
24104             var margin = style['margin-left'];
24105             if (typeof(margin_to_depth[margin]) == 'undefined') {
24106                 max_margins++;
24107                 margin_to_depth[margin] = max_margins;
24108             }
24109             nlvl = margin_to_depth[margin] ;
24110              
24111             if (nlvl > lvl) {
24112                 //new indent
24113                 var nul = doc.createElement(listtype); // what about number lists...
24114                 if (!last_li) {
24115                     last_li = doc.createElement('li');
24116                     stack[lvl].appendChild(last_li);
24117                 }
24118                 last_li.appendChild(nul);
24119                 stack[nlvl] = nul;
24120                 
24121             }
24122             lvl = nlvl;
24123             
24124             // not starting at 1..
24125             if (!stack[nlvl].hasAttribute("start") && listtype == "ol") {
24126                 stack[nlvl].setAttribute("start", num);
24127             }
24128             
24129             var nli = stack[nlvl].appendChild(doc.createElement('li'));
24130             last_li = nli;
24131             nli.innerHTML = n.innerHTML;
24132             //Roo.log("innerHTML = " + n.innerHTML);
24133             parent.removeChild(n);
24134             
24135              
24136              
24137             
24138         },this);
24139         
24140         
24141         
24142         
24143     },
24144     
24145     replaceImageTable : function(doc)
24146     {
24147          /*
24148           <table cellpadding=0 cellspacing=0 align=left>
24149   <tr>
24150    <td width=423 height=0></td>
24151   </tr>
24152   <tr>
24153    <td></td>
24154    <td><img width=601 height=401
24155    src="file:///C:/Users/Alan/AppData/Local/Temp/msohtmlclip1/01/clip_image002.jpg"
24156    v:shapes="Picture_x0020_2"></td>
24157   </tr>
24158  </table>
24159  */
24160         var imgs = Array.from(doc.getElementsByTagName('img'));
24161         Roo.each(imgs, function(img) {
24162             var td = img.parentNode;
24163             if (td.nodeName !=  'TD') {
24164                 return;
24165             }
24166             var tr = td.parentNode;
24167             if (tr.nodeName !=  'TR') {
24168                 return;
24169             }
24170             var tbody = tr.parentNode;
24171             if (tbody.nodeName !=  'TBODY') {
24172                 return;
24173             }
24174             var table = tbody.parentNode;
24175             if (table.nodeName !=  'TABLE') {
24176                 return;
24177             }
24178             // first row..
24179             
24180             if (table.getElementsByTagName('tr').length != 2) {
24181                 return;
24182             }
24183             if (table.getElementsByTagName('td').length != 3) {
24184                 return;
24185             }
24186             if (table.innerText.trim() != '') {
24187                 return;
24188             }
24189             var p = table.parentNode;
24190             img.parentNode.removeChild(img);
24191             p.insertBefore(img, table);
24192             p.removeChild(table);
24193             
24194             
24195             
24196         });
24197         
24198       
24199     }
24200     
24201 });
24202 /**
24203  * @class Roo.htmleditor.FilterStyleToTag
24204  * part of the word stuff... - certain 'styles' should be converted to tags.
24205  * eg.
24206  *   font-weight: bold -> bold
24207  *   ?? super / subscrit etc..
24208  * 
24209  * @constructor
24210 * Run a new style to tag filter.
24211 * @param {Object} config Configuration options
24212  */
24213 Roo.htmleditor.FilterStyleToTag = function(cfg)
24214 {
24215     
24216     this.tags = {
24217         B  : [ 'fontWeight' , 'bold', 'font-weight'],
24218         I :  [ 'fontStyle' , 'italic', 'font-style'],
24219         //pre :  [ 'font-style' , 'italic'],
24220         // h1.. h6 ?? font-size?
24221         SUP : [ 'verticalAlign' , 'super', 'vertical-align'],
24222         SUB : [ 'verticalAlign' , 'sub', 'vertical-align']
24223         
24224         
24225     };
24226     
24227     Roo.apply(this, cfg);
24228      
24229     
24230     this.walk(cfg.node);
24231     
24232     
24233     
24234 }
24235
24236
24237 Roo.extend(Roo.htmleditor.FilterStyleToTag, Roo.htmleditor.Filter,
24238 {
24239     tag: true, // all tags
24240     
24241     tags : false,
24242     
24243     
24244     replaceTag : function(node)
24245     {
24246         
24247         
24248         if (node.getAttribute("style") === null) {
24249             return true;
24250         }
24251         var inject = [];
24252         for (var k in this.tags) {
24253             if (node.style[this.tags[k][0]] == this.tags[k][1]) {
24254                 inject.push(k);
24255                 node.style.removeProperty(this.tags[k][2]);
24256             }
24257         }
24258         if (!inject.length) {
24259             return true; 
24260         }
24261         var cn = Array.from(node.childNodes);
24262         var nn = node;
24263         Roo.each(inject, function(t) {
24264             var nc = node.ownerDocument.createElement(t);
24265             nn.appendChild(nc);
24266             nn = nc;
24267         });
24268         for(var i = 0;i < cn.length;i++) {
24269             node.removeChild(cn[i]);
24270             nn.appendChild(cn[i]);
24271         }
24272         return true /// iterate thru
24273     }
24274     
24275 })/**
24276  * @class Roo.htmleditor.FilterLongBr
24277  * BR/BR/BR - keep a maximum of 2...
24278  * @constructor
24279  * Run a new Long BR Filter
24280  * @param {Object} config Configuration options
24281  */
24282
24283 Roo.htmleditor.FilterLongBr = function(cfg)
24284 {
24285     // no need to apply config.
24286     this.searchTag(cfg.node);
24287 }
24288
24289 Roo.extend(Roo.htmleditor.FilterLongBr, Roo.htmleditor.Filter,
24290 {
24291     
24292      
24293     tag : 'BR',
24294     
24295      
24296     replaceTag : function(node)
24297     {
24298         
24299         var ps = node.nextSibling;
24300         while (ps && ps.nodeType == 3 && ps.nodeValue.trim().length < 1) {
24301             ps = ps.nextSibling;
24302         }
24303         
24304         if (!ps &&  [ 'TD', 'TH', 'LI', 'H1', 'H2', 'H3', 'H4', 'H5', 'H6' ].indexOf(node.parentNode.tagName) > -1) { 
24305             node.parentNode.removeChild(node); // remove last BR inside one fo these tags
24306             return false;
24307         }
24308         
24309         if (!ps || ps.nodeType != 1) {
24310             return false;
24311         }
24312         
24313         if (!ps || ps.tagName != 'BR') {
24314            
24315             return false;
24316         }
24317         
24318         
24319         
24320         if (!node.previousSibling) {
24321             return false;
24322         }
24323         var ps = node.previousSibling;
24324         
24325         while (ps && ps.nodeType == 3 && ps.nodeValue.trim().length < 1) {
24326             ps = ps.previousSibling;
24327         }
24328         if (!ps || ps.nodeType != 1) {
24329             return false;
24330         }
24331         // if header or BR before.. then it's a candidate for removal.. - as we only want '2' of these..
24332         if (!ps || [ 'BR', 'H1', 'H2', 'H3', 'H4', 'H5', 'H6' ].indexOf(ps.tagName) < 0) {
24333             return false;
24334         }
24335         
24336         node.parentNode.removeChild(node); // remove me...
24337         
24338         return false; // no need to do children
24339
24340     }
24341     
24342 }); 
24343
24344 /**
24345  * @class Roo.htmleditor.FilterBlock
24346  * removes id / data-block and contenteditable that are associated with blocks
24347  * usage should be done on a cloned copy of the dom
24348  * @constructor
24349 * Run a new Attribute Filter { node : xxxx }}
24350 * @param {Object} config Configuration options
24351  */
24352 Roo.htmleditor.FilterBlock = function(cfg)
24353 {
24354     Roo.apply(this, cfg);
24355     var qa = cfg.node.querySelectorAll;
24356     this.removeAttributes('data-block');
24357     this.removeAttributes('contenteditable');
24358     this.removeAttributes('id');
24359     
24360 }
24361
24362 Roo.apply(Roo.htmleditor.FilterBlock.prototype,
24363 {
24364     node: true, // all tags
24365      
24366      
24367     removeAttributes : function(attr)
24368     {
24369         var ar = this.node.querySelectorAll('*[' + attr + ']');
24370         for (var i =0;i<ar.length;i++) {
24371             ar[i].removeAttribute(attr);
24372         }
24373     }
24374         
24375         
24376         
24377     
24378 });
24379 /***
24380  * This is based loosely on tinymce 
24381  * @class Roo.htmleditor.TidySerializer
24382  * https://github.com/thorn0/tinymce.html/blob/master/tinymce.html.js
24383  * @constructor
24384  * @method Serializer
24385  * @param {Object} settings Name/value settings object.
24386  */
24387
24388
24389 Roo.htmleditor.TidySerializer = function(settings)
24390 {
24391     Roo.apply(this, settings);
24392     
24393     this.writer = new Roo.htmleditor.TidyWriter(settings);
24394     
24395     
24396
24397 };
24398 Roo.htmleditor.TidySerializer.prototype = {
24399     
24400     /**
24401      * @param {boolean} inner do the inner of the node.
24402      */
24403     inner : false,
24404     
24405     writer : false,
24406     
24407     /**
24408     * Serializes the specified node into a string.
24409     *
24410     * @example
24411     * new tinymce.html.Serializer().serialize(new tinymce.html.DomParser().parse('<p>text</p>'));
24412     * @method serialize
24413     * @param {DomElement} node Node instance to serialize.
24414     * @return {String} String with HTML based on DOM tree.
24415     */
24416     serialize : function(node) {
24417         
24418         // = settings.validate;
24419         var writer = this.writer;
24420         var self  = this;
24421         this.handlers = {
24422             // #text
24423             3: function(node) {
24424                 
24425                 writer.text(node.nodeValue, node);
24426             },
24427             // #comment
24428             8: function(node) {
24429                 writer.comment(node.nodeValue);
24430             },
24431             // Processing instruction
24432             7: function(node) {
24433                 writer.pi(node.name, node.nodeValue);
24434             },
24435             // Doctype
24436             10: function(node) {
24437                 writer.doctype(node.nodeValue);
24438             },
24439             // CDATA
24440             4: function(node) {
24441                 writer.cdata(node.nodeValue);
24442             },
24443             // Document fragment
24444             11: function(node) {
24445                 node = node.firstChild;
24446                 if (!node) {
24447                     return;
24448                 }
24449                 while(node) {
24450                     self.walk(node);
24451                     node = node.nextSibling
24452                 }
24453             }
24454         };
24455         writer.reset();
24456         1 != node.nodeType || this.inner ? this.handlers[11](node) : this.walk(node);
24457         return writer.getContent();
24458     },
24459
24460     walk: function(node)
24461     {
24462         var attrName, attrValue, sortedAttrs, i, l, elementRule,
24463             handler = this.handlers[node.nodeType];
24464             
24465         if (handler) {
24466             handler(node);
24467             return;
24468         }
24469     
24470         var name = node.nodeName;
24471         var isEmpty = node.childNodes.length < 1;
24472       
24473         var writer = this.writer;
24474         var attrs = node.attributes;
24475         // Sort attributes
24476         
24477         writer.start(node.nodeName, attrs, isEmpty, node);
24478         if (isEmpty) {
24479             return;
24480         }
24481         node = node.firstChild;
24482         if (!node) {
24483             writer.end(name);
24484             return;
24485         }
24486         while (node) {
24487             this.walk(node);
24488             node = node.nextSibling;
24489         }
24490         writer.end(name);
24491         
24492     
24493     }
24494     // Serialize element and treat all non elements as fragments
24495    
24496 }; 
24497
24498 /***
24499  * This is based loosely on tinymce 
24500  * @class Roo.htmleditor.TidyWriter
24501  * https://github.com/thorn0/tinymce.html/blob/master/tinymce.html.js
24502  *
24503  * Known issues?
24504  * - not tested much with 'PRE' formated elements.
24505  * 
24506  *
24507  *
24508  */
24509
24510 Roo.htmleditor.TidyWriter = function(settings)
24511 {
24512     
24513     // indent, indentBefore, indentAfter, encode, htmlOutput, html = [];
24514     Roo.apply(this, settings);
24515     this.html = [];
24516     this.state = [];
24517      
24518     this.encode = Roo.htmleditor.TidyEntities.getEncodeFunc(settings.entity_encoding || 'raw', settings.entities);
24519   
24520 }
24521 Roo.htmleditor.TidyWriter.prototype = {
24522
24523  
24524     state : false,
24525     
24526     indent :  '  ',
24527     
24528     // part of state...
24529     indentstr : '',
24530     in_pre: false,
24531     in_inline : false,
24532     last_inline : false,
24533     encode : false,
24534      
24535     
24536             /**
24537     * Writes the a start element such as <p id="a">.
24538     *
24539     * @method start
24540     * @param {String} name Name of the element.
24541     * @param {Array} attrs Optional attribute array or undefined if it hasn't any.
24542     * @param {Boolean} empty Optional empty state if the tag should end like <br />.
24543     */
24544     start: function(name, attrs, empty, node)
24545     {
24546         var i, l, attr, value;
24547         
24548         // there are some situations where adding line break && indentation will not work. will not work.
24549         // <span / b / i ... formating?
24550         
24551         var in_inline = this.in_inline || Roo.htmleditor.TidyWriter.inline_elements.indexOf(name) > -1;
24552         var in_pre    = this.in_pre    || Roo.htmleditor.TidyWriter.whitespace_elements.indexOf(name) > -1;
24553         
24554         var is_short   = empty ? Roo.htmleditor.TidyWriter.shortend_elements.indexOf(name) > -1 : false;
24555         
24556         var add_lb = name == 'BR' ? false : in_inline;
24557         
24558         if (!add_lb && !this.in_pre && this.lastElementEndsWS()) {
24559             i_inline = false;
24560         }
24561
24562         var indentstr =  this.indentstr;
24563         
24564         // e_inline = elements that can be inline, but still allow \n before and after?
24565         // only 'BR' ??? any others?
24566         
24567         // ADD LINE BEFORE tage
24568         if (!this.in_pre) {
24569             if (in_inline) {
24570                 //code
24571                 if (name == 'BR') {
24572                     this.addLine();
24573                 } else if (this.lastElementEndsWS()) {
24574                     this.addLine();
24575                 } else{
24576                     // otherwise - no new line. (and dont indent.)
24577                     indentstr = '';
24578                 }
24579                 
24580             } else {
24581                 this.addLine();
24582             }
24583         } else {
24584             indentstr = '';
24585         }
24586         
24587         this.html.push(indentstr + '<', name.toLowerCase());
24588         
24589         if (attrs) {
24590             for (i = 0, l = attrs.length; i < l; i++) {
24591                 attr = attrs[i];
24592                 this.html.push(' ', attr.name, '="', this.encode(attr.value, true), '"');
24593             }
24594         }
24595      
24596         if (empty) {
24597             if (is_short) {
24598                 this.html[this.html.length] = '/>';
24599             } else {
24600                 this.html[this.html.length] = '></' + name.toLowerCase() + '>';
24601             }
24602             var e_inline = name == 'BR' ? false : this.in_inline;
24603             
24604             if (!e_inline && !this.in_pre) {
24605                 this.addLine();
24606             }
24607             return;
24608         
24609         }
24610         // not empty..
24611         this.html[this.html.length] = '>';
24612         
24613         // there is a special situation, where we need to turn on in_inline - if any of the imediate chidlren are one of these.
24614         /*
24615         if (!in_inline && !in_pre) {
24616             var cn = node.firstChild;
24617             while(cn) {
24618                 if (Roo.htmleditor.TidyWriter.inline_elements.indexOf(cn.nodeName) > -1) {
24619                     in_inline = true
24620                     break;
24621                 }
24622                 cn = cn.nextSibling;
24623             }
24624              
24625         }
24626         */
24627         
24628         
24629         this.pushState({
24630             indentstr : in_pre   ? '' : (this.indentstr + this.indent),
24631             in_pre : in_pre,
24632             in_inline :  in_inline
24633         });
24634         // add a line after if we are not in a
24635         
24636         if (!in_inline && !in_pre) {
24637             this.addLine();
24638         }
24639         
24640             
24641          
24642         
24643     },
24644     
24645     lastElementEndsWS : function()
24646     {
24647         var value = this.html.length > 0 ? this.html[this.html.length-1] : false;
24648         if (value === false) {
24649             return true;
24650         }
24651         return value.match(/\s+$/);
24652         
24653     },
24654     
24655     /**
24656      * Writes the a end element such as </p>.
24657      *
24658      * @method end
24659      * @param {String} name Name of the element.
24660      */
24661     end: function(name) {
24662         var value;
24663         this.popState();
24664         var indentstr = '';
24665         var in_inline = this.in_inline || Roo.htmleditor.TidyWriter.inline_elements.indexOf(name) > -1;
24666         
24667         if (!this.in_pre && !in_inline) {
24668             this.addLine();
24669             indentstr  = this.indentstr;
24670         }
24671         this.html.push(indentstr + '</', name.toLowerCase(), '>');
24672         this.last_inline = in_inline;
24673         
24674         // pop the indent state..
24675     },
24676     /**
24677      * Writes a text node.
24678      *
24679      * In pre - we should not mess with the contents.
24680      * 
24681      *
24682      * @method text
24683      * @param {String} text String to write out.
24684      * @param {Boolean} raw Optional raw state if true the contents wont get encoded.
24685      */
24686     text: function(in_text, node)
24687     {
24688         // if not in whitespace critical
24689         if (in_text.length < 1) {
24690             return;
24691         }
24692         var text = new XMLSerializer().serializeToString(document.createTextNode(in_text)); // escape it properly?
24693         
24694         if (this.in_pre) {
24695             this.html[this.html.length] =  text;
24696             return;   
24697         }
24698         
24699         if (this.in_inline) {
24700             text = text.replace(/\s+/g,' '); // all white space inc line breaks to a slingle' '
24701             if (text != ' ') {
24702                 text = text.replace(/\s+/,' ');  // all white space to single white space
24703                 
24704                     
24705                 // if next tag is '<BR>', then we can trim right..
24706                 if (node.nextSibling &&
24707                     node.nextSibling.nodeType == 1 &&
24708                     node.nextSibling.nodeName == 'BR' )
24709                 {
24710                     text = text.replace(/\s+$/g,'');
24711                 }
24712                 // if previous tag was a BR, we can also trim..
24713                 if (node.previousSibling &&
24714                     node.previousSibling.nodeType == 1 &&
24715                     node.previousSibling.nodeName == 'BR' )
24716                 {
24717                     text = this.indentstr +  text.replace(/^\s+/g,'');
24718                 }
24719                 if (text.match(/\n/)) {
24720                     text = text.replace(
24721                         /(?![^\n]{1,64}$)([^\n]{1,64})\s/g, '$1\n' + this.indentstr
24722                     );
24723                     // remoeve the last whitespace / line break.
24724                     text = text.replace(/\n\s+$/,'');
24725                 }
24726                 // repace long lines
24727                 
24728             }
24729              
24730             this.html[this.html.length] =  text;
24731             return;   
24732         }
24733         // see if previous element was a inline element.
24734         var indentstr = this.indentstr;
24735    
24736         text = text.replace(/\s+/g," "); // all whitespace into single white space.
24737         
24738         // should trim left?
24739         if (node.previousSibling &&
24740             node.previousSibling.nodeType == 1 &&
24741             Roo.htmleditor.TidyWriter.inline_elements.indexOf(node.previousSibling.nodeName) > -1)
24742         {
24743             indentstr = '';
24744             
24745         } else {
24746             this.addLine();
24747             text = text.replace(/^\s+/,''); // trim left
24748           
24749         }
24750         // should trim right?
24751         if (node.nextSibling &&
24752             node.nextSibling.nodeType == 1 &&
24753             Roo.htmleditor.TidyWriter.inline_elements.indexOf(node.nextSibling.nodeName) > -1)
24754         {
24755           // noop
24756             
24757         }  else {
24758             text = text.replace(/\s+$/,''); // trim right
24759         }
24760          
24761               
24762         
24763         
24764         
24765         if (text.length < 1) {
24766             return;
24767         }
24768         if (!text.match(/\n/)) {
24769             this.html.push(indentstr + text);
24770             return;
24771         }
24772         
24773         text = this.indentstr + text.replace(
24774             /(?![^\n]{1,64}$)([^\n]{1,64})\s/g, '$1\n' + this.indentstr
24775         );
24776         // remoeve the last whitespace / line break.
24777         text = text.replace(/\s+$/,''); 
24778         
24779         this.html.push(text);
24780         
24781         // split and indent..
24782         
24783         
24784     },
24785     /**
24786      * Writes a cdata node such as <![CDATA[data]]>.
24787      *
24788      * @method cdata
24789      * @param {String} text String to write out inside the cdata.
24790      */
24791     cdata: function(text) {
24792         this.html.push('<![CDATA[', text, ']]>');
24793     },
24794     /**
24795     * Writes a comment node such as <!-- Comment -->.
24796     *
24797     * @method cdata
24798     * @param {String} text String to write out inside the comment.
24799     */
24800    comment: function(text) {
24801        this.html.push('<!--', text, '-->');
24802    },
24803     /**
24804      * Writes a PI node such as <?xml attr="value" ?>.
24805      *
24806      * @method pi
24807      * @param {String} name Name of the pi.
24808      * @param {String} text String to write out inside the pi.
24809      */
24810     pi: function(name, text) {
24811         text ? this.html.push('<?', name, ' ', this.encode(text), '?>') : this.html.push('<?', name, '?>');
24812         this.indent != '' && this.html.push('\n');
24813     },
24814     /**
24815      * Writes a doctype node such as <!DOCTYPE data>.
24816      *
24817      * @method doctype
24818      * @param {String} text String to write out inside the doctype.
24819      */
24820     doctype: function(text) {
24821         this.html.push('<!DOCTYPE', text, '>', this.indent != '' ? '\n' : '');
24822     },
24823     /**
24824      * Resets the internal buffer if one wants to reuse the writer.
24825      *
24826      * @method reset
24827      */
24828     reset: function() {
24829         this.html.length = 0;
24830         this.state = [];
24831         this.pushState({
24832             indentstr : '',
24833             in_pre : false, 
24834             in_inline : false
24835         })
24836     },
24837     /**
24838      * Returns the contents that got serialized.
24839      *
24840      * @method getContent
24841      * @return {String} HTML contents that got written down.
24842      */
24843     getContent: function() {
24844         return this.html.join('').replace(/\n$/, '');
24845     },
24846     
24847     pushState : function(cfg)
24848     {
24849         this.state.push(cfg);
24850         Roo.apply(this, cfg);
24851     },
24852     
24853     popState : function()
24854     {
24855         if (this.state.length < 1) {
24856             return; // nothing to push
24857         }
24858         var cfg = {
24859             in_pre: false,
24860             indentstr : ''
24861         };
24862         this.state.pop();
24863         if (this.state.length > 0) {
24864             cfg = this.state[this.state.length-1]; 
24865         }
24866         Roo.apply(this, cfg);
24867     },
24868     
24869     addLine: function()
24870     {
24871         if (this.html.length < 1) {
24872             return;
24873         }
24874         
24875         
24876         var value = this.html[this.html.length - 1];
24877         if (value.length > 0 && '\n' !== value) {
24878             this.html.push('\n');
24879         }
24880     }
24881     
24882     
24883 //'pre script noscript style textarea video audio iframe object code'
24884 // shortended... 'area base basefont br col frame hr img input isindex link  meta param embed source wbr track');
24885 // inline 
24886 };
24887
24888 Roo.htmleditor.TidyWriter.inline_elements = [
24889         'SPAN','STRONG','B','EM','I','FONT','STRIKE','U','VAR',
24890         'CITE','DFN','CODE','MARK','Q','SUP','SUB','SAMP', 'A'
24891 ];
24892 Roo.htmleditor.TidyWriter.shortend_elements = [
24893     'AREA','BASE','BASEFONT','BR','COL','FRAME','HR','IMG','INPUT',
24894     'ISINDEX','LINK','','META','PARAM','EMBED','SOURCE','WBR','TRACK'
24895 ];
24896
24897 Roo.htmleditor.TidyWriter.whitespace_elements = [
24898     'PRE','SCRIPT','NOSCRIPT','STYLE','TEXTAREA','VIDEO','AUDIO','IFRAME','OBJECT','CODE'
24899 ];/***
24900  * This is based loosely on tinymce 
24901  * @class Roo.htmleditor.TidyEntities
24902  * @static
24903  * https://github.com/thorn0/tinymce.html/blob/master/tinymce.html.js
24904  *
24905  * Not 100% sure this is actually used or needed.
24906  */
24907
24908 Roo.htmleditor.TidyEntities = {
24909     
24910     /**
24911      * initialize data..
24912      */
24913     init : function (){
24914      
24915         this.namedEntities = this.buildEntitiesLookup(this.namedEntitiesData, 32);
24916        
24917     },
24918
24919
24920     buildEntitiesLookup: function(items, radix) {
24921         var i, chr, entity, lookup = {};
24922         if (!items) {
24923             return {};
24924         }
24925         items = typeof(items) == 'string' ? items.split(',') : items;
24926         radix = radix || 10;
24927         // Build entities lookup table
24928         for (i = 0; i < items.length; i += 2) {
24929             chr = String.fromCharCode(parseInt(items[i], radix));
24930             // Only add non base entities
24931             if (!this.baseEntities[chr]) {
24932                 entity = '&' + items[i + 1] + ';';
24933                 lookup[chr] = entity;
24934                 lookup[entity] = chr;
24935             }
24936         }
24937         return lookup;
24938         
24939     },
24940     
24941     asciiMap : {
24942             128: '€',
24943             130: '‚',
24944             131: 'ƒ',
24945             132: '„',
24946             133: '…',
24947             134: '†',
24948             135: '‡',
24949             136: 'ˆ',
24950             137: '‰',
24951             138: 'Š',
24952             139: '‹',
24953             140: 'Œ',
24954             142: 'Ž',
24955             145: '‘',
24956             146: '’',
24957             147: '“',
24958             148: '”',
24959             149: '•',
24960             150: '–',
24961             151: '—',
24962             152: '˜',
24963             153: '™',
24964             154: 'š',
24965             155: '›',
24966             156: 'œ',
24967             158: 'ž',
24968             159: 'Ÿ'
24969     },
24970     // Raw entities
24971     baseEntities : {
24972         '"': '&quot;',
24973         // Needs to be escaped since the YUI compressor would otherwise break the code
24974         '\'': '&#39;',
24975         '<': '&lt;',
24976         '>': '&gt;',
24977         '&': '&amp;',
24978         '`': '&#96;'
24979     },
24980     // Reverse lookup table for raw entities
24981     reverseEntities : {
24982         '&lt;': '<',
24983         '&gt;': '>',
24984         '&amp;': '&',
24985         '&quot;': '"',
24986         '&apos;': '\''
24987     },
24988     
24989     attrsCharsRegExp : /[&<>\"\u0060\u007E-\uD7FF\uE000-\uFFEF]|[\uD800-\uDBFF][\uDC00-\uDFFF]/g,
24990     textCharsRegExp : /[<>&\u007E-\uD7FF\uE000-\uFFEF]|[\uD800-\uDBFF][\uDC00-\uDFFF]/g,
24991     rawCharsRegExp : /[<>&\"\']/g,
24992     entityRegExp : /&#([a-z0-9]+);?|&([a-z0-9]+);/gi,
24993     namedEntities  : false,
24994     namedEntitiesData : [ 
24995         '50',
24996         'nbsp',
24997         '51',
24998         'iexcl',
24999         '52',
25000         'cent',
25001         '53',
25002         'pound',
25003         '54',
25004         'curren',
25005         '55',
25006         'yen',
25007         '56',
25008         'brvbar',
25009         '57',
25010         'sect',
25011         '58',
25012         'uml',
25013         '59',
25014         'copy',
25015         '5a',
25016         'ordf',
25017         '5b',
25018         'laquo',
25019         '5c',
25020         'not',
25021         '5d',
25022         'shy',
25023         '5e',
25024         'reg',
25025         '5f',
25026         'macr',
25027         '5g',
25028         'deg',
25029         '5h',
25030         'plusmn',
25031         '5i',
25032         'sup2',
25033         '5j',
25034         'sup3',
25035         '5k',
25036         'acute',
25037         '5l',
25038         'micro',
25039         '5m',
25040         'para',
25041         '5n',
25042         'middot',
25043         '5o',
25044         'cedil',
25045         '5p',
25046         'sup1',
25047         '5q',
25048         'ordm',
25049         '5r',
25050         'raquo',
25051         '5s',
25052         'frac14',
25053         '5t',
25054         'frac12',
25055         '5u',
25056         'frac34',
25057         '5v',
25058         'iquest',
25059         '60',
25060         'Agrave',
25061         '61',
25062         'Aacute',
25063         '62',
25064         'Acirc',
25065         '63',
25066         'Atilde',
25067         '64',
25068         'Auml',
25069         '65',
25070         'Aring',
25071         '66',
25072         'AElig',
25073         '67',
25074         'Ccedil',
25075         '68',
25076         'Egrave',
25077         '69',
25078         'Eacute',
25079         '6a',
25080         'Ecirc',
25081         '6b',
25082         'Euml',
25083         '6c',
25084         'Igrave',
25085         '6d',
25086         'Iacute',
25087         '6e',
25088         'Icirc',
25089         '6f',
25090         'Iuml',
25091         '6g',
25092         'ETH',
25093         '6h',
25094         'Ntilde',
25095         '6i',
25096         'Ograve',
25097         '6j',
25098         'Oacute',
25099         '6k',
25100         'Ocirc',
25101         '6l',
25102         'Otilde',
25103         '6m',
25104         'Ouml',
25105         '6n',
25106         'times',
25107         '6o',
25108         'Oslash',
25109         '6p',
25110         'Ugrave',
25111         '6q',
25112         'Uacute',
25113         '6r',
25114         'Ucirc',
25115         '6s',
25116         'Uuml',
25117         '6t',
25118         'Yacute',
25119         '6u',
25120         'THORN',
25121         '6v',
25122         'szlig',
25123         '70',
25124         'agrave',
25125         '71',
25126         'aacute',
25127         '72',
25128         'acirc',
25129         '73',
25130         'atilde',
25131         '74',
25132         'auml',
25133         '75',
25134         'aring',
25135         '76',
25136         'aelig',
25137         '77',
25138         'ccedil',
25139         '78',
25140         'egrave',
25141         '79',
25142         'eacute',
25143         '7a',
25144         'ecirc',
25145         '7b',
25146         'euml',
25147         '7c',
25148         'igrave',
25149         '7d',
25150         'iacute',
25151         '7e',
25152         'icirc',
25153         '7f',
25154         'iuml',
25155         '7g',
25156         'eth',
25157         '7h',
25158         'ntilde',
25159         '7i',
25160         'ograve',
25161         '7j',
25162         'oacute',
25163         '7k',
25164         'ocirc',
25165         '7l',
25166         'otilde',
25167         '7m',
25168         'ouml',
25169         '7n',
25170         'divide',
25171         '7o',
25172         'oslash',
25173         '7p',
25174         'ugrave',
25175         '7q',
25176         'uacute',
25177         '7r',
25178         'ucirc',
25179         '7s',
25180         'uuml',
25181         '7t',
25182         'yacute',
25183         '7u',
25184         'thorn',
25185         '7v',
25186         'yuml',
25187         'ci',
25188         'fnof',
25189         'sh',
25190         'Alpha',
25191         'si',
25192         'Beta',
25193         'sj',
25194         'Gamma',
25195         'sk',
25196         'Delta',
25197         'sl',
25198         'Epsilon',
25199         'sm',
25200         'Zeta',
25201         'sn',
25202         'Eta',
25203         'so',
25204         'Theta',
25205         'sp',
25206         'Iota',
25207         'sq',
25208         'Kappa',
25209         'sr',
25210         'Lambda',
25211         'ss',
25212         'Mu',
25213         'st',
25214         'Nu',
25215         'su',
25216         'Xi',
25217         'sv',
25218         'Omicron',
25219         't0',
25220         'Pi',
25221         't1',
25222         'Rho',
25223         't3',
25224         'Sigma',
25225         't4',
25226         'Tau',
25227         't5',
25228         'Upsilon',
25229         't6',
25230         'Phi',
25231         't7',
25232         'Chi',
25233         't8',
25234         'Psi',
25235         't9',
25236         'Omega',
25237         'th',
25238         'alpha',
25239         'ti',
25240         'beta',
25241         'tj',
25242         'gamma',
25243         'tk',
25244         'delta',
25245         'tl',
25246         'epsilon',
25247         'tm',
25248         'zeta',
25249         'tn',
25250         'eta',
25251         'to',
25252         'theta',
25253         'tp',
25254         'iota',
25255         'tq',
25256         'kappa',
25257         'tr',
25258         'lambda',
25259         'ts',
25260         'mu',
25261         'tt',
25262         'nu',
25263         'tu',
25264         'xi',
25265         'tv',
25266         'omicron',
25267         'u0',
25268         'pi',
25269         'u1',
25270         'rho',
25271         'u2',
25272         'sigmaf',
25273         'u3',
25274         'sigma',
25275         'u4',
25276         'tau',
25277         'u5',
25278         'upsilon',
25279         'u6',
25280         'phi',
25281         'u7',
25282         'chi',
25283         'u8',
25284         'psi',
25285         'u9',
25286         'omega',
25287         'uh',
25288         'thetasym',
25289         'ui',
25290         'upsih',
25291         'um',
25292         'piv',
25293         '812',
25294         'bull',
25295         '816',
25296         'hellip',
25297         '81i',
25298         'prime',
25299         '81j',
25300         'Prime',
25301         '81u',
25302         'oline',
25303         '824',
25304         'frasl',
25305         '88o',
25306         'weierp',
25307         '88h',
25308         'image',
25309         '88s',
25310         'real',
25311         '892',
25312         'trade',
25313         '89l',
25314         'alefsym',
25315         '8cg',
25316         'larr',
25317         '8ch',
25318         'uarr',
25319         '8ci',
25320         'rarr',
25321         '8cj',
25322         'darr',
25323         '8ck',
25324         'harr',
25325         '8dl',
25326         'crarr',
25327         '8eg',
25328         'lArr',
25329         '8eh',
25330         'uArr',
25331         '8ei',
25332         'rArr',
25333         '8ej',
25334         'dArr',
25335         '8ek',
25336         'hArr',
25337         '8g0',
25338         'forall',
25339         '8g2',
25340         'part',
25341         '8g3',
25342         'exist',
25343         '8g5',
25344         'empty',
25345         '8g7',
25346         'nabla',
25347         '8g8',
25348         'isin',
25349         '8g9',
25350         'notin',
25351         '8gb',
25352         'ni',
25353         '8gf',
25354         'prod',
25355         '8gh',
25356         'sum',
25357         '8gi',
25358         'minus',
25359         '8gn',
25360         'lowast',
25361         '8gq',
25362         'radic',
25363         '8gt',
25364         'prop',
25365         '8gu',
25366         'infin',
25367         '8h0',
25368         'ang',
25369         '8h7',
25370         'and',
25371         '8h8',
25372         'or',
25373         '8h9',
25374         'cap',
25375         '8ha',
25376         'cup',
25377         '8hb',
25378         'int',
25379         '8hk',
25380         'there4',
25381         '8hs',
25382         'sim',
25383         '8i5',
25384         'cong',
25385         '8i8',
25386         'asymp',
25387         '8j0',
25388         'ne',
25389         '8j1',
25390         'equiv',
25391         '8j4',
25392         'le',
25393         '8j5',
25394         'ge',
25395         '8k2',
25396         'sub',
25397         '8k3',
25398         'sup',
25399         '8k4',
25400         'nsub',
25401         '8k6',
25402         'sube',
25403         '8k7',
25404         'supe',
25405         '8kl',
25406         'oplus',
25407         '8kn',
25408         'otimes',
25409         '8l5',
25410         'perp',
25411         '8m5',
25412         'sdot',
25413         '8o8',
25414         'lceil',
25415         '8o9',
25416         'rceil',
25417         '8oa',
25418         'lfloor',
25419         '8ob',
25420         'rfloor',
25421         '8p9',
25422         'lang',
25423         '8pa',
25424         'rang',
25425         '9ea',
25426         'loz',
25427         '9j0',
25428         'spades',
25429         '9j3',
25430         'clubs',
25431         '9j5',
25432         'hearts',
25433         '9j6',
25434         'diams',
25435         'ai',
25436         'OElig',
25437         'aj',
25438         'oelig',
25439         'b0',
25440         'Scaron',
25441         'b1',
25442         'scaron',
25443         'bo',
25444         'Yuml',
25445         'm6',
25446         'circ',
25447         'ms',
25448         'tilde',
25449         '802',
25450         'ensp',
25451         '803',
25452         'emsp',
25453         '809',
25454         'thinsp',
25455         '80c',
25456         'zwnj',
25457         '80d',
25458         'zwj',
25459         '80e',
25460         'lrm',
25461         '80f',
25462         'rlm',
25463         '80j',
25464         'ndash',
25465         '80k',
25466         'mdash',
25467         '80o',
25468         'lsquo',
25469         '80p',
25470         'rsquo',
25471         '80q',
25472         'sbquo',
25473         '80s',
25474         'ldquo',
25475         '80t',
25476         'rdquo',
25477         '80u',
25478         'bdquo',
25479         '810',
25480         'dagger',
25481         '811',
25482         'Dagger',
25483         '81g',
25484         'permil',
25485         '81p',
25486         'lsaquo',
25487         '81q',
25488         'rsaquo',
25489         '85c',
25490         'euro'
25491     ],
25492
25493          
25494     /**
25495      * Encodes the specified string using raw entities. This means only the required XML base entities will be encoded.
25496      *
25497      * @method encodeRaw
25498      * @param {String} text Text to encode.
25499      * @param {Boolean} attr Optional flag to specify if the text is attribute contents.
25500      * @return {String} Entity encoded text.
25501      */
25502     encodeRaw: function(text, attr)
25503     {
25504         var t = this;
25505         return text.replace(attr ? this.attrsCharsRegExp : this.textCharsRegExp, function(chr) {
25506             return t.baseEntities[chr] || chr;
25507         });
25508     },
25509     /**
25510      * Encoded the specified text with both the attributes and text entities. This function will produce larger text contents
25511      * since it doesn't know if the context is within a attribute or text node. This was added for compatibility
25512      * and is exposed as the DOMUtils.encode function.
25513      *
25514      * @method encodeAllRaw
25515      * @param {String} text Text to encode.
25516      * @return {String} Entity encoded text.
25517      */
25518     encodeAllRaw: function(text) {
25519         var t = this;
25520         return ('' + text).replace(this.rawCharsRegExp, function(chr) {
25521             return t.baseEntities[chr] || chr;
25522         });
25523     },
25524     /**
25525      * Encodes the specified string using numeric entities. The core entities will be
25526      * encoded as named ones but all non lower ascii characters will be encoded into numeric entities.
25527      *
25528      * @method encodeNumeric
25529      * @param {String} text Text to encode.
25530      * @param {Boolean} attr Optional flag to specify if the text is attribute contents.
25531      * @return {String} Entity encoded text.
25532      */
25533     encodeNumeric: function(text, attr) {
25534         var t = this;
25535         return text.replace(attr ? this.attrsCharsRegExp : this.textCharsRegExp, function(chr) {
25536             // Multi byte sequence convert it to a single entity
25537             if (chr.length > 1) {
25538                 return '&#' + (1024 * (chr.charCodeAt(0) - 55296) + (chr.charCodeAt(1) - 56320) + 65536) + ';';
25539             }
25540             return t.baseEntities[chr] || '&#' + chr.charCodeAt(0) + ';';
25541         });
25542     },
25543     /**
25544      * Encodes the specified string using named entities. The core entities will be encoded
25545      * as named ones but all non lower ascii characters will be encoded into named entities.
25546      *
25547      * @method encodeNamed
25548      * @param {String} text Text to encode.
25549      * @param {Boolean} attr Optional flag to specify if the text is attribute contents.
25550      * @param {Object} entities Optional parameter with entities to use.
25551      * @return {String} Entity encoded text.
25552      */
25553     encodeNamed: function(text, attr, entities) {
25554         var t = this;
25555         entities = entities || this.namedEntities;
25556         return text.replace(attr ? this.attrsCharsRegExp : this.textCharsRegExp, function(chr) {
25557             return t.baseEntities[chr] || entities[chr] || chr;
25558         });
25559     },
25560     /**
25561      * Returns an encode function based on the name(s) and it's optional entities.
25562      *
25563      * @method getEncodeFunc
25564      * @param {String} name Comma separated list of encoders for example named,numeric.
25565      * @param {String} entities Optional parameter with entities to use instead of the built in set.
25566      * @return {function} Encode function to be used.
25567      */
25568     getEncodeFunc: function(name, entities) {
25569         entities = this.buildEntitiesLookup(entities) || this.namedEntities;
25570         var t = this;
25571         function encodeNamedAndNumeric(text, attr) {
25572             return text.replace(attr ? t.attrsCharsRegExp : t.textCharsRegExp, function(chr) {
25573                 return t.baseEntities[chr] || entities[chr] || '&#' + chr.charCodeAt(0) + ';' || chr;
25574             });
25575         }
25576
25577         function encodeCustomNamed(text, attr) {
25578             return t.encodeNamed(text, attr, entities);
25579         }
25580         // Replace + with , to be compatible with previous TinyMCE versions
25581         name = this.makeMap(name.replace(/\+/g, ','));
25582         // Named and numeric encoder
25583         if (name.named && name.numeric) {
25584             return this.encodeNamedAndNumeric;
25585         }
25586         // Named encoder
25587         if (name.named) {
25588             // Custom names
25589             if (entities) {
25590                 return encodeCustomNamed;
25591             }
25592             return this.encodeNamed;
25593         }
25594         // Numeric
25595         if (name.numeric) {
25596             return this.encodeNumeric;
25597         }
25598         // Raw encoder
25599         return this.encodeRaw;
25600     },
25601     /**
25602      * Decodes the specified string, this will replace entities with raw UTF characters.
25603      *
25604      * @method decode
25605      * @param {String} text Text to entity decode.
25606      * @return {String} Entity decoded string.
25607      */
25608     decode: function(text)
25609     {
25610         var  t = this;
25611         return text.replace(this.entityRegExp, function(all, numeric) {
25612             if (numeric) {
25613                 numeric = 'x' === numeric.charAt(0).toLowerCase() ? parseInt(numeric.substr(1), 16) : parseInt(numeric, 10);
25614                 // Support upper UTF
25615                 if (numeric > 65535) {
25616                     numeric -= 65536;
25617                     return String.fromCharCode(55296 + (numeric >> 10), 56320 + (1023 & numeric));
25618                 }
25619                 return t.asciiMap[numeric] || String.fromCharCode(numeric);
25620             }
25621             return t.reverseEntities[all] || t.namedEntities[all] || t.nativeDecode(all);
25622         });
25623     },
25624     nativeDecode : function (text) {
25625         return text;
25626     },
25627     makeMap : function (items, delim, map) {
25628                 var i;
25629                 items = items || [];
25630                 delim = delim || ',';
25631                 if (typeof items == "string") {
25632                         items = items.split(delim);
25633                 }
25634                 map = map || {};
25635                 i = items.length;
25636                 while (i--) {
25637                         map[items[i]] = {};
25638                 }
25639                 return map;
25640         }
25641 };
25642     
25643     
25644     
25645 Roo.htmleditor.TidyEntities.init();
25646 /**
25647  * @class Roo.htmleditor.KeyEnter
25648  * Handle Enter press..
25649  * @cfg {Roo.HtmlEditorCore} core the editor.
25650  * @constructor
25651  * Create a new Filter.
25652  * @param {Object} config Configuration options
25653  */
25654
25655
25656
25657
25658
25659 Roo.htmleditor.KeyEnter = function(cfg) {
25660     Roo.apply(this, cfg);
25661     // this does not actually call walk as it's really just a abstract class
25662  
25663     Roo.get(this.core.doc.body).on('keypress', this.keypress, this);
25664 }
25665
25666 //Roo.htmleditor.KeyEnter.i = 0;
25667
25668
25669 Roo.htmleditor.KeyEnter.prototype = {
25670     
25671     core : false,
25672     
25673     keypress : function(e)
25674     {
25675         if (e.charCode != 13 && e.charCode != 10) {
25676             Roo.log([e.charCode,e]);
25677             return true;
25678         }
25679         e.preventDefault();
25680         // https://stackoverflow.com/questions/18552336/prevent-contenteditable-adding-div-on-enter-chrome
25681         var doc = this.core.doc;
25682           //add a new line
25683        
25684     
25685         var sel = this.core.getSelection();
25686         var range = sel.getRangeAt(0);
25687         var n = range.commonAncestorContainer;
25688         var pc = range.closest([ 'ol', 'ul']);
25689         var pli = range.closest('li');
25690         if (!pc || e.ctrlKey) {
25691             // on it list, or ctrl pressed.
25692             if (!e.ctrlKey) {
25693                 sel.insertNode('br', 'after'); 
25694             } else {
25695                 // only do this if we have ctrl key..
25696                 var br = doc.createElement('br');
25697                 br.className = 'clear';
25698                 br.setAttribute('style', 'clear: both');
25699                 sel.insertNode(br, 'after'); 
25700             }
25701             
25702          
25703             this.core.undoManager.addEvent();
25704             this.core.fireEditorEvent(e);
25705             return false;
25706         }
25707         
25708         // deal with <li> insetion
25709         if (pli.innerText.trim() == '' &&
25710             pli.previousSibling &&
25711             pli.previousSibling.nodeName == 'LI' &&
25712             pli.previousSibling.innerText.trim() ==  '') {
25713             pli.parentNode.removeChild(pli.previousSibling);
25714             sel.cursorAfter(pc);
25715             this.core.undoManager.addEvent();
25716             this.core.fireEditorEvent(e);
25717             return false;
25718         }
25719     
25720         var li = doc.createElement('LI');
25721         li.innerHTML = '&nbsp;';
25722         if (!pli || !pli.firstSibling) {
25723             pc.appendChild(li);
25724         } else {
25725             pli.parentNode.insertBefore(li, pli.firstSibling);
25726         }
25727         sel.cursorText (li.firstChild);
25728       
25729         this.core.undoManager.addEvent();
25730         this.core.fireEditorEvent(e);
25731
25732         return false;
25733         
25734     
25735         
25736         
25737          
25738     }
25739 };
25740      
25741 /**
25742  * @class Roo.htmleditor.Block
25743  * Base class for html editor blocks - do not use it directly .. extend it..
25744  * @cfg {DomElement} node The node to apply stuff to.
25745  * @cfg {String} friendly_name the name that appears in the context bar about this block
25746  * @cfg {Object} Context menu - see Roo.form.HtmlEditor.ToolbarContext
25747  
25748  * @constructor
25749  * Create a new Filter.
25750  * @param {Object} config Configuration options
25751  */
25752
25753 Roo.htmleditor.Block  = function(cfg)
25754 {
25755     // do nothing .. should not be called really.
25756 }
25757 /**
25758  * factory method to get the block from an element (using cache if necessary)
25759  * @static
25760  * @param {HtmlElement} the dom element
25761  */
25762 Roo.htmleditor.Block.factory = function(node)
25763 {
25764     var cc = Roo.htmleditor.Block.cache;
25765     var id = Roo.get(node).id;
25766     if (typeof(cc[id]) != 'undefined' && (!cc[id].node || cc[id].node.closest('body'))) {
25767         Roo.htmleditor.Block.cache[id].readElement(node);
25768         return Roo.htmleditor.Block.cache[id];
25769     }
25770     var db  = node.getAttribute('data-block');
25771     if (!db) {
25772         db = node.nodeName.toLowerCase().toUpperCaseFirst();
25773     }
25774     var cls = Roo.htmleditor['Block' + db];
25775     if (typeof(cls) == 'undefined') {
25776         //Roo.log(node.getAttribute('data-block'));
25777         Roo.log("OOps missing block : " + 'Block' + db);
25778         return false;
25779     }
25780     Roo.htmleditor.Block.cache[id] = new cls({ node: node });
25781     return Roo.htmleditor.Block.cache[id];  /// should trigger update element
25782 };
25783
25784 /**
25785  * initalize all Elements from content that are 'blockable'
25786  * @static
25787  * @param the body element
25788  */
25789 Roo.htmleditor.Block.initAll = function(body, type)
25790 {
25791     if (typeof(type) == 'undefined') {
25792         var ia = Roo.htmleditor.Block.initAll;
25793         ia(body,'table');
25794         ia(body,'td');
25795         ia(body,'figure');
25796         return;
25797     }
25798     Roo.each(Roo.get(body).query(type), function(e) {
25799         Roo.htmleditor.Block.factory(e);    
25800     },this);
25801 };
25802 // question goes here... do we need to clear out this cache sometimes?
25803 // or show we make it relivant to the htmleditor.
25804 Roo.htmleditor.Block.cache = {};
25805
25806 Roo.htmleditor.Block.prototype = {
25807     
25808     node : false,
25809     
25810      // used by context menu
25811     friendly_name : 'Based Block',
25812     
25813     // text for button to delete this element
25814     deleteTitle : false,
25815     
25816     context : false,
25817     /**
25818      * Update a node with values from this object
25819      * @param {DomElement} node
25820      */
25821     updateElement : function(node)
25822     {
25823         Roo.DomHelper.update(node === undefined ? this.node : node, this.toObject());
25824     },
25825      /**
25826      * convert to plain HTML for calling insertAtCursor..
25827      */
25828     toHTML : function()
25829     {
25830         return Roo.DomHelper.markup(this.toObject());
25831     },
25832     /**
25833      * used by readEleemnt to extract data from a node
25834      * may need improving as it's pretty basic
25835      
25836      * @param {DomElement} node
25837      * @param {String} tag - tag to find, eg. IMG ?? might be better to use DomQuery ?
25838      * @param {String} attribute (use html - for contents, style for using next param as style, or false to return the node)
25839      * @param {String} style the style property - eg. text-align
25840      */
25841     getVal : function(node, tag, attr, style)
25842     {
25843         var n = node;
25844         if (tag !== true && n.tagName != tag.toUpperCase()) {
25845             // in theory we could do figure[3] << 3rd figure? or some more complex search..?
25846             // but kiss for now.
25847             n = node.getElementsByTagName(tag).item(0);
25848         }
25849         if (!n) {
25850             return '';
25851         }
25852         if (attr === false) {
25853             return n;
25854         }
25855         if (attr == 'html') {
25856             return n.innerHTML;
25857         }
25858         if (attr == 'style') {
25859             return n.style[style]; 
25860         }
25861         
25862         return n.hasAttribute(attr) ? n.getAttribute(attr) : '';
25863             
25864     },
25865     /**
25866      * create a DomHelper friendly object - for use with 
25867      * Roo.DomHelper.markup / overwrite / etc..
25868      * (override this)
25869      */
25870     toObject : function()
25871     {
25872         return {};
25873     },
25874       /**
25875      * Read a node that has a 'data-block' property - and extract the values from it.
25876      * @param {DomElement} node - the node
25877      */
25878     readElement : function(node)
25879     {
25880         
25881     } 
25882     
25883     
25884 };
25885
25886  
25887
25888 /**
25889  * @class Roo.htmleditor.BlockFigure
25890  * Block that has an image and a figcaption
25891  * @cfg {String} image_src the url for the image
25892  * @cfg {String} align (left|right) alignment for the block default left
25893  * @cfg {String} caption the text to appear below  (and in the alt tag)
25894  * @cfg {String} caption_display (block|none) display or not the caption
25895  * @cfg {String|number} image_width the width of the image number or %?
25896  * @cfg {String|number} image_height the height of the image number or %?
25897  * 
25898  * @constructor
25899  * Create a new Filter.
25900  * @param {Object} config Configuration options
25901  */
25902
25903 Roo.htmleditor.BlockFigure = function(cfg)
25904 {
25905     if (cfg.node) {
25906         this.readElement(cfg.node);
25907         this.updateElement(cfg.node);
25908     }
25909     Roo.apply(this, cfg);
25910 }
25911 Roo.extend(Roo.htmleditor.BlockFigure, Roo.htmleditor.Block, {
25912  
25913     
25914     // setable values.
25915     image_src: '',
25916     align: 'center',
25917     caption : '',
25918     caption_display : 'block',
25919     width : '100%',
25920     cls : '',
25921     href: '',
25922     video_url : '',
25923     
25924     // margin: '2%', not used
25925     
25926     text_align: 'left', //   (left|right) alignment for the text caption default left. - not used at present
25927
25928     
25929     // used by context menu
25930     friendly_name : 'Image with caption',
25931     deleteTitle : "Delete Image and Caption",
25932     
25933     contextMenu : function(toolbar)
25934     {
25935         
25936         var block = function() {
25937             return Roo.htmleditor.Block.factory(toolbar.tb.selectedNode);
25938         };
25939         
25940         
25941         var rooui =  typeof(Roo.bootstrap) == 'undefined' ? Roo : Roo.bootstrap;
25942         
25943         var syncValue = toolbar.editorcore.syncValue;
25944         
25945         var fields = {};
25946         
25947         return [
25948              {
25949                 xtype : 'TextItem',
25950                 text : "Source: ",
25951                 xns : rooui.Toolbar  //Boostrap?
25952             },
25953             {
25954                 xtype : 'Button',
25955                 text: 'Change Image URL',
25956                  
25957                 listeners : {
25958                     click: function (btn, state)
25959                     {
25960                         var b = block();
25961                         
25962                         Roo.MessageBox.show({
25963                             title : "Image Source URL",
25964                             msg : "Enter the url for the image",
25965                             buttons: Roo.MessageBox.OKCANCEL,
25966                             fn: function(btn, val){
25967                                 if (btn != 'ok') {
25968                                     return;
25969                                 }
25970                                 b.image_src = val;
25971                                 b.updateElement();
25972                                 syncValue();
25973                                 toolbar.editorcore.onEditorEvent();
25974                             },
25975                             minWidth:250,
25976                             prompt:true,
25977                             //multiline: multiline,
25978                             modal : true,
25979                             value : b.image_src
25980                         });
25981                     }
25982                 },
25983                 xns : rooui.Toolbar
25984             },
25985          
25986             {
25987                 xtype : 'Button',
25988                 text: 'Change Link URL',
25989                  
25990                 listeners : {
25991                     click: function (btn, state)
25992                     {
25993                         var b = block();
25994                         
25995                         Roo.MessageBox.show({
25996                             title : "Link URL",
25997                             msg : "Enter the url for the link - leave blank to have no link",
25998                             buttons: Roo.MessageBox.OKCANCEL,
25999                             fn: function(btn, val){
26000                                 if (btn != 'ok') {
26001                                     return;
26002                                 }
26003                                 b.href = val;
26004                                 b.updateElement();
26005                                 syncValue();
26006                                 toolbar.editorcore.onEditorEvent();
26007                             },
26008                             minWidth:250,
26009                             prompt:true,
26010                             //multiline: multiline,
26011                             modal : true,
26012                             value : b.href
26013                         });
26014                     }
26015                 },
26016                 xns : rooui.Toolbar
26017             },
26018             {
26019                 xtype : 'Button',
26020                 text: 'Show Video URL',
26021                  
26022                 listeners : {
26023                     click: function (btn, state)
26024                     {
26025                         Roo.MessageBox.alert("Video URL",
26026                             block().video_url == '' ? 'This image is not linked ot a video' :
26027                                 'The image is linked to: <a target="_new" href="' + block().video_url + '">' + block().video_url + '</a>');
26028                     }
26029                 },
26030                 xns : rooui.Toolbar
26031             },
26032             
26033             
26034             {
26035                 xtype : 'TextItem',
26036                 text : "Width: ",
26037                 xns : rooui.Toolbar  //Boostrap?
26038             },
26039             {
26040                 xtype : 'ComboBox',
26041                 allowBlank : false,
26042                 displayField : 'val',
26043                 editable : true,
26044                 listWidth : 100,
26045                 triggerAction : 'all',
26046                 typeAhead : true,
26047                 valueField : 'val',
26048                 width : 70,
26049                 name : 'width',
26050                 listeners : {
26051                     select : function (combo, r, index)
26052                     {
26053                         toolbar.editorcore.selectNode(toolbar.tb.selectedNode);
26054                         var b = block();
26055                         b.width = r.get('val');
26056                         b.updateElement();
26057                         syncValue();
26058                         toolbar.editorcore.onEditorEvent();
26059                     }
26060                 },
26061                 xns : rooui.form,
26062                 store : {
26063                     xtype : 'SimpleStore',
26064                     data : [
26065                         ['100%'],
26066                         ['80%'],
26067                         ['50%'],
26068                         ['20%'],
26069                         ['10%']
26070                     ],
26071                     fields : [ 'val'],
26072                     xns : Roo.data
26073                 }
26074             },
26075             {
26076                 xtype : 'TextItem',
26077                 text : "Align: ",
26078                 xns : rooui.Toolbar  //Boostrap?
26079             },
26080             {
26081                 xtype : 'ComboBox',
26082                 allowBlank : false,
26083                 displayField : 'val',
26084                 editable : true,
26085                 listWidth : 100,
26086                 triggerAction : 'all',
26087                 typeAhead : true,
26088                 valueField : 'val',
26089                 width : 70,
26090                 name : 'align',
26091                 listeners : {
26092                     select : function (combo, r, index)
26093                     {
26094                         toolbar.editorcore.selectNode(toolbar.tb.selectedNode);
26095                         var b = block();
26096                         b.align = r.get('val');
26097                         b.updateElement();
26098                         syncValue();
26099                         toolbar.editorcore.onEditorEvent();
26100                     }
26101                 },
26102                 xns : rooui.form,
26103                 store : {
26104                     xtype : 'SimpleStore',
26105                     data : [
26106                         ['left'],
26107                         ['right'],
26108                         ['center']
26109                     ],
26110                     fields : [ 'val'],
26111                     xns : Roo.data
26112                 }
26113             },
26114             
26115               
26116             {
26117                 xtype : 'Button',
26118                 text: 'Hide Caption',
26119                 name : 'caption_display',
26120                 pressed : false,
26121                 enableToggle : true,
26122                 setValue : function(v) {
26123                     // this trigger toggle.
26124                      
26125                     this.setText(v ? "Hide Caption" : "Show Caption");
26126                     this.setPressed(v != 'block');
26127                 },
26128                 listeners : {
26129                     toggle: function (btn, state)
26130                     {
26131                         var b  = block();
26132                         b.caption_display = b.caption_display == 'block' ? 'none' : 'block';
26133                         this.setText(b.caption_display == 'block' ? "Hide Caption" : "Show Caption");
26134                         b.updateElement();
26135                         syncValue();
26136                         toolbar.editorcore.selectNode(toolbar.tb.selectedNode);
26137                         toolbar.editorcore.onEditorEvent();
26138                     }
26139                 },
26140                 xns : rooui.Toolbar
26141             }
26142         ];
26143         
26144     },
26145     /**
26146      * create a DomHelper friendly object - for use with
26147      * Roo.DomHelper.markup / overwrite / etc..
26148      */
26149     toObject : function()
26150     {
26151         var d = document.createElement('div');
26152         d.innerHTML = this.caption;
26153         
26154         var m = this.width != '100%' && this.align == 'center' ? '0 auto' : 0; 
26155         
26156         var iw = this.align == 'center' ? this.width : '100%';
26157         var img =   {
26158             tag : 'img',
26159             contenteditable : 'false',
26160             src : this.image_src,
26161             alt : d.innerText.replace(/\n/g, " ").replace(/\s+/g, ' ').trim(), // removeHTML and reduce spaces..
26162             style: {
26163                 width : iw,
26164                 maxWidth : iw + ' !important', // this is not getting rendered?
26165                 margin : m  
26166                 
26167             },
26168             width: this.align == 'center' ?  this.width : '100%' 
26169
26170         };
26171         
26172         /*
26173         '<div class="{0}" width="420" height="315" src="{1}" frameborder="0" allowfullscreen>' +
26174                     '<a href="{2}">' + 
26175                         '<img class="{0}-thumbnail" src="{3}/Images/{4}/{5}#image-{4}" />' + 
26176                     '</a>' + 
26177                 '</div>',
26178         */
26179                 
26180         if (this.href.length > 0) {
26181             img = {
26182                 tag : 'a',
26183                 href: this.href,
26184                 contenteditable : 'true',
26185                 cn : [
26186                     img
26187                 ]
26188             };
26189         }
26190         
26191         
26192         if (this.video_url.length > 0) {
26193             img = {
26194                 tag : 'div',
26195                 cls : this.cls,
26196                 frameborder : 0,
26197                 allowfullscreen : true,
26198                 width : 420,  // these are for video tricks - that we replace the outer
26199                 height : 315,
26200                 src : this.video_url,
26201                 cn : [
26202                     img
26203                 ]
26204             };
26205         }
26206
26207
26208   
26209         var ret =   {
26210             tag: 'figure',
26211             'data-block' : 'Figure',
26212             'data-width' : this.width,
26213             'data-caption' : this.caption, 
26214             'data-caption-display' : this.caption_display,
26215             contenteditable : 'false',
26216             
26217             style : {
26218                 display: 'block',
26219                 float :  this.align ,
26220                 maxWidth :  this.align == 'center' ? '100% !important' : (this.width + ' !important'),
26221                 width : this.align == 'center' ? '100%' : this.width,
26222                 margin:  '0px',
26223                 padding: this.align == 'center' ? '0' : '0 10px' ,
26224                 textAlign : this.align   // seems to work for email..
26225                 
26226             },
26227             
26228             align : this.align,
26229             cn : [
26230                 img
26231             ]
26232         };
26233
26234         // show figcaption only if caption_display is 'block'
26235         if(this.caption_display == 'block') {
26236             ret['cn'].push({
26237                 tag: 'figcaption',
26238                 style : {
26239                     textAlign : 'left',
26240                     fontSize : '16px',
26241                     lineHeight : '24px',
26242                     display : this.caption_display,
26243                     maxWidth : (this.align == 'center' ?  this.width : '100%' ) + ' !important',
26244                     margin: m,
26245                     width: this.align == 'center' ?  this.width : '100%' 
26246                 
26247                      
26248                 },
26249                 cls : this.cls.length > 0 ? (this.cls  + '-thumbnail' ) : '',
26250                 cn : [
26251                     {
26252                         tag: 'div',
26253                         style  : {
26254                             marginTop : '16px',
26255                             textAlign : 'start'
26256                         },
26257                         align: 'left',
26258                         cn : [
26259                             {
26260                                 // we can not rely on yahoo syndication to use CSS elements - so have to use  '<i>' to encase stuff.
26261                                 tag : 'i',
26262                                 contenteditable : Roo.htmleditor.BlockFigure.caption_edit,
26263                                 html : this.caption.length ? this.caption : "Caption" // fake caption
26264                             }
26265                             
26266                         ]
26267                     }
26268                     
26269                 ]
26270                 
26271             });
26272         }
26273         return ret;
26274          
26275     },
26276     
26277     readElement : function(node)
26278     {
26279         // this should not really come from the link...
26280         this.video_url = this.getVal(node, 'div', 'src');
26281         this.cls = this.getVal(node, 'div', 'class');
26282         this.href = this.getVal(node, 'a', 'href');
26283         
26284         
26285         this.image_src = this.getVal(node, 'img', 'src');
26286          
26287         this.align = this.getVal(node, 'figure', 'align');
26288
26289         // caption display is stored in figure
26290         this.caption_display = this.getVal(node, true, 'data-caption-display');
26291
26292         // backward compatible
26293         // it was stored in figcaption
26294         if(this.caption_display == '') {
26295             this.caption_display = this.getVal(node, 'figcaption', 'data-display');
26296         }
26297
26298         // read caption from figcaption
26299         var figcaption = this.getVal(node, 'figcaption', false);
26300
26301         if (figcaption !== '') {
26302             this.caption = this.getVal(figcaption, 'i', 'html');
26303         }
26304                 
26305
26306         // read caption from data-caption in figure if no caption from figcaption
26307         var dc = this.getVal(node, true, 'data-caption');
26308
26309         if(this.caption_display == 'none' && dc && dc.length){
26310             this.caption = dc;
26311         }
26312
26313         //this.text_align = this.getVal(node, 'figcaption', 'style','text-align');
26314         this.width = this.getVal(node, true, 'data-width');
26315         //this.margin = this.getVal(node, 'figure', 'style', 'margin');
26316         
26317     },
26318     removeNode : function()
26319     {
26320         return this.node;
26321     }
26322     
26323   
26324    
26325      
26326     
26327     
26328     
26329     
26330 });
26331
26332 Roo.apply(Roo.htmleditor.BlockFigure, {
26333     caption_edit : true
26334 });
26335
26336  
26337
26338 /**
26339  * @class Roo.htmleditor.BlockTable
26340  * Block that manages a table
26341  * 
26342  * @constructor
26343  * Create a new Filter.
26344  * @param {Object} config Configuration options
26345  */
26346
26347 Roo.htmleditor.BlockTable = function(cfg)
26348 {
26349     if (cfg.node) {
26350         this.readElement(cfg.node);
26351         this.updateElement(cfg.node);
26352     }
26353     Roo.apply(this, cfg);
26354     if (!cfg.node) {
26355         this.rows = [];
26356         for(var r = 0; r < this.no_row; r++) {
26357             this.rows[r] = [];
26358             for(var c = 0; c < this.no_col; c++) {
26359                 this.rows[r][c] = this.emptyCell();
26360             }
26361         }
26362     }
26363     
26364     
26365 }
26366 Roo.extend(Roo.htmleditor.BlockTable, Roo.htmleditor.Block, {
26367  
26368     rows : false,
26369     no_col : 1,
26370     no_row : 1,
26371     
26372     
26373     width: '100%',
26374     
26375     // used by context menu
26376     friendly_name : 'Table',
26377     deleteTitle : 'Delete Table',
26378     // context menu is drawn once..
26379     
26380     contextMenu : function(toolbar)
26381     {
26382         
26383         var block = function() {
26384             return Roo.htmleditor.Block.factory(toolbar.tb.selectedNode);
26385         };
26386         
26387         
26388         var rooui =  typeof(Roo.bootstrap) == 'undefined' ? Roo : Roo.bootstrap;
26389         
26390         var syncValue = toolbar.editorcore.syncValue;
26391         
26392         var fields = {};
26393         
26394         return [
26395             {
26396                 xtype : 'TextItem',
26397                 text : "Width: ",
26398                 xns : rooui.Toolbar  //Boostrap?
26399             },
26400             {
26401                 xtype : 'ComboBox',
26402                 allowBlank : false,
26403                 displayField : 'val',
26404                 editable : true,
26405                 listWidth : 100,
26406                 triggerAction : 'all',
26407                 typeAhead : true,
26408                 valueField : 'val',
26409                 width : 100,
26410                 name : 'width',
26411                 listeners : {
26412                     select : function (combo, r, index)
26413                     {
26414                         toolbar.editorcore.selectNode(toolbar.tb.selectedNode);
26415                         var b = block();
26416                         b.width = r.get('val');
26417                         b.updateElement();
26418                         syncValue();
26419                         toolbar.editorcore.onEditorEvent();
26420                     }
26421                 },
26422                 xns : rooui.form,
26423                 store : {
26424                     xtype : 'SimpleStore',
26425                     data : [
26426                         ['100%'],
26427                         ['auto']
26428                     ],
26429                     fields : [ 'val'],
26430                     xns : Roo.data
26431                 }
26432             },
26433             // -------- Cols
26434             
26435             {
26436                 xtype : 'TextItem',
26437                 text : "Columns: ",
26438                 xns : rooui.Toolbar  //Boostrap?
26439             },
26440          
26441             {
26442                 xtype : 'Button',
26443                 text: '-',
26444                 listeners : {
26445                     click : function (_self, e)
26446                     {
26447                         toolbar.editorcore.selectNode(toolbar.tb.selectedNode);
26448                         block().removeColumn();
26449                         syncValue();
26450                         toolbar.editorcore.onEditorEvent();
26451                     }
26452                 },
26453                 xns : rooui.Toolbar
26454             },
26455             {
26456                 xtype : 'Button',
26457                 text: '+',
26458                 listeners : {
26459                     click : function (_self, e)
26460                     {
26461                         toolbar.editorcore.selectNode(toolbar.tb.selectedNode);
26462                         block().addColumn();
26463                         syncValue();
26464                         toolbar.editorcore.onEditorEvent();
26465                     }
26466                 },
26467                 xns : rooui.Toolbar
26468             },
26469             // -------- ROWS
26470             {
26471                 xtype : 'TextItem',
26472                 text : "Rows: ",
26473                 xns : rooui.Toolbar  //Boostrap?
26474             },
26475          
26476             {
26477                 xtype : 'Button',
26478                 text: '-',
26479                 listeners : {
26480                     click : function (_self, e)
26481                     {
26482                         toolbar.editorcore.selectNode(toolbar.tb.selectedNode);
26483                         block().removeRow();
26484                         syncValue();
26485                         toolbar.editorcore.onEditorEvent();
26486                     }
26487                 },
26488                 xns : rooui.Toolbar
26489             },
26490             {
26491                 xtype : 'Button',
26492                 text: '+',
26493                 listeners : {
26494                     click : function (_self, e)
26495                     {
26496                         block().addRow();
26497                         syncValue();
26498                         toolbar.editorcore.onEditorEvent();
26499                     }
26500                 },
26501                 xns : rooui.Toolbar
26502             },
26503             // -------- ROWS
26504             {
26505                 xtype : 'Button',
26506                 text: 'Reset Column Widths',
26507                 listeners : {
26508                     
26509                     click : function (_self, e)
26510                     {
26511                         block().resetWidths();
26512                         syncValue();
26513                         toolbar.editorcore.onEditorEvent();
26514                     }
26515                 },
26516                 xns : rooui.Toolbar
26517             } 
26518             
26519             
26520             
26521         ];
26522         
26523     },
26524     
26525     
26526   /**
26527      * create a DomHelper friendly object - for use with
26528      * Roo.DomHelper.markup / overwrite / etc..
26529      * ?? should it be called with option to hide all editing features?
26530      */
26531     toObject : function()
26532     {
26533         
26534         var ret = {
26535             tag : 'table',
26536             contenteditable : 'false', // this stops cell selection from picking the table.
26537             'data-block' : 'Table',
26538             style : {
26539                 width:  this.width,
26540                 border : 'solid 1px #000', // ??? hard coded?
26541                 'border-collapse' : 'collapse' 
26542             },
26543             cn : [
26544                 { tag : 'tbody' , cn : [] }
26545             ]
26546         };
26547         
26548         // do we have a head = not really 
26549         var ncols = 0;
26550         Roo.each(this.rows, function( row ) {
26551             var tr = {
26552                 tag: 'tr',
26553                 style : {
26554                     margin: '6px',
26555                     border : 'solid 1px #000',
26556                     textAlign : 'left' 
26557                 },
26558                 cn : [ ]
26559             };
26560             
26561             ret.cn[0].cn.push(tr);
26562             // does the row have any properties? ?? height?
26563             var nc = 0;
26564             Roo.each(row, function( cell ) {
26565                 
26566                 var td = {
26567                     tag : 'td',
26568                     contenteditable :  'true',
26569                     'data-block' : 'Td',
26570                     html : cell.html,
26571                     style : cell.style
26572                 };
26573                 if (cell.colspan > 1) {
26574                     td.colspan = cell.colspan ;
26575                     nc += cell.colspan;
26576                 } else {
26577                     nc++;
26578                 }
26579                 if (cell.rowspan > 1) {
26580                     td.rowspan = cell.rowspan ;
26581                 }
26582                 
26583                 
26584                 // widths ?
26585                 tr.cn.push(td);
26586                     
26587                 
26588             }, this);
26589             ncols = Math.max(nc, ncols);
26590             
26591             
26592         }, this);
26593         // add the header row..
26594         
26595         ncols++;
26596          
26597         
26598         return ret;
26599          
26600     },
26601     
26602     readElement : function(node)
26603     {
26604         node  = node ? node : this.node ;
26605         this.width = this.getVal(node, true, 'style', 'width') || '100%';
26606         
26607         this.rows = [];
26608         this.no_row = 0;
26609         var trs = Array.from(node.rows);
26610         trs.forEach(function(tr) {
26611             var row =  [];
26612             this.rows.push(row);
26613             
26614             this.no_row++;
26615             var no_column = 0;
26616             Array.from(tr.cells).forEach(function(td) {
26617                 
26618                 var add = {
26619                     colspan : td.hasAttribute('colspan') ? td.getAttribute('colspan')*1 : 1,
26620                     rowspan : td.hasAttribute('rowspan') ? td.getAttribute('rowspan')*1 : 1,
26621                     style : td.hasAttribute('style') ? td.getAttribute('style') : '',
26622                     html : td.innerHTML
26623                 };
26624                 no_column += add.colspan;
26625                      
26626                 
26627                 row.push(add);
26628                 
26629                 
26630             },this);
26631             this.no_col = Math.max(this.no_col, no_column);
26632             
26633             
26634         },this);
26635         
26636         
26637     },
26638     normalizeRows: function()
26639     {
26640         var ret= [];
26641         var rid = -1;
26642         this.rows.forEach(function(row) {
26643             rid++;
26644             ret[rid] = [];
26645             row = this.normalizeRow(row);
26646             var cid = 0;
26647             row.forEach(function(c) {
26648                 while (typeof(ret[rid][cid]) != 'undefined') {
26649                     cid++;
26650                 }
26651                 if (typeof(ret[rid]) == 'undefined') {
26652                     ret[rid] = [];
26653                 }
26654                 ret[rid][cid] = c;
26655                 c.row = rid;
26656                 c.col = cid;
26657                 if (c.rowspan < 2) {
26658                     return;
26659                 }
26660                 
26661                 for(var i = 1 ;i < c.rowspan; i++) {
26662                     if (typeof(ret[rid+i]) == 'undefined') {
26663                         ret[rid+i] = [];
26664                     }
26665                     ret[rid+i][cid] = c;
26666                 }
26667             });
26668         }, this);
26669         return ret;
26670     
26671     },
26672     
26673     normalizeRow: function(row)
26674     {
26675         var ret= [];
26676         row.forEach(function(c) {
26677             if (c.colspan < 2) {
26678                 ret.push(c);
26679                 return;
26680             }
26681             for(var i =0 ;i < c.colspan; i++) {
26682                 ret.push(c);
26683             }
26684         });
26685         return ret;
26686     
26687     },
26688     
26689     deleteColumn : function(sel)
26690     {
26691         if (!sel || sel.type != 'col') {
26692             return;
26693         }
26694         if (this.no_col < 2) {
26695             return;
26696         }
26697         
26698         this.rows.forEach(function(row) {
26699             var cols = this.normalizeRow(row);
26700             var col = cols[sel.col];
26701             if (col.colspan > 1) {
26702                 col.colspan --;
26703             } else {
26704                 row.remove(col);
26705             }
26706             
26707         }, this);
26708         this.no_col--;
26709         
26710     },
26711     removeColumn : function()
26712     {
26713         this.deleteColumn({
26714             type: 'col',
26715             col : this.no_col-1
26716         });
26717         this.updateElement();
26718     },
26719     
26720      
26721     addColumn : function()
26722     {
26723         
26724         this.rows.forEach(function(row) {
26725             row.push(this.emptyCell());
26726            
26727         }, this);
26728         this.updateElement();
26729     },
26730     
26731     deleteRow : function(sel)
26732     {
26733         if (!sel || sel.type != 'row') {
26734             return;
26735         }
26736         
26737         if (this.no_row < 2) {
26738             return;
26739         }
26740         
26741         var rows = this.normalizeRows();
26742         
26743         
26744         rows[sel.row].forEach(function(col) {
26745             if (col.rowspan > 1) {
26746                 col.rowspan--;
26747             } else {
26748                 col.remove = 1; // flage it as removed.
26749             }
26750             
26751         }, this);
26752         var newrows = [];
26753         this.rows.forEach(function(row) {
26754             newrow = [];
26755             row.forEach(function(c) {
26756                 if (typeof(c.remove) == 'undefined') {
26757                     newrow.push(c);
26758                 }
26759                 
26760             });
26761             if (newrow.length > 0) {
26762                 newrows.push(row);
26763             }
26764         });
26765         this.rows =  newrows;
26766         
26767         
26768         
26769         this.no_row--;
26770         this.updateElement();
26771         
26772     },
26773     removeRow : function()
26774     {
26775         this.deleteRow({
26776             type: 'row',
26777             row : this.no_row-1
26778         });
26779         
26780     },
26781     
26782      
26783     addRow : function()
26784     {
26785         
26786         var row = [];
26787         for (var i = 0; i < this.no_col; i++ ) {
26788             
26789             row.push(this.emptyCell());
26790            
26791         }
26792         this.rows.push(row);
26793         this.updateElement();
26794         
26795     },
26796      
26797     // the default cell object... at present...
26798     emptyCell : function() {
26799         return (new Roo.htmleditor.BlockTd({})).toObject();
26800         
26801      
26802     },
26803     
26804     removeNode : function()
26805     {
26806         return this.node;
26807     },
26808     
26809     
26810     
26811     resetWidths : function()
26812     {
26813         Array.from(this.node.getElementsByTagName('td')).forEach(function(n) {
26814             var nn = Roo.htmleditor.Block.factory(n);
26815             nn.width = '';
26816             nn.updateElement(n);
26817         });
26818     }
26819     
26820     
26821     
26822     
26823 })
26824
26825 /**
26826  *
26827  * editing a TD?
26828  *
26829  * since selections really work on the table cell, then editing really should work from there
26830  *
26831  * The original plan was to support merging etc... - but that may not be needed yet..
26832  *
26833  * So this simple version will support:
26834  *   add/remove cols
26835  *   adjust the width +/-
26836  *   reset the width...
26837  *   
26838  *
26839  */
26840
26841
26842  
26843
26844 /**
26845  * @class Roo.htmleditor.BlockTable
26846  * Block that manages a table
26847  * 
26848  * @constructor
26849  * Create a new Filter.
26850  * @param {Object} config Configuration options
26851  */
26852
26853 Roo.htmleditor.BlockTd = function(cfg)
26854 {
26855     if (cfg.node) {
26856         this.readElement(cfg.node);
26857         this.updateElement(cfg.node);
26858     }
26859     Roo.apply(this, cfg);
26860      
26861     
26862     
26863 }
26864 Roo.extend(Roo.htmleditor.BlockTd, Roo.htmleditor.Block, {
26865  
26866     node : false,
26867     
26868     width: '',
26869     textAlign : 'left',
26870     valign : 'top',
26871     
26872     colspan : 1,
26873     rowspan : 1,
26874     
26875     
26876     // used by context menu
26877     friendly_name : 'Table Cell',
26878     deleteTitle : false, // use our customer delete
26879     
26880     // context menu is drawn once..
26881     
26882     contextMenu : function(toolbar)
26883     {
26884         
26885         var cell = function() {
26886             return Roo.htmleditor.Block.factory(toolbar.tb.selectedNode);
26887         };
26888         
26889         var table = function() {
26890             return Roo.htmleditor.Block.factory(toolbar.tb.selectedNode.closest('table'));
26891         };
26892         
26893         var lr = false;
26894         var saveSel = function()
26895         {
26896             lr = toolbar.editorcore.getSelection().getRangeAt(0);
26897         }
26898         var restoreSel = function()
26899         {
26900             if (lr) {
26901                 (function() {
26902                     toolbar.editorcore.focus();
26903                     var cr = toolbar.editorcore.getSelection();
26904                     cr.removeAllRanges();
26905                     cr.addRange(lr);
26906                     toolbar.editorcore.onEditorEvent();
26907                 }).defer(10, this);
26908                 
26909                 
26910             }
26911         }
26912         
26913         var rooui =  typeof(Roo.bootstrap) == 'undefined' ? Roo : Roo.bootstrap;
26914         
26915         var syncValue = toolbar.editorcore.syncValue;
26916         
26917         var fields = {};
26918         
26919         return [
26920             {
26921                 xtype : 'Button',
26922                 text : 'Edit Table',
26923                 listeners : {
26924                     click : function() {
26925                         var t = toolbar.tb.selectedNode.closest('table');
26926                         toolbar.editorcore.selectNode(t);
26927                         toolbar.editorcore.onEditorEvent();                        
26928                     }
26929                 }
26930                 
26931             },
26932               
26933            
26934              
26935             {
26936                 xtype : 'TextItem',
26937                 text : "Column Width: ",
26938                  xns : rooui.Toolbar 
26939                
26940             },
26941             {
26942                 xtype : 'Button',
26943                 text: '-',
26944                 listeners : {
26945                     click : function (_self, e)
26946                     {
26947                         toolbar.editorcore.selectNode(toolbar.tb.selectedNode);
26948                         cell().shrinkColumn();
26949                         syncValue();
26950                          toolbar.editorcore.onEditorEvent();
26951                     }
26952                 },
26953                 xns : rooui.Toolbar
26954             },
26955             {
26956                 xtype : 'Button',
26957                 text: '+',
26958                 listeners : {
26959                     click : function (_self, e)
26960                     {
26961                         toolbar.editorcore.selectNode(toolbar.tb.selectedNode);
26962                         cell().growColumn();
26963                         syncValue();
26964                         toolbar.editorcore.onEditorEvent();
26965                     }
26966                 },
26967                 xns : rooui.Toolbar
26968             },
26969             
26970             {
26971                 xtype : 'TextItem',
26972                 text : "Vertical Align: ",
26973                 xns : rooui.Toolbar  //Boostrap?
26974             },
26975             {
26976                 xtype : 'ComboBox',
26977                 allowBlank : false,
26978                 displayField : 'val',
26979                 editable : true,
26980                 listWidth : 100,
26981                 triggerAction : 'all',
26982                 typeAhead : true,
26983                 valueField : 'val',
26984                 width : 100,
26985                 name : 'valign',
26986                 listeners : {
26987                     select : function (combo, r, index)
26988                     {
26989                         toolbar.editorcore.selectNode(toolbar.tb.selectedNode);
26990                         var b = cell();
26991                         b.valign = r.get('val');
26992                         b.updateElement();
26993                         syncValue();
26994                         toolbar.editorcore.onEditorEvent();
26995                     }
26996                 },
26997                 xns : rooui.form,
26998                 store : {
26999                     xtype : 'SimpleStore',
27000                     data : [
27001                         ['top'],
27002                         ['middle'],
27003                         ['bottom'] // there are afew more... 
27004                     ],
27005                     fields : [ 'val'],
27006                     xns : Roo.data
27007                 }
27008             },
27009             
27010             {
27011                 xtype : 'TextItem',
27012                 text : "Merge Cells: ",
27013                  xns : rooui.Toolbar 
27014                
27015             },
27016             
27017             
27018             {
27019                 xtype : 'Button',
27020                 text: 'Right',
27021                 listeners : {
27022                     click : function (_self, e)
27023                     {
27024                         toolbar.editorcore.selectNode(toolbar.tb.selectedNode);
27025                         cell().mergeRight();
27026                         //block().growColumn();
27027                         syncValue();
27028                         toolbar.editorcore.onEditorEvent();
27029                     }
27030                 },
27031                 xns : rooui.Toolbar
27032             },
27033              
27034             {
27035                 xtype : 'Button',
27036                 text: 'Below',
27037                 listeners : {
27038                     click : function (_self, e)
27039                     {
27040                         toolbar.editorcore.selectNode(toolbar.tb.selectedNode);
27041                         cell().mergeBelow();
27042                         //block().growColumn();
27043                         syncValue();
27044                         toolbar.editorcore.onEditorEvent();
27045                     }
27046                 },
27047                 xns : rooui.Toolbar
27048             },
27049             {
27050                 xtype : 'TextItem',
27051                 text : "| ",
27052                  xns : rooui.Toolbar 
27053                
27054             },
27055             
27056             {
27057                 xtype : 'Button',
27058                 text: 'Split',
27059                 listeners : {
27060                     click : function (_self, e)
27061                     {
27062                         //toolbar.editorcore.selectNode(toolbar.tb.selectedNode);
27063                         cell().split();
27064                         syncValue();
27065                         toolbar.editorcore.selectNode(toolbar.tb.selectedNode);
27066                         toolbar.editorcore.onEditorEvent();
27067                                              
27068                     }
27069                 },
27070                 xns : rooui.Toolbar
27071             },
27072             {
27073                 xtype : 'Fill',
27074                 xns : rooui.Toolbar 
27075                
27076             },
27077         
27078           
27079             {
27080                 xtype : 'Button',
27081                 text: 'Delete',
27082                  
27083                 xns : rooui.Toolbar,
27084                 menu : {
27085                     xtype : 'Menu',
27086                     xns : rooui.menu,
27087                     items : [
27088                         {
27089                             xtype : 'Item',
27090                             html: 'Column',
27091                             listeners : {
27092                                 click : function (_self, e)
27093                                 {
27094                                     var t = table();
27095                                     
27096                                     cell().deleteColumn();
27097                                     syncValue();
27098                                     toolbar.editorcore.selectNode(t.node);
27099                                     toolbar.editorcore.onEditorEvent();   
27100                                 }
27101                             },
27102                             xns : rooui.menu
27103                         },
27104                         {
27105                             xtype : 'Item',
27106                             html: 'Row',
27107                             listeners : {
27108                                 click : function (_self, e)
27109                                 {
27110                                     var t = table();
27111                                     cell().deleteRow();
27112                                     syncValue();
27113                                     
27114                                     toolbar.editorcore.selectNode(t.node);
27115                                     toolbar.editorcore.onEditorEvent();   
27116                                                          
27117                                 }
27118                             },
27119                             xns : rooui.menu
27120                         },
27121                        {
27122                             xtype : 'Separator',
27123                             xns : rooui.menu
27124                         },
27125                         {
27126                             xtype : 'Item',
27127                             html: 'Table',
27128                             listeners : {
27129                                 click : function (_self, e)
27130                                 {
27131                                     var t = table();
27132                                     var nn = t.node.nextSibling || t.node.previousSibling;
27133                                     t.node.parentNode.removeChild(t.node);
27134                                     if (nn) { 
27135                                         toolbar.editorcore.selectNode(nn, true);
27136                                     }
27137                                     toolbar.editorcore.onEditorEvent();   
27138                                                          
27139                                 }
27140                             },
27141                             xns : rooui.menu
27142                         }
27143                     ]
27144                 }
27145             }
27146             
27147             // align... << fixme
27148             
27149         ];
27150         
27151     },
27152     
27153     
27154   /**
27155      * create a DomHelper friendly object - for use with
27156      * Roo.DomHelper.markup / overwrite / etc..
27157      * ?? should it be called with option to hide all editing features?
27158      */
27159  /**
27160      * create a DomHelper friendly object - for use with
27161      * Roo.DomHelper.markup / overwrite / etc..
27162      * ?? should it be called with option to hide all editing features?
27163      */
27164     toObject : function()
27165     {
27166         var ret = {
27167             tag : 'td',
27168             contenteditable : 'true', // this stops cell selection from picking the table.
27169             'data-block' : 'Td',
27170             valign : this.valign,
27171             style : {  
27172                 'text-align' :  this.textAlign,
27173                 border : 'solid 1px rgb(0, 0, 0)', // ??? hard coded?
27174                 'border-collapse' : 'collapse',
27175                 padding : '6px', // 8 for desktop / 4 for mobile
27176                 'vertical-align': this.valign
27177             },
27178             html : this.html
27179         };
27180         if (this.width != '') {
27181             ret.width = this.width;
27182             ret.style.width = this.width;
27183         }
27184         
27185         
27186         if (this.colspan > 1) {
27187             ret.colspan = this.colspan ;
27188         } 
27189         if (this.rowspan > 1) {
27190             ret.rowspan = this.rowspan ;
27191         }
27192         
27193            
27194         
27195         return ret;
27196          
27197     },
27198     
27199     readElement : function(node)
27200     {
27201         node  = node ? node : this.node ;
27202         this.width = node.style.width;
27203         this.colspan = Math.max(1,1*node.getAttribute('colspan'));
27204         this.rowspan = Math.max(1,1*node.getAttribute('rowspan'));
27205         this.html = node.innerHTML;
27206         if (node.style.textAlign != '') {
27207             this.textAlign = node.style.textAlign;
27208         }
27209         
27210         
27211     },
27212      
27213     // the default cell object... at present...
27214     emptyCell : function() {
27215         return {
27216             colspan :  1,
27217             rowspan :  1,
27218             textAlign : 'left',
27219             html : "&nbsp;" // is this going to be editable now?
27220         };
27221      
27222     },
27223     
27224     removeNode : function()
27225     {
27226         return this.node.closest('table');
27227          
27228     },
27229     
27230     cellData : false,
27231     
27232     colWidths : false,
27233     
27234     toTableArray  : function()
27235     {
27236         var ret = [];
27237         var tab = this.node.closest('tr').closest('table');
27238         Array.from(tab.rows).forEach(function(r, ri){
27239             ret[ri] = [];
27240         });
27241         var rn = 0;
27242         this.colWidths = [];
27243         var all_auto = true;
27244         Array.from(tab.rows).forEach(function(r, ri){
27245             
27246             var cn = 0;
27247             Array.from(r.cells).forEach(function(ce, ci){
27248                 var c =  {
27249                     cell : ce,
27250                     row : rn,
27251                     col: cn,
27252                     colspan : ce.colSpan,
27253                     rowspan : ce.rowSpan
27254                 };
27255                 if (ce.isEqualNode(this.node)) {
27256                     this.cellData = c;
27257                 }
27258                 // if we have been filled up by a row?
27259                 if (typeof(ret[rn][cn]) != 'undefined') {
27260                     while(typeof(ret[rn][cn]) != 'undefined') {
27261                         cn++;
27262                     }
27263                     c.col = cn;
27264                 }
27265                 
27266                 if (typeof(this.colWidths[cn]) == 'undefined' && c.colspan < 2) {
27267                     this.colWidths[cn] =   ce.style.width;
27268                     if (this.colWidths[cn] != '') {
27269                         all_auto = false;
27270                     }
27271                 }
27272                 
27273                 
27274                 if (c.colspan < 2 && c.rowspan < 2 ) {
27275                     ret[rn][cn] = c;
27276                     cn++;
27277                     return;
27278                 }
27279                 for(var j = 0; j < c.rowspan; j++) {
27280                     if (typeof(ret[rn+j]) == 'undefined') {
27281                         continue; // we have a problem..
27282                     }
27283                     ret[rn+j][cn] = c;
27284                     for(var i = 0; i < c.colspan; i++) {
27285                         ret[rn+j][cn+i] = c;
27286                     }
27287                 }
27288                 
27289                 cn += c.colspan;
27290             }, this);
27291             rn++;
27292         }, this);
27293         
27294         // initalize widths.?
27295         // either all widths or no widths..
27296         if (all_auto) {
27297             this.colWidths[0] = false; // no widths flag.
27298         }
27299         
27300         
27301         return ret;
27302         
27303     },
27304     
27305     
27306     
27307     
27308     mergeRight: function()
27309     {
27310          
27311         // get the contents of the next cell along..
27312         var tr = this.node.closest('tr');
27313         var i = Array.prototype.indexOf.call(tr.childNodes, this.node);
27314         if (i >= tr.childNodes.length - 1) {
27315             return; // no cells on right to merge with.
27316         }
27317         var table = this.toTableArray();
27318         
27319         if (typeof(table[this.cellData.row][this.cellData.col+this.cellData.colspan]) == 'undefined') {
27320             return; // nothing right?
27321         }
27322         var rc = table[this.cellData.row][this.cellData.col+this.cellData.colspan];
27323         // right cell - must be same rowspan and on the same row.
27324         if (rc.rowspan != this.cellData.rowspan || rc.row != this.cellData.row) {
27325             return; // right hand side is not same rowspan.
27326         }
27327         
27328         
27329         
27330         this.node.innerHTML += ' ' + rc.cell.innerHTML;
27331         tr.removeChild(rc.cell);
27332         this.colspan += rc.colspan;
27333         this.node.setAttribute('colspan', this.colspan);
27334
27335         var table = this.toTableArray();
27336         this.normalizeWidths(table);
27337         this.updateWidths(table);
27338     },
27339     
27340     
27341     mergeBelow : function()
27342     {
27343         var table = this.toTableArray();
27344         if (typeof(table[this.cellData.row+this.cellData.rowspan]) == 'undefined') {
27345             return; // no row below
27346         }
27347         if (typeof(table[this.cellData.row+this.cellData.rowspan][this.cellData.col]) == 'undefined') {
27348             return; // nothing right?
27349         }
27350         var rc = table[this.cellData.row+this.cellData.rowspan][this.cellData.col];
27351         
27352         if (rc.colspan != this.cellData.colspan || rc.col != this.cellData.col) {
27353             return; // right hand side is not same rowspan.
27354         }
27355         this.node.innerHTML =  this.node.innerHTML + rc.cell.innerHTML ;
27356         rc.cell.parentNode.removeChild(rc.cell);
27357         this.rowspan += rc.rowspan;
27358         this.node.setAttribute('rowspan', this.rowspan);
27359     },
27360     
27361     split: function()
27362     {
27363         if (this.node.rowSpan < 2 && this.node.colSpan < 2) {
27364             return;
27365         }
27366         var table = this.toTableArray();
27367         var cd = this.cellData;
27368         this.rowspan = 1;
27369         this.colspan = 1;
27370         
27371         for(var r = cd.row; r < cd.row + cd.rowspan; r++) {
27372              
27373             
27374             for(var c = cd.col; c < cd.col + cd.colspan; c++) {
27375                 if (r == cd.row && c == cd.col) {
27376                     this.node.removeAttribute('rowspan');
27377                     this.node.removeAttribute('colspan');
27378                 }
27379                  
27380                 var ntd = this.node.cloneNode(); // which col/row should be 0..
27381                 ntd.removeAttribute('id'); 
27382                 ntd.style.width  = this.colWidths[c];
27383                 ntd.innerHTML = '';
27384                 table[r][c] = { cell : ntd, col : c, row: r , colspan : 1 , rowspan : 1   };
27385             }
27386             
27387         }
27388         this.redrawAllCells(table);
27389         
27390     },
27391     
27392     
27393     
27394     redrawAllCells: function(table)
27395     {
27396         
27397          
27398         var tab = this.node.closest('tr').closest('table');
27399         var ctr = tab.rows[0].parentNode;
27400         Array.from(tab.rows).forEach(function(r, ri){
27401             
27402             Array.from(r.cells).forEach(function(ce, ci){
27403                 ce.parentNode.removeChild(ce);
27404             });
27405             r.parentNode.removeChild(r);
27406         });
27407         for(var r = 0 ; r < table.length; r++) {
27408             var re = tab.rows[r];
27409             
27410             var re = tab.ownerDocument.createElement('tr');
27411             ctr.appendChild(re);
27412             for(var c = 0 ; c < table[r].length; c++) {
27413                 if (table[r][c].cell === false) {
27414                     continue;
27415                 }
27416                 
27417                 re.appendChild(table[r][c].cell);
27418                  
27419                 table[r][c].cell = false;
27420             }
27421         }
27422         
27423     },
27424     updateWidths : function(table)
27425     {
27426         for(var r = 0 ; r < table.length; r++) {
27427            
27428             for(var c = 0 ; c < table[r].length; c++) {
27429                 if (table[r][c].cell === false) {
27430                     continue;
27431                 }
27432                 
27433                 if (this.colWidths[0] != false && table[r][c].colspan < 2) {
27434                     var el = Roo.htmleditor.Block.factory(table[r][c].cell);
27435                     el.width = Math.floor(this.colWidths[c])  +'%';
27436                     el.updateElement(el.node);
27437                 }
27438                 if (this.colWidths[0] != false && table[r][c].colspan > 1) {
27439                     var el = Roo.htmleditor.Block.factory(table[r][c].cell);
27440                     var width = 0;
27441                     var lv = false;
27442                     for(var i = 0; i < table[r][c].colspan; i ++) {
27443                         if (typeof(this.colWidths[c + i]) != 'undefined') {
27444                             lv = this.colWidths[c + i];
27445                         } else {
27446                             this.colWidths[c + i] = lv;
27447                         }
27448                         width += Math.floor(this.colWidths[c + i]);
27449                     }
27450                     el.width = width  +'%';
27451                     el.updateElement(el.node);
27452                 }
27453                 table[r][c].cell = false; // done
27454             }
27455         }
27456     },
27457     normalizeWidths : function(table)
27458     {
27459         if (this.colWidths[0] === false) {
27460             var nw = 100.0 / this.colWidths.length;
27461             this.colWidths.forEach(function(w,i) {
27462                 this.colWidths[i] = nw;
27463             },this);
27464             return;
27465         }
27466     
27467         var t = 0, missing = [];
27468         
27469         this.colWidths.forEach(function(w,i) {
27470             //if you mix % and
27471             this.colWidths[i] = this.colWidths[i] == '' ? 0 : (this.colWidths[i]+'').replace(/[^0-9]+/g,'')*1;
27472             var add =  this.colWidths[i];
27473             if (add > 0) {
27474                 t+=add;
27475                 return;
27476             }
27477             missing.push(i);
27478             
27479             
27480         },this);
27481         var nc = this.colWidths.length;
27482         if (missing.length) {
27483             var mult = (nc - missing.length) / (1.0 * nc);
27484             var t = mult * t;
27485             var ew = (100 -t) / (1.0 * missing.length);
27486             this.colWidths.forEach(function(w,i) {
27487                 if (w > 0) {
27488                     this.colWidths[i] = w * mult;
27489                     return;
27490                 }
27491                 
27492                 this.colWidths[i] = ew;
27493             }, this);
27494             // have to make up numbers..
27495              
27496         }
27497         // now we should have all the widths..
27498         
27499     
27500     },
27501     
27502     shrinkColumn : function()
27503     {
27504         var table = this.toTableArray();
27505         this.normalizeWidths(table);
27506         var col = this.cellData.col;
27507         var nw = this.colWidths[col] * 0.8;
27508         if (nw < 5) {
27509             return;
27510         }
27511         var otherAdd = (this.colWidths[col]  * 0.2) / (this.colWidths.length -1);
27512         this.colWidths.forEach(function(w,i) {
27513             if (i == col) {
27514                  this.colWidths[i] = nw;
27515                 return;
27516             }
27517             if (typeof(this.colWidths[i]) == 'undefined') {
27518                 this.colWidths[i] = otherAdd;
27519             } else {
27520                 this.colWidths[i] += otherAdd;
27521             }
27522         }, this);
27523         this.updateWidths(table);
27524          
27525     },
27526     growColumn : function()
27527     {
27528         var table = this.toTableArray();
27529         this.normalizeWidths(table);
27530         var col = this.cellData.col;
27531         var nw = this.colWidths[col] * 1.2;
27532         if (nw > 90) {
27533             return;
27534         }
27535         var otherSub = (this.colWidths[col]  * 0.2) / (this.colWidths.length -1);
27536         this.colWidths.forEach(function(w,i) {
27537             if (i == col) {
27538                 this.colWidths[i] = nw;
27539                 return;
27540             }
27541             if (typeof(this.colWidths[i]) == 'undefined') {
27542                 this.colWidths[i] = otherSub;
27543             } else {
27544                 this.colWidths[i] -= otherSub;
27545             }
27546             
27547         }, this);
27548         this.updateWidths(table);
27549          
27550     },
27551     deleteRow : function()
27552     {
27553         // delete this rows 'tr'
27554         // if any of the cells in this row have a rowspan > 1 && row!= this row..
27555         // then reduce the rowspan.
27556         var table = this.toTableArray();
27557         // this.cellData.row;
27558         for (var i =0;i< table[this.cellData.row].length ; i++) {
27559             var c = table[this.cellData.row][i];
27560             if (c.row != this.cellData.row) {
27561                 
27562                 c.rowspan--;
27563                 c.cell.setAttribute('rowspan', c.rowspan);
27564                 continue;
27565             }
27566             if (c.rowspan > 1) {
27567                 c.rowspan--;
27568                 c.cell.setAttribute('rowspan', c.rowspan);
27569             }
27570         }
27571         table.splice(this.cellData.row,1);
27572         this.redrawAllCells(table);
27573         
27574     },
27575     deleteColumn : function()
27576     {
27577         var table = this.toTableArray();
27578         
27579         for (var i =0;i< table.length ; i++) {
27580             var c = table[i][this.cellData.col];
27581             if (c.col != this.cellData.col) {
27582                 table[i][this.cellData.col].colspan--;
27583             } else if (c.colspan > 1) {
27584                 c.colspan--;
27585                 c.cell.setAttribute('colspan', c.colspan);
27586             }
27587             table[i].splice(this.cellData.col,1);
27588         }
27589         
27590         this.redrawAllCells(table);
27591     }
27592     
27593     
27594     
27595     
27596 })
27597
27598 //<script type="text/javascript">
27599
27600 /*
27601  * Based  Ext JS Library 1.1.1
27602  * Copyright(c) 2006-2007, Ext JS, LLC.
27603  * LGPL
27604  *
27605  */
27606  
27607 /**
27608  * @class Roo.HtmlEditorCore
27609  * @extends Roo.Component
27610  * Provides a the editing component for the HTML editors in Roo. (bootstrap and Roo.form)
27611  *
27612  * any element that has display set to 'none' can cause problems in Safari and Firefox.<br/><br/>
27613  */
27614
27615 Roo.HtmlEditorCore = function(config){
27616     
27617     
27618     Roo.HtmlEditorCore.superclass.constructor.call(this, config);
27619     
27620     
27621     this.addEvents({
27622         /**
27623          * @event initialize
27624          * Fires when the editor is fully initialized (including the iframe)
27625          * @param {Roo.HtmlEditorCore} this
27626          */
27627         initialize: true,
27628         /**
27629          * @event activate
27630          * Fires when the editor is first receives the focus. Any insertion must wait
27631          * until after this event.
27632          * @param {Roo.HtmlEditorCore} this
27633          */
27634         activate: true,
27635          /**
27636          * @event beforesync
27637          * Fires before the textarea is updated with content from the editor iframe. Return false
27638          * to cancel the sync.
27639          * @param {Roo.HtmlEditorCore} this
27640          * @param {String} html
27641          */
27642         beforesync: true,
27643          /**
27644          * @event beforepush
27645          * Fires before the iframe editor is updated with content from the textarea. Return false
27646          * to cancel the push.
27647          * @param {Roo.HtmlEditorCore} this
27648          * @param {String} html
27649          */
27650         beforepush: true,
27651          /**
27652          * @event sync
27653          * Fires when the textarea is updated with content from the editor iframe.
27654          * @param {Roo.HtmlEditorCore} this
27655          * @param {String} html
27656          */
27657         sync: true,
27658          /**
27659          * @event push
27660          * Fires when the iframe editor is updated with content from the textarea.
27661          * @param {Roo.HtmlEditorCore} this
27662          * @param {String} html
27663          */
27664         push: true,
27665         
27666         /**
27667          * @event editorevent
27668          * Fires when on any editor (mouse up/down cursor movement etc.) - used for toolbar hooks.
27669          * @param {Roo.HtmlEditorCore} this
27670          */
27671         editorevent: true 
27672         
27673         
27674     });
27675     
27676     // at this point this.owner is set, so we can start working out the whitelisted / blacklisted elements
27677     
27678     // defaults : white / black...
27679     this.applyBlacklists();
27680     
27681     
27682     
27683 };
27684
27685
27686 Roo.extend(Roo.HtmlEditorCore, Roo.Component,  {
27687
27688
27689      /**
27690      * @cfg {Roo.form.HtmlEditor|Roo.bootstrap.HtmlEditor} the owner field 
27691      */
27692     
27693     owner : false,
27694     
27695      /**
27696      * @cfg {String} css styling for resizing. (used on bootstrap only)
27697      */
27698     resize : false,
27699      /**
27700      * @cfg {Number} height (in pixels)
27701      */   
27702     height: 300,
27703    /**
27704      * @cfg {Number} width (in pixels)
27705      */   
27706     width: 500,
27707      /**
27708      * @cfg {boolean} autoClean - default true - loading and saving will remove quite a bit of formating,
27709      *         if you are doing an email editor, this probably needs disabling, it's designed
27710      */
27711     autoClean: true,
27712     
27713     /**
27714      * @cfg {boolean} enableBlocks - default true - if the block editor (table and figure should be enabled)
27715      */
27716     enableBlocks : true,
27717     /**
27718      * @cfg {Array} stylesheets url of stylesheets. set to [] to disable stylesheets.
27719      * 
27720      */
27721     stylesheets: false,
27722      /**
27723      * @cfg {String} language default en - language of text (usefull for rtl languages)
27724      * 
27725      */
27726     language: 'en',
27727     
27728     /**
27729      * @cfg {boolean} allowComments - default false - allow comments in HTML source
27730      *          - by default they are stripped - if you are editing email you may need this.
27731      */
27732     allowComments: false,
27733     // id of frame..
27734     frameId: false,
27735     
27736     // private properties
27737     validationEvent : false,
27738     deferHeight: true,
27739     initialized : false,
27740     activated : false,
27741     sourceEditMode : false,
27742     onFocus : Roo.emptyFn,
27743     iframePad:3,
27744     hideMode:'offsets',
27745     
27746     clearUp: true,
27747     
27748     // blacklist + whitelisted elements..
27749     black: false,
27750     white: false,
27751      
27752     bodyCls : '',
27753
27754     
27755     undoManager : false,
27756     /**
27757      * Protected method that will not generally be called directly. It
27758      * is called when the editor initializes the iframe with HTML contents. Override this method if you
27759      * want to change the initialization markup of the iframe (e.g. to add stylesheets).
27760      */
27761     getDocMarkup : function(){
27762         // body styles..
27763         var st = '';
27764         
27765         // inherit styels from page...?? 
27766         if (this.stylesheets === false) {
27767             
27768             Roo.get(document.head).select('style').each(function(node) {
27769                 st += node.dom.outerHTML || new XMLSerializer().serializeToString(node.dom);
27770             });
27771             
27772             Roo.get(document.head).select('link').each(function(node) { 
27773                 st += node.dom.outerHTML || new XMLSerializer().serializeToString(node.dom);
27774             });
27775             
27776         } else if (!this.stylesheets.length) {
27777                 // simple..
27778                 st = '<style type="text/css">' +
27779                     'body{border:0;margin:0;padding:3px;height:98%;cursor:text;}' +
27780                    '</style>';
27781         } else {
27782             for (var i in this.stylesheets) {
27783                 if (typeof(this.stylesheets[i]) != 'string') {
27784                     continue;
27785                 }
27786                 st += '<link rel="stylesheet" href="' + this.stylesheets[i] +'" type="text/css">';
27787             }
27788             
27789         }
27790         
27791         st +=  '<style type="text/css">' +
27792             'IMG { cursor: pointer } ' +
27793         '</style>';
27794         
27795         st += '<meta name="google" content="notranslate">';
27796         
27797         var cls = 'notranslate roo-htmleditor-body';
27798         
27799         if(this.bodyCls.length){
27800             cls += ' ' + this.bodyCls;
27801         }
27802         
27803         return '<html  class="notranslate" translate="no"><head>' + st  +
27804             //<style type="text/css">' +
27805             //'body{border:0;margin:0;padding:3px;height:98%;cursor:text;}' +
27806             //'</style>' +
27807             ' </head><body contenteditable="true" data-enable-grammerly="true" class="' +  cls + '"></body></html>';
27808     },
27809
27810     // private
27811     onRender : function(ct, position)
27812     {
27813         var _t = this;
27814         //Roo.HtmlEditorCore.superclass.onRender.call(this, ct, position);
27815         this.el = this.owner.inputEl ? this.owner.inputEl() : this.owner.el;
27816         
27817         
27818         this.el.dom.style.border = '0 none';
27819         this.el.dom.setAttribute('tabIndex', -1);
27820         this.el.addClass('x-hidden hide');
27821         
27822         
27823         
27824         if(Roo.isIE){ // fix IE 1px bogus margin
27825             this.el.applyStyles('margin-top:-1px;margin-bottom:-1px;')
27826         }
27827        
27828         
27829         this.frameId = Roo.id();
27830         
27831         var ifcfg = {
27832             tag: 'iframe',
27833             cls: 'form-control', // bootstrap..
27834             id: this.frameId,
27835             name: this.frameId,
27836             frameBorder : 'no',
27837             'src' : Roo.SSL_SECURE_URL ? Roo.SSL_SECURE_URL  :  "javascript:false"
27838         };
27839         if (this.resize) {
27840             ifcfg.style = { resize : this.resize };
27841         }
27842         
27843         var iframe = this.owner.wrap.createChild(ifcfg, this.el); 
27844         
27845         
27846         this.iframe = iframe.dom;
27847
27848         this.assignDocWin();
27849         
27850         this.doc.designMode = 'on';
27851        
27852         this.doc.open();
27853         this.doc.write(this.getDocMarkup());
27854         this.doc.close();
27855
27856         
27857         var task = { // must defer to wait for browser to be ready
27858             run : function(){
27859                 //console.log("run task?" + this.doc.readyState);
27860                 this.assignDocWin();
27861                 if(this.doc.body || this.doc.readyState == 'complete'){
27862                     try {
27863                         this.doc.designMode="on";
27864                         
27865                     } catch (e) {
27866                         return;
27867                     }
27868                     Roo.TaskMgr.stop(task);
27869                     this.initEditor.defer(10, this);
27870                 }
27871             },
27872             interval : 10,
27873             duration: 10000,
27874             scope: this
27875         };
27876         Roo.TaskMgr.start(task);
27877
27878     },
27879
27880     // private
27881     onResize : function(w, h)
27882     {
27883          Roo.log('resize: ' +w + ',' + h );
27884         //Roo.HtmlEditorCore.superclass.onResize.apply(this, arguments);
27885         if(!this.iframe){
27886             return;
27887         }
27888         if(typeof w == 'number'){
27889             
27890             this.iframe.style.width = w + 'px';
27891         }
27892         if(typeof h == 'number'){
27893             
27894             this.iframe.style.height = h + 'px';
27895             if(this.doc){
27896                 (this.doc.body || this.doc.documentElement).style.height = (h - (this.iframePad*2)) + 'px';
27897             }
27898         }
27899         
27900     },
27901
27902     /**
27903      * Toggles the editor between standard and source edit mode.
27904      * @param {Boolean} sourceEdit (optional) True for source edit, false for standard
27905      */
27906     toggleSourceEdit : function(sourceEditMode){
27907         
27908         this.sourceEditMode = sourceEditMode === true;
27909         
27910         if(this.sourceEditMode){
27911  
27912             Roo.get(this.iframe).addClass(['x-hidden','hide', 'd-none']);     //FIXME - what's the BS styles for these
27913             
27914         }else{
27915             Roo.get(this.iframe).removeClass(['x-hidden','hide', 'd-none']);
27916             //this.iframe.className = '';
27917             this.deferFocus();
27918         }
27919         //this.setSize(this.owner.wrap.getSize());
27920         //this.fireEvent('editmodechange', this, this.sourceEditMode);
27921     },
27922
27923     
27924   
27925
27926     /**
27927      * Protected method that will not generally be called directly. If you need/want
27928      * custom HTML cleanup, this is the method you should override.
27929      * @param {String} html The HTML to be cleaned
27930      * return {String} The cleaned HTML
27931      */
27932     cleanHtml : function(html)
27933     {
27934         html = String(html);
27935         if(html.length > 5){
27936             if(Roo.isSafari){ // strip safari nonsense
27937                 html = html.replace(/\sclass="(?:Apple-style-span|khtml-block-placeholder)"/gi, '');
27938             }
27939         }
27940         if(html == '&nbsp;'){
27941             html = '';
27942         }
27943         return html;
27944     },
27945
27946     /**
27947      * HTML Editor -> Textarea
27948      * Protected method that will not generally be called directly. Syncs the contents
27949      * of the editor iframe with the textarea.
27950      */
27951     syncValue : function()
27952     {
27953         //Roo.log("HtmlEditorCore:syncValue (EDITOR->TEXT)");
27954         if(this.initialized){
27955             
27956             if (this.undoManager) {
27957                 this.undoManager.addEvent();
27958             }
27959
27960             
27961             var bd = (this.doc.body || this.doc.documentElement);
27962            
27963             
27964             var sel = this.win.getSelection();
27965             
27966             var div = document.createElement('div');
27967             div.innerHTML = bd.innerHTML;
27968             var gtx = div.getElementsByClassName('gtx-trans-icon'); // google translate - really annoying and difficult to get rid of.
27969             if (gtx.length > 0) {
27970                 var rm = gtx.item(0).parentNode;
27971                 rm.parentNode.removeChild(rm);
27972             }
27973             
27974            
27975             if (this.enableBlocks) {
27976                 Array.from(bd.getElementsByTagName('img')).forEach(function(img) {
27977                     var fig = img.closest('figure');
27978                     if (fig) {
27979                         var bf = new Roo.htmleditor.BlockFigure({
27980                             node : fig
27981                         });
27982                         bf.updateElement();
27983                     }
27984                     
27985                 });
27986                 new Roo.htmleditor.FilterBlock({ node : div });
27987             }
27988             
27989             var html = div.innerHTML;
27990             
27991             //?? tidy?
27992             if (this.autoClean) {
27993                 new Roo.htmleditor.FilterBlack({ node : div, tag : this.black});
27994                 new Roo.htmleditor.FilterAttributes({
27995                     node : div,
27996                     attrib_white : [
27997                             'href',
27998                             'src',
27999                             'name',
28000                             'align',
28001                             'colspan',
28002                             'rowspan',
28003                             'data-display',
28004                             'data-caption-display',
28005                             'data-width',
28006                             'data-caption',
28007                             'start' ,
28008                             'style',
28009                             // youtube embed.
28010                             'class',
28011                             'allowfullscreen',
28012                             'frameborder',
28013                             'width',
28014                             'height',
28015                             'alt'
28016                             ],
28017                     attrib_clean : ['href', 'src' ] 
28018                 });
28019                 new Roo.htmleditor.FilterEmpty({ node : div});
28020                 
28021                 var tidy = new Roo.htmleditor.TidySerializer({
28022                     inner:  true
28023                 });
28024                 html  = tidy.serialize(div);
28025                 
28026             }
28027             
28028             
28029             if(Roo.isSafari){
28030                 var bs = bd.getAttribute('style'); // Safari puts text-align styles on the body element!
28031                 var m = bs ? bs.match(/text-align:(.*?);/i) : false;
28032                 if(m && m[1]){
28033                     html = '<div style="'+m[0]+'">' + html + '</div>';
28034                 }
28035             }
28036             html = this.cleanHtml(html);
28037             // fix up the special chars.. normaly like back quotes in word...
28038             // however we do not want to do this with chinese..
28039             html = html.replace(/[\uD800-\uDBFF][\uDC00-\uDFFF]|[\u0080-\uFFFF]/g, function(match) {
28040                 
28041                 var cc = match.charCodeAt();
28042
28043                 // Get the character value, handling surrogate pairs
28044                 if (match.length == 2) {
28045                     // It's a surrogate pair, calculate the Unicode code point
28046                     var high = match.charCodeAt(0) - 0xD800;
28047                     var low  = match.charCodeAt(1) - 0xDC00;
28048                     cc = (high * 0x400) + low + 0x10000;
28049                 }  else if (
28050                     (cc >= 0x4E00 && cc < 0xA000 ) ||
28051                     (cc >= 0x3400 && cc < 0x4E00 ) ||
28052                     (cc >= 0xf900 && cc < 0xfb00 )
28053                 ) {
28054                         return match;
28055                 }  
28056          
28057                 // No, use a numeric entity. Here we brazenly (and possibly mistakenly)
28058                 return "&#" + cc + ";";
28059                 
28060                 
28061             });
28062             
28063             
28064              
28065             if(this.owner.fireEvent('beforesync', this, html) !== false){
28066                 this.el.dom.value = html;
28067                 this.owner.fireEvent('sync', this, html);
28068             }
28069         }
28070     },
28071
28072     /**
28073      * TEXTAREA -> EDITABLE
28074      * Protected method that will not generally be called directly. Pushes the value of the textarea
28075      * into the iframe editor.
28076      */
28077     pushValue : function()
28078     {
28079         //Roo.log("HtmlEditorCore:pushValue (TEXT->EDITOR)");
28080         if(this.initialized){
28081             var v = this.el.dom.value.trim();
28082             
28083             
28084             if(this.owner.fireEvent('beforepush', this, v) !== false){
28085                 var d = (this.doc.body || this.doc.documentElement);
28086                 d.innerHTML = v;
28087                  
28088                 this.el.dom.value = d.innerHTML;
28089                 this.owner.fireEvent('push', this, v);
28090             }
28091             if (this.autoClean) {
28092                 new Roo.htmleditor.FilterParagraph({node : this.doc.body}); // paragraphs
28093                 new Roo.htmleditor.FilterSpan({node : this.doc.body}); // empty spans
28094             }
28095             if (this.enableBlocks) {
28096                 Roo.htmleditor.Block.initAll(this.doc.body);
28097             }
28098             
28099             this.updateLanguage();
28100             
28101             var lc = this.doc.body.lastChild;
28102             if (lc && lc.nodeType == 1 && lc.getAttribute("contenteditable") == "false") {
28103                 // add an extra line at the end.
28104                 this.doc.body.appendChild(this.doc.createElement('br'));
28105             }
28106             
28107             
28108         }
28109     },
28110
28111     // private
28112     deferFocus : function(){
28113         this.focus.defer(10, this);
28114     },
28115
28116     // doc'ed in Field
28117     focus : function(){
28118         if(this.win && !this.sourceEditMode){
28119             this.win.focus();
28120         }else{
28121             this.el.focus();
28122         }
28123     },
28124     
28125     assignDocWin: function()
28126     {
28127         var iframe = this.iframe;
28128         
28129          if(Roo.isIE){
28130             this.doc = iframe.contentWindow.document;
28131             this.win = iframe.contentWindow;
28132         } else {
28133 //            if (!Roo.get(this.frameId)) {
28134 //                return;
28135 //            }
28136 //            this.doc = (iframe.contentDocument || Roo.get(this.frameId).dom.document);
28137 //            this.win = Roo.get(this.frameId).dom.contentWindow;
28138             
28139             if (!Roo.get(this.frameId) && !iframe.contentDocument) {
28140                 return;
28141             }
28142             
28143             this.doc = (iframe.contentDocument || Roo.get(this.frameId).dom.document);
28144             this.win = (iframe.contentWindow || Roo.get(this.frameId).dom.contentWindow);
28145         }
28146     },
28147     
28148     // private
28149     initEditor : function(){
28150         //console.log("INIT EDITOR");
28151         this.assignDocWin();
28152         
28153         
28154         
28155         this.doc.designMode="on";
28156         this.doc.open();
28157         this.doc.write(this.getDocMarkup());
28158         this.doc.close();
28159         
28160         var dbody = (this.doc.body || this.doc.documentElement);
28161         //var ss = this.el.getStyles('font-size', 'font-family', 'background-image', 'background-repeat');
28162         // this copies styles from the containing element into thsi one..
28163         // not sure why we need all of this..
28164         //var ss = this.el.getStyles('font-size', 'background-image', 'background-repeat');
28165         
28166         //var ss = this.el.getStyles( 'background-image', 'background-repeat');
28167         //ss['background-attachment'] = 'fixed'; // w3c
28168         dbody.bgProperties = 'fixed'; // ie
28169         dbody.setAttribute("translate", "no");
28170         
28171         //Roo.DomHelper.applyStyles(dbody, ss);
28172         Roo.EventManager.on(this.doc, {
28173              
28174             'mouseup': this.onEditorEvent,
28175             'dblclick': this.onEditorEvent,
28176             'click': this.onEditorEvent,
28177             'keyup': this.onEditorEvent,
28178             
28179             buffer:100,
28180             scope: this
28181         });
28182         Roo.EventManager.on(this.doc, {
28183             'paste': this.onPasteEvent,
28184             scope : this
28185         });
28186         if(Roo.isGecko){
28187             Roo.EventManager.on(this.doc, 'keypress', this.mozKeyPress, this);
28188         }
28189         //??? needed???
28190         if(Roo.isIE || Roo.isSafari || Roo.isOpera){
28191             Roo.EventManager.on(this.doc, 'keydown', this.fixKeys, this);
28192         }
28193         this.initialized = true;
28194
28195         
28196         // initialize special key events - enter
28197         new Roo.htmleditor.KeyEnter({core : this});
28198         
28199          
28200         
28201         this.owner.fireEvent('initialize', this);
28202         this.pushValue();
28203     },
28204     // this is to prevent a href clicks resulting in a redirect?
28205    
28206     onPasteEvent : function(e,v)
28207     {
28208         // I think we better assume paste is going to be a dirty load of rubish from word..
28209         
28210         // even pasting into a 'email version' of this widget will have to clean up that mess.
28211         var cd = (e.browserEvent.clipboardData || window.clipboardData);
28212         
28213         // check what type of paste - if it's an image, then handle it differently.
28214         if (cd.files && cd.files.length > 0 && cd.types.indexOf('text/html') < 0) {
28215             // pasting images? 
28216             var urlAPI = (window.createObjectURL && window) || 
28217                 (window.URL && URL.revokeObjectURL && URL) || 
28218                 (window.webkitURL && webkitURL);
28219             
28220             var r = new FileReader();
28221             var t = this;
28222             r.addEventListener('load',function()
28223             {
28224                 
28225                 var d = (new DOMParser().parseFromString('<img src="' + r.result+ '">', 'text/html')).body;
28226                 // is insert asycn?
28227                 if (t.enableBlocks) {
28228                     
28229                     Array.from(d.getElementsByTagName('img')).forEach(function(img) {
28230                         if (img.closest('figure')) { // assume!! that it's aready
28231                             return;
28232                         }
28233                         var fig  = new Roo.htmleditor.BlockFigure({
28234                             image_src  : img.src
28235                         });
28236                         fig.updateElement(img); // replace it..
28237                         
28238                     });
28239                 }
28240                 t.insertAtCursor(d.innerHTML.replace(/&nbsp;/g,' '));
28241                 t.owner.fireEvent('paste', this);
28242             });
28243             r.readAsDataURL(cd.files[0]);
28244             
28245             e.preventDefault();
28246             
28247             return false;
28248         }
28249         if (cd.types.indexOf('text/html') < 0 ) {
28250             return false;
28251         }
28252         var images = [];
28253         var html = cd.getData('text/html'); // clipboard event
28254         if (cd.types.indexOf('text/rtf') > -1) {
28255             var parser = new Roo.rtf.Parser(cd.getData('text/rtf'));
28256             images = parser.doc ? parser.doc.getElementsByType('pict') : [];
28257         }
28258         // Roo.log(images);
28259         // Roo.log(imgs);
28260         // fixme..
28261         images = images.filter(function(g) { return !g.path.match(/^rtf\/(head|pgdsctbl|listtable|footerf)/); }) // ignore headers/footers etc.
28262                        .map(function(g) { return g.toDataURL(); })
28263                        .filter(function(g) { return g != 'about:blank'; });
28264         
28265         //Roo.log(html);
28266         html = this.cleanWordChars(html);
28267         
28268         var d = (new DOMParser().parseFromString(html, 'text/html')).body;
28269         
28270         
28271         var sn = this.getParentElement();
28272         // check if d contains a table, and prevent nesting??
28273         //Roo.log(d.getElementsByTagName('table'));
28274         //Roo.log(sn);
28275         //Roo.log(sn.closest('table'));
28276         if (d.getElementsByTagName('table').length && sn && sn.closest('table')) {
28277             e.preventDefault();
28278             this.insertAtCursor("You can not nest tables");
28279             //Roo.log("prevent?"); // fixme - 
28280             return false;
28281         }
28282         
28283         
28284         
28285         if (images.length > 0) {
28286             // replace all v:imagedata - with img.
28287             var ar = Array.from(d.getElementsByTagName('v:imagedata'));
28288             Roo.each(ar, function(node) {
28289                 node.parentNode.insertBefore(d.ownerDocument.createElement('img'), node );
28290                 node.parentNode.removeChild(node);
28291             });
28292             
28293             
28294             Roo.each(d.getElementsByTagName('img'), function(img, i) {
28295                 img.setAttribute('src', images[i]);
28296             });
28297         }
28298         if (this.autoClean) {
28299             new Roo.htmleditor.FilterWord({ node : d });
28300             
28301             new Roo.htmleditor.FilterStyleToTag({ node : d });
28302             new Roo.htmleditor.FilterAttributes({
28303                 node : d,
28304                 attrib_white : [
28305                     'href',
28306                     'src',
28307                     'name',
28308                     'align',
28309                     'colspan',
28310                     'rowspan' 
28311                 /*  THESE ARE NOT ALLWOED FOR PASTE
28312                  *    'data-display',
28313                     'data-caption-display',
28314                     'data-width',
28315                     'data-caption',
28316                     'start' ,
28317                     'style',
28318                     // youtube embed.
28319                     'class',
28320                     'allowfullscreen',
28321                     'frameborder',
28322                     'width',
28323                     'height',
28324                     'alt'
28325                     */
28326                     ],
28327                 attrib_clean : ['href', 'src' ] 
28328             });
28329             new Roo.htmleditor.FilterBlack({ node : d, tag : this.black});
28330             // should be fonts..
28331             new Roo.htmleditor.FilterKeepChildren({node : d, tag : [ 'FONT', ':' ]} );
28332             new Roo.htmleditor.FilterParagraph({ node : d });
28333             new Roo.htmleditor.FilterHashLink({node : d});
28334             new Roo.htmleditor.FilterSpan({ node : d });
28335             new Roo.htmleditor.FilterLongBr({ node : d });
28336             new Roo.htmleditor.FilterComment({ node : d });
28337             new Roo.htmleditor.FilterEmpty({ node : d});
28338             
28339             
28340         }
28341         if (this.enableBlocks) {
28342                 
28343             Array.from(d.getElementsByTagName('img')).forEach(function(img) {
28344                 if (img.closest('figure')) { // assume!! that it's aready
28345                     return;
28346                 }
28347                 var fig  = new Roo.htmleditor.BlockFigure({
28348                     image_src  : img.src
28349                 });
28350                 fig.updateElement(img); // replace it..
28351                 
28352             });
28353         }
28354         
28355         
28356         this.insertAtCursor(d.innerHTML.replace(/&nbsp;/g,' '));
28357         if (this.enableBlocks) {
28358             Roo.htmleditor.Block.initAll(this.doc.body);
28359         }
28360          
28361         
28362         e.preventDefault();
28363         this.owner.fireEvent('paste', this);
28364         return false;
28365         // default behaveiour should be our local cleanup paste? (optional?)
28366         // for simple editor - we want to hammer the paste and get rid of everything... - so over-rideable..
28367         //this.owner.fireEvent('paste', e, v);
28368     },
28369     // private
28370     onDestroy : function(){
28371         
28372         
28373         
28374         if(this.rendered){
28375             
28376             //for (var i =0; i < this.toolbars.length;i++) {
28377             //    // fixme - ask toolbars for heights?
28378             //    this.toolbars[i].onDestroy();
28379            // }
28380             
28381             //this.wrap.dom.innerHTML = '';
28382             //this.wrap.remove();
28383         }
28384     },
28385
28386     // private
28387     onFirstFocus : function(){
28388         
28389         this.assignDocWin();
28390         this.undoManager = new Roo.lib.UndoManager(100,(this.doc.body || this.doc.documentElement));
28391         
28392         this.activated = true;
28393          
28394     
28395         if(Roo.isGecko){ // prevent silly gecko errors
28396             this.win.focus();
28397             var s = this.win.getSelection();
28398             if(!s.focusNode || s.focusNode.nodeType != 3){
28399                 var r = s.getRangeAt(0);
28400                 r.selectNodeContents((this.doc.body || this.doc.documentElement));
28401                 r.collapse(true);
28402                 this.deferFocus();
28403             }
28404             try{
28405                 this.execCmd('useCSS', true);
28406                 this.execCmd('styleWithCSS', false);
28407             }catch(e){}
28408         }
28409         this.owner.fireEvent('activate', this);
28410     },
28411
28412     // private
28413     adjustFont: function(btn){
28414         var adjust = btn.cmd == 'increasefontsize' ? 1 : -1;
28415         //if(Roo.isSafari){ // safari
28416         //    adjust *= 2;
28417        // }
28418         var v = parseInt(this.doc.queryCommandValue('FontSize')|| 3, 10);
28419         if(Roo.isSafari){ // safari
28420             var sm = { 10 : 1, 13: 2, 16:3, 18:4, 24: 5, 32:6, 48: 7 };
28421             v =  (v < 10) ? 10 : v;
28422             v =  (v > 48) ? 48 : v;
28423             v = typeof(sm[v]) == 'undefined' ? 1 : sm[v];
28424             
28425         }
28426         
28427         
28428         v = Math.max(1, v+adjust);
28429         
28430         this.execCmd('FontSize', v  );
28431     },
28432
28433     onEditorEvent : function(e)
28434     {
28435          
28436         
28437         if (e && (e.ctrlKey || e.metaKey) && e.keyCode === 90) {
28438             return; // we do not handle this.. (undo manager does..)
28439         }
28440         // clicking a 'block'?
28441         
28442         // in theory this detects if the last element is not a br, then we try and do that.
28443         // its so clicking in space at bottom triggers adding a br and moving the cursor.
28444         if (e &&
28445             e.target.nodeName == 'BODY' &&
28446             e.type == "mouseup" &&
28447             this.doc.body.lastChild
28448            ) {
28449             var lc = this.doc.body.lastChild;
28450             // gtx-trans is google translate plugin adding crap.
28451             while ((lc.nodeType == 3 && lc.nodeValue == '') || lc.id == 'gtx-trans') {
28452                 lc = lc.previousSibling;
28453             }
28454             if (lc.nodeType == 1 && lc.nodeName != 'BR') {
28455             // if last element is <BR> - then dont do anything.
28456             
28457                 var ns = this.doc.createElement('br');
28458                 this.doc.body.appendChild(ns);
28459                 range = this.doc.createRange();
28460                 range.setStartAfter(ns);
28461                 range.collapse(true);
28462                 var sel = this.win.getSelection();
28463                 sel.removeAllRanges();
28464                 sel.addRange(range);
28465             }
28466         }
28467         
28468         
28469         
28470         this.fireEditorEvent(e);
28471       //  this.updateToolbar();
28472         this.syncValue(); //we can not sync so often.. sync cleans, so this breaks stuff
28473     },
28474     
28475     fireEditorEvent: function(e)
28476     {
28477         this.owner.fireEvent('editorevent', this, e);
28478     },
28479
28480     insertTag : function(tg)
28481     {
28482         // could be a bit smarter... -> wrap the current selected tRoo..
28483         if (tg.toLowerCase() == 'span' ||
28484             tg.toLowerCase() == 'code' ||
28485             tg.toLowerCase() == 'sup' ||
28486             tg.toLowerCase() == 'sub' 
28487             ) {
28488             
28489             range = this.createRange(this.getSelection());
28490             var wrappingNode = this.doc.createElement(tg.toLowerCase());
28491             wrappingNode.appendChild(range.extractContents());
28492             range.insertNode(wrappingNode);
28493
28494             return;
28495             
28496             
28497             
28498         }
28499         this.execCmd("formatblock",   tg);
28500         this.undoManager.addEvent(); 
28501     },
28502     
28503     insertText : function(txt)
28504     {
28505         
28506         
28507         var range = this.createRange();
28508         range.deleteContents();
28509                //alert(Sender.getAttribute('label'));
28510                
28511         range.insertNode(this.doc.createTextNode(txt));
28512         this.undoManager.addEvent();
28513     } ,
28514     
28515      
28516
28517     /**
28518      * Executes a Midas editor command on the editor document and performs necessary focus and
28519      * toolbar updates. <b>This should only be called after the editor is initialized.</b>
28520      * @param {String} cmd The Midas command
28521      * @param {String/Boolean} value (optional) The value to pass to the command (defaults to null)
28522      */
28523     relayCmd : function(cmd, value)
28524     {
28525         
28526         switch (cmd) {
28527             case 'justifyleft':
28528             case 'justifyright':
28529             case 'justifycenter':
28530                 // if we are in a cell, then we will adjust the
28531                 var n = this.getParentElement();
28532                 var td = n.closest('td');
28533                 if (td) {
28534                     var bl = Roo.htmleditor.Block.factory(td);
28535                     bl.textAlign = cmd.replace('justify','');
28536                     bl.updateElement();
28537                     this.owner.fireEvent('editorevent', this);
28538                     return;
28539                 }
28540                 this.execCmd('styleWithCSS', true); // 
28541                 break;
28542             case 'bold':
28543             case 'italic':
28544             case 'underline':                
28545                 // if there is no selection, then we insert, and set the curson inside it..
28546                 this.execCmd('styleWithCSS', false); 
28547                 break;
28548                 
28549         
28550             default:
28551                 break;
28552         }
28553         
28554         
28555         this.win.focus();
28556         this.execCmd(cmd, value);
28557         this.owner.fireEvent('editorevent', this);
28558         //this.updateToolbar();
28559         this.owner.deferFocus();
28560     },
28561
28562     /**
28563      * Executes a Midas editor command directly on the editor document.
28564      * For visual commands, you should use {@link #relayCmd} instead.
28565      * <b>This should only be called after the editor is initialized.</b>
28566      * @param {String} cmd The Midas command
28567      * @param {String/Boolean} value (optional) The value to pass to the command (defaults to null)
28568      */
28569     execCmd : function(cmd, value){
28570         this.doc.execCommand(cmd, false, value === undefined ? null : value);
28571         this.syncValue();
28572     },
28573  
28574  
28575    
28576     /**
28577      * Inserts the passed text at the current cursor position. Note: the editor must be initialized and activated
28578      * to insert tRoo.
28579      * @param {String} text | dom node.. 
28580      */
28581     insertAtCursor : function(text)
28582     {
28583         
28584         if(!this.activated){
28585             return;
28586         }
28587          
28588         if(Roo.isGecko || Roo.isOpera || Roo.isSafari){
28589             this.win.focus();
28590             
28591             
28592             // from jquery ui (MIT licenced)
28593             var range, node;
28594             var win = this.win;
28595             
28596             if (win.getSelection && win.getSelection().getRangeAt) {
28597                 
28598                 // delete the existing?
28599                 
28600                 this.createRange(this.getSelection()).deleteContents();
28601                 range = win.getSelection().getRangeAt(0);
28602                 node = typeof(text) == 'string' ? range.createContextualFragment(text) : text;
28603                 range.insertNode(node);
28604                 range = range.cloneRange();
28605                 range.collapse(false);
28606                  
28607                 win.getSelection().removeAllRanges();
28608                 win.getSelection().addRange(range);
28609                 
28610                 
28611                 
28612             } else if (win.document.selection && win.document.selection.createRange) {
28613                 // no firefox support
28614                 var txt = typeof(text) == 'string' ? text : text.outerHTML;
28615                 win.document.selection.createRange().pasteHTML(txt);
28616             
28617             } else {
28618                 // no firefox support
28619                 var txt = typeof(text) == 'string' ? text : text.outerHTML;
28620                 this.execCmd('InsertHTML', txt);
28621             } 
28622             this.syncValue();
28623             
28624             this.deferFocus();
28625         }
28626     },
28627  // private
28628     mozKeyPress : function(e){
28629         if(e.ctrlKey){
28630             var c = e.getCharCode(), cmd;
28631           
28632             if(c > 0){
28633                 c = String.fromCharCode(c).toLowerCase();
28634                 switch(c){
28635                     case 'b':
28636                         cmd = 'bold';
28637                         break;
28638                     case 'i':
28639                         cmd = 'italic';
28640                         break;
28641                     
28642                     case 'u':
28643                         cmd = 'underline';
28644                         break;
28645                     
28646                     //case 'v':
28647                       //  this.cleanUpPaste.defer(100, this);
28648                       //  return;
28649                         
28650                 }
28651                 if(cmd){
28652                     
28653                     this.relayCmd(cmd);
28654                     //this.win.focus();
28655                     //this.execCmd(cmd);
28656                     //this.deferFocus();
28657                     e.preventDefault();
28658                 }
28659                 
28660             }
28661         }
28662     },
28663
28664     // private
28665     fixKeys : function(){ // load time branching for fastest keydown performance
28666         
28667         
28668         if(Roo.isIE){
28669             return function(e){
28670                 var k = e.getKey(), r;
28671                 if(k == e.TAB){
28672                     e.stopEvent();
28673                     r = this.doc.selection.createRange();
28674                     if(r){
28675                         r.collapse(true);
28676                         r.pasteHTML('&#160;&#160;&#160;&#160;');
28677                         this.deferFocus();
28678                     }
28679                     return;
28680                 }
28681                 /// this is handled by Roo.htmleditor.KeyEnter
28682                  /*
28683                 if(k == e.ENTER){
28684                     r = this.doc.selection.createRange();
28685                     if(r){
28686                         var target = r.parentElement();
28687                         if(!target || target.tagName.toLowerCase() != 'li'){
28688                             e.stopEvent();
28689                             r.pasteHTML('<br/>');
28690                             r.collapse(false);
28691                             r.select();
28692                         }
28693                     }
28694                 }
28695                 */
28696                 //if (String.fromCharCode(k).toLowerCase() == 'v') { // paste
28697                 //    this.cleanUpPaste.defer(100, this);
28698                 //    return;
28699                 //}
28700                 
28701                 
28702             };
28703         }else if(Roo.isOpera){
28704             return function(e){
28705                 var k = e.getKey();
28706                 if(k == e.TAB){
28707                     e.stopEvent();
28708                     this.win.focus();
28709                     this.execCmd('InsertHTML','&#160;&#160;&#160;&#160;');
28710                     this.deferFocus();
28711                 }
28712                
28713                 //if (String.fromCharCode(k).toLowerCase() == 'v') { // paste
28714                 //    this.cleanUpPaste.defer(100, this);
28715                  //   return;
28716                 //}
28717                 
28718             };
28719         }else if(Roo.isSafari){
28720             return function(e){
28721                 var k = e.getKey();
28722                 
28723                 if(k == e.TAB){
28724                     e.stopEvent();
28725                     this.execCmd('InsertText','\t');
28726                     this.deferFocus();
28727                     return;
28728                 }
28729                  this.mozKeyPress(e);
28730                 
28731                //if (String.fromCharCode(k).toLowerCase() == 'v') { // paste
28732                  //   this.cleanUpPaste.defer(100, this);
28733                  //   return;
28734                // }
28735                 
28736              };
28737         }
28738     }(),
28739     
28740     getAllAncestors: function()
28741     {
28742         var p = this.getSelectedNode();
28743         var a = [];
28744         if (!p) {
28745             a.push(p); // push blank onto stack..
28746             p = this.getParentElement();
28747         }
28748         
28749         
28750         while (p && (p.nodeType == 1) && (p.tagName.toLowerCase() != 'body')) {
28751             a.push(p);
28752             p = p.parentNode;
28753         }
28754         a.push(this.doc.body);
28755         return a;
28756     },
28757     lastSel : false,
28758     lastSelNode : false,
28759     
28760     
28761     getSelection : function() 
28762     {
28763         this.assignDocWin();
28764         return Roo.lib.Selection.wrap(Roo.isIE ? this.doc.selection : this.win.getSelection(), this.doc);
28765     },
28766     /**
28767      * Select a dom node
28768      * @param {DomElement} node the node to select
28769      */
28770     selectNode : function(node, collapse)
28771     {
28772         var nodeRange = node.ownerDocument.createRange();
28773         try {
28774             nodeRange.selectNode(node);
28775         } catch (e) {
28776             nodeRange.selectNodeContents(node);
28777         }
28778         if (collapse === true) {
28779             nodeRange.collapse(true);
28780         }
28781         //
28782         var s = this.win.getSelection();
28783         s.removeAllRanges();
28784         s.addRange(nodeRange);
28785     },
28786     
28787     getSelectedNode: function() 
28788     {
28789         // this may only work on Gecko!!!
28790         
28791         // should we cache this!!!!
28792         
28793          
28794          
28795         var range = this.createRange(this.getSelection()).cloneRange();
28796         
28797         if (Roo.isIE) {
28798             var parent = range.parentElement();
28799             while (true) {
28800                 var testRange = range.duplicate();
28801                 testRange.moveToElementText(parent);
28802                 if (testRange.inRange(range)) {
28803                     break;
28804                 }
28805                 if ((parent.nodeType != 1) || (parent.tagName.toLowerCase() == 'body')) {
28806                     break;
28807                 }
28808                 parent = parent.parentElement;
28809             }
28810             return parent;
28811         }
28812         
28813         // is ancestor a text element.
28814         var ac =  range.commonAncestorContainer;
28815         if (ac.nodeType == 3) {
28816             ac = ac.parentNode;
28817         }
28818         
28819         var ar = ac.childNodes;
28820          
28821         var nodes = [];
28822         var other_nodes = [];
28823         var has_other_nodes = false;
28824         for (var i=0;i<ar.length;i++) {
28825             if ((ar[i].nodeType == 3) && (!ar[i].data.length)) { // empty text ? 
28826                 continue;
28827             }
28828             // fullly contained node.
28829             
28830             if (this.rangeIntersectsNode(range,ar[i]) && this.rangeCompareNode(range,ar[i]) == 3) {
28831                 nodes.push(ar[i]);
28832                 continue;
28833             }
28834             
28835             // probably selected..
28836             if ((ar[i].nodeType == 1) && this.rangeIntersectsNode(range,ar[i]) && (this.rangeCompareNode(range,ar[i]) > 0)) {
28837                 other_nodes.push(ar[i]);
28838                 continue;
28839             }
28840             // outer..
28841             if (!this.rangeIntersectsNode(range,ar[i])|| (this.rangeCompareNode(range,ar[i]) == 0))  {
28842                 continue;
28843             }
28844             
28845             
28846             has_other_nodes = true;
28847         }
28848         if (!nodes.length && other_nodes.length) {
28849             nodes= other_nodes;
28850         }
28851         if (has_other_nodes || !nodes.length || (nodes.length > 1)) {
28852             return false;
28853         }
28854         
28855         return nodes[0];
28856     },
28857     
28858     
28859     createRange: function(sel)
28860     {
28861         // this has strange effects when using with 
28862         // top toolbar - not sure if it's a great idea.
28863         //this.editor.contentWindow.focus();
28864         if (typeof sel != "undefined") {
28865             try {
28866                 return sel.getRangeAt ? sel.getRangeAt(0) : sel.createRange();
28867             } catch(e) {
28868                 return this.doc.createRange();
28869             }
28870         } else {
28871             return this.doc.createRange();
28872         }
28873     },
28874     getParentElement: function()
28875     {
28876         
28877         this.assignDocWin();
28878         var sel = Roo.isIE ? this.doc.selection : this.win.getSelection();
28879         
28880         var range = this.createRange(sel);
28881          
28882         try {
28883             var p = range.commonAncestorContainer;
28884             while (p.nodeType == 3) { // text node
28885                 p = p.parentNode;
28886             }
28887             return p;
28888         } catch (e) {
28889             return null;
28890         }
28891     
28892     },
28893     /***
28894      *
28895      * Range intersection.. the hard stuff...
28896      *  '-1' = before
28897      *  '0' = hits..
28898      *  '1' = after.
28899      *         [ -- selected range --- ]
28900      *   [fail]                        [fail]
28901      *
28902      *    basically..
28903      *      if end is before start or  hits it. fail.
28904      *      if start is after end or hits it fail.
28905      *
28906      *   if either hits (but other is outside. - then it's not 
28907      *   
28908      *    
28909      **/
28910     
28911     
28912     // @see http://www.thismuchiknow.co.uk/?p=64.
28913     rangeIntersectsNode : function(range, node)
28914     {
28915         var nodeRange = node.ownerDocument.createRange();
28916         try {
28917             nodeRange.selectNode(node);
28918         } catch (e) {
28919             nodeRange.selectNodeContents(node);
28920         }
28921     
28922         var rangeStartRange = range.cloneRange();
28923         rangeStartRange.collapse(true);
28924     
28925         var rangeEndRange = range.cloneRange();
28926         rangeEndRange.collapse(false);
28927     
28928         var nodeStartRange = nodeRange.cloneRange();
28929         nodeStartRange.collapse(true);
28930     
28931         var nodeEndRange = nodeRange.cloneRange();
28932         nodeEndRange.collapse(false);
28933     
28934         return rangeStartRange.compareBoundaryPoints(
28935                  Range.START_TO_START, nodeEndRange) == -1 &&
28936                rangeEndRange.compareBoundaryPoints(
28937                  Range.START_TO_START, nodeStartRange) == 1;
28938         
28939          
28940     },
28941     rangeCompareNode : function(range, node)
28942     {
28943         var nodeRange = node.ownerDocument.createRange();
28944         try {
28945             nodeRange.selectNode(node);
28946         } catch (e) {
28947             nodeRange.selectNodeContents(node);
28948         }
28949         
28950         
28951         range.collapse(true);
28952     
28953         nodeRange.collapse(true);
28954      
28955         var ss = range.compareBoundaryPoints( Range.START_TO_START, nodeRange);
28956         var ee = range.compareBoundaryPoints(  Range.END_TO_END, nodeRange);
28957          
28958         //Roo.log(node.tagName + ': ss='+ss +', ee='+ee)
28959         
28960         var nodeIsBefore   =  ss == 1;
28961         var nodeIsAfter    = ee == -1;
28962         
28963         if (nodeIsBefore && nodeIsAfter) {
28964             return 0; // outer
28965         }
28966         if (!nodeIsBefore && nodeIsAfter) {
28967             return 1; //right trailed.
28968         }
28969         
28970         if (nodeIsBefore && !nodeIsAfter) {
28971             return 2;  // left trailed.
28972         }
28973         // fully contined.
28974         return 3;
28975     },
28976  
28977     cleanWordChars : function(input) {// change the chars to hex code
28978         
28979        var swapCodes  = [ 
28980             [    8211, "&#8211;" ], 
28981             [    8212, "&#8212;" ], 
28982             [    8216,  "'" ],  
28983             [    8217, "'" ],  
28984             [    8220, '"' ],  
28985             [    8221, '"' ],  
28986             [    8226, "*" ],  
28987             [    8230, "..." ]
28988         ]; 
28989         var output = input;
28990         Roo.each(swapCodes, function(sw) { 
28991             var swapper = new RegExp("\\u" + sw[0].toString(16), "g"); // hex codes
28992             
28993             output = output.replace(swapper, sw[1]);
28994         });
28995         
28996         return output;
28997     },
28998     
28999      
29000     
29001         
29002     
29003     cleanUpChild : function (node)
29004     {
29005         
29006         new Roo.htmleditor.FilterComment({node : node});
29007         new Roo.htmleditor.FilterAttributes({
29008                 node : node,
29009                 attrib_black : this.ablack,
29010                 attrib_clean : this.aclean,
29011                 style_white : this.cwhite,
29012                 style_black : this.cblack
29013         });
29014         new Roo.htmleditor.FilterBlack({ node : node, tag : this.black});
29015         new Roo.htmleditor.FilterKeepChildren({node : node, tag : this.tag_remove} );
29016          
29017         
29018     },
29019     
29020     /**
29021      * Clean up MS wordisms...
29022      * @deprecated - use filter directly
29023      */
29024     cleanWord : function(node)
29025     {
29026         new Roo.htmleditor.FilterWord({ node : node ? node : this.doc.body });
29027         new Roo.htmleditor.FilterKeepChildren({node : node ? node : this.doc.body, tag : [ 'FONT', ':' ]} );
29028         
29029     },
29030    
29031     
29032     /**
29033
29034      * @deprecated - use filters
29035      */
29036     cleanTableWidths : function(node)
29037     {
29038         new Roo.htmleditor.FilterTableWidth({ node : node ? node : this.doc.body});
29039         
29040  
29041     },
29042     
29043      
29044         
29045     applyBlacklists : function()
29046     {
29047         var w = typeof(this.owner.white) != 'undefined' && this.owner.white ? this.owner.white  : [];
29048         var b = typeof(this.owner.black) != 'undefined' && this.owner.black ? this.owner.black :  [];
29049         
29050         this.aclean = typeof(this.owner.aclean) != 'undefined' && this.owner.aclean ? this.owner.aclean :  Roo.HtmlEditorCore.aclean;
29051         this.ablack = typeof(this.owner.ablack) != 'undefined' && this.owner.ablack ? this.owner.ablack :  Roo.HtmlEditorCore.ablack;
29052         this.tag_remove = typeof(this.owner.tag_remove) != 'undefined' && this.owner.tag_remove ? this.owner.tag_remove :  Roo.HtmlEditorCore.tag_remove;
29053         
29054         this.white = [];
29055         this.black = [];
29056         Roo.each(Roo.HtmlEditorCore.white, function(tag) {
29057             if (b.indexOf(tag) > -1) {
29058                 return;
29059             }
29060             this.white.push(tag);
29061             
29062         }, this);
29063         
29064         Roo.each(w, function(tag) {
29065             if (b.indexOf(tag) > -1) {
29066                 return;
29067             }
29068             if (this.white.indexOf(tag) > -1) {
29069                 return;
29070             }
29071             this.white.push(tag);
29072             
29073         }, this);
29074         
29075         
29076         Roo.each(Roo.HtmlEditorCore.black, function(tag) {
29077             if (w.indexOf(tag) > -1) {
29078                 return;
29079             }
29080             this.black.push(tag);
29081             
29082         }, this);
29083         
29084         Roo.each(b, function(tag) {
29085             if (w.indexOf(tag) > -1) {
29086                 return;
29087             }
29088             if (this.black.indexOf(tag) > -1) {
29089                 return;
29090             }
29091             this.black.push(tag);
29092             
29093         }, this);
29094         
29095         
29096         w = typeof(this.owner.cwhite) != 'undefined' && this.owner.cwhite ? this.owner.cwhite  : [];
29097         b = typeof(this.owner.cblack) != 'undefined' && this.owner.cblack ? this.owner.cblack :  [];
29098         
29099         this.cwhite = [];
29100         this.cblack = [];
29101         Roo.each(Roo.HtmlEditorCore.cwhite, function(tag) {
29102             if (b.indexOf(tag) > -1) {
29103                 return;
29104             }
29105             this.cwhite.push(tag);
29106             
29107         }, this);
29108         
29109         Roo.each(w, function(tag) {
29110             if (b.indexOf(tag) > -1) {
29111                 return;
29112             }
29113             if (this.cwhite.indexOf(tag) > -1) {
29114                 return;
29115             }
29116             this.cwhite.push(tag);
29117             
29118         }, this);
29119         
29120         
29121         Roo.each(Roo.HtmlEditorCore.cblack, function(tag) {
29122             if (w.indexOf(tag) > -1) {
29123                 return;
29124             }
29125             this.cblack.push(tag);
29126             
29127         }, this);
29128         
29129         Roo.each(b, function(tag) {
29130             if (w.indexOf(tag) > -1) {
29131                 return;
29132             }
29133             if (this.cblack.indexOf(tag) > -1) {
29134                 return;
29135             }
29136             this.cblack.push(tag);
29137             
29138         }, this);
29139     },
29140     
29141     setStylesheets : function(stylesheets)
29142     {
29143         if(typeof(stylesheets) == 'string'){
29144             Roo.get(this.iframe.contentDocument.head).createChild({
29145                 tag : 'link',
29146                 rel : 'stylesheet',
29147                 type : 'text/css',
29148                 href : stylesheets
29149             });
29150             
29151             return;
29152         }
29153         var _this = this;
29154      
29155         Roo.each(stylesheets, function(s) {
29156             if(!s.length){
29157                 return;
29158             }
29159             
29160             Roo.get(_this.iframe.contentDocument.head).createChild({
29161                 tag : 'link',
29162                 rel : 'stylesheet',
29163                 type : 'text/css',
29164                 href : s
29165             });
29166         });
29167
29168         
29169     },
29170     
29171     
29172     updateLanguage : function()
29173     {
29174         if (!this.iframe || !this.iframe.contentDocument) {
29175             return;
29176         }
29177         Roo.get(this.iframe.contentDocument.body).attr("lang", this.language);
29178     },
29179     
29180     
29181     removeStylesheets : function()
29182     {
29183         var _this = this;
29184         
29185         Roo.each(Roo.get(_this.iframe.contentDocument.head).select('link[rel=stylesheet]', true).elements, function(s){
29186             s.remove();
29187         });
29188     },
29189     
29190     setStyle : function(style)
29191     {
29192         Roo.get(this.iframe.contentDocument.head).createChild({
29193             tag : 'style',
29194             type : 'text/css',
29195             html : style
29196         });
29197
29198         return;
29199     }
29200     
29201     // hide stuff that is not compatible
29202     /**
29203      * @event blur
29204      * @hide
29205      */
29206     /**
29207      * @event change
29208      * @hide
29209      */
29210     /**
29211      * @event focus
29212      * @hide
29213      */
29214     /**
29215      * @event specialkey
29216      * @hide
29217      */
29218     /**
29219      * @cfg {String} fieldClass @hide
29220      */
29221     /**
29222      * @cfg {String} focusClass @hide
29223      */
29224     /**
29225      * @cfg {String} autoCreate @hide
29226      */
29227     /**
29228      * @cfg {String} inputType @hide
29229      */
29230     /**
29231      * @cfg {String} invalidClass @hide
29232      */
29233     /**
29234      * @cfg {String} invalidText @hide
29235      */
29236     /**
29237      * @cfg {String} msgFx @hide
29238      */
29239     /**
29240      * @cfg {String} validateOnBlur @hide
29241      */
29242 });
29243
29244 Roo.HtmlEditorCore.white = [
29245         'AREA', 'BR', 'IMG', 'INPUT', 'HR', 'WBR',
29246         
29247        'ADDRESS', 'BLOCKQUOTE', 'CENTER', 'DD',      'DIR',       'DIV', 
29248        'DL',      'DT',         'H1',     'H2',      'H3',        'H4', 
29249        'H5',      'H6',         'HR',     'ISINDEX', 'LISTING',   'MARQUEE', 
29250        'MENU',    'MULTICOL',   'OL',     'P',       'PLAINTEXT', 'PRE', 
29251        'TABLE',   'UL',         'XMP', 
29252        
29253        'CAPTION', 'COL', 'COLGROUP', 'TBODY', 'TD', 'TFOOT', 'TH', 
29254       'THEAD',   'TR', 
29255      
29256       'DIR', 'MENU', 'OL', 'UL', 'DL',
29257        
29258       'EMBED',  'OBJECT'
29259 ];
29260
29261
29262 Roo.HtmlEditorCore.black = [
29263     //    'embed',  'object', // enable - backend responsiblity to clean thiese
29264         'APPLET', // 
29265         'BASE',   'BASEFONT', 'BGSOUND', 'BLINK',  'BODY', 
29266         'FRAME',  'FRAMESET', 'HEAD',    'HTML',   'ILAYER', 
29267         'IFRAME', 'LAYER',  'LINK',     'META',    'OBJECT',   
29268         'SCRIPT', 'STYLE' ,'TITLE',  'XML',
29269         //'FONT' // CLEAN LATER..
29270         'COLGROUP', 'COL'   // messy tables.
29271         
29272         
29273 ];
29274 Roo.HtmlEditorCore.clean = [ // ?? needed???
29275      'SCRIPT', 'STYLE', 'TITLE', 'XML'
29276 ];
29277 Roo.HtmlEditorCore.tag_remove = [
29278     'FONT', 'TBODY'  
29279 ];
29280 // attributes..
29281
29282 Roo.HtmlEditorCore.ablack = [
29283     'on'
29284 ];
29285     
29286 Roo.HtmlEditorCore.aclean = [ 
29287     'action', 'background', 'codebase', 'dynsrc', 'href', 'lowsrc' 
29288 ];
29289
29290 // protocols..
29291 Roo.HtmlEditorCore.pwhite= [
29292         'http',  'https',  'mailto'
29293 ];
29294
29295 // white listed style attributes.
29296 Roo.HtmlEditorCore.cwhite= [
29297       //  'text-align', /// default is to allow most things..
29298       
29299          
29300 //        'font-size'//??
29301 ];
29302
29303 // black listed style attributes.
29304 Roo.HtmlEditorCore.cblack= [
29305       //  'font-size' -- this can be set by the project 
29306 ];
29307
29308
29309
29310
29311     //<script type="text/javascript">
29312
29313 /*
29314  * Ext JS Library 1.1.1
29315  * Copyright(c) 2006-2007, Ext JS, LLC.
29316  * Licence LGPL
29317  * 
29318  */
29319  
29320  
29321 Roo.form.HtmlEditor = function(config){
29322     
29323     
29324     
29325     Roo.form.HtmlEditor.superclass.constructor.call(this, config);
29326     
29327     if (!this.toolbars) {
29328         this.toolbars = [];
29329     }
29330     this.editorcore = new Roo.HtmlEditorCore(Roo.apply({ owner : this} , config));
29331     
29332     
29333 };
29334
29335 /**
29336  * @class Roo.form.HtmlEditor
29337  * @extends Roo.form.Field
29338  * Provides a lightweight HTML Editor component.
29339  *
29340  * This has been tested on Fireforx / Chrome.. IE may not be so great..
29341  * 
29342  * <br><br><b>Note: The focus/blur and validation marking functionality inherited from Ext.form.Field is NOT
29343  * supported by this editor.</b><br/><br/>
29344  * An Editor is a sensitive component that can't be used in all spots standard fields can be used. Putting an Editor within
29345  * any element that has display set to 'none' can cause problems in Safari and Firefox.<br/><br/>
29346  */
29347 Roo.extend(Roo.form.HtmlEditor, Roo.form.Field, {
29348     /**
29349      * @cfg {Boolean} clearUp
29350      */
29351     clearUp : true,
29352       /**
29353      * @cfg {Array} toolbars Array of toolbars. - defaults to just the Standard one
29354      */
29355     toolbars : false,
29356    
29357      /**
29358      * @cfg {String} resizable  's' or 'se' or 'e' - wrapps the element in a
29359      *                        Roo.resizable.
29360      */
29361     resizable : false,
29362      /**
29363      * @cfg {Number} height (in pixels)
29364      */   
29365     height: 300,
29366    /**
29367      * @cfg {Number} width (in pixels)
29368      */   
29369     width: 500,
29370     
29371     /**
29372      * @cfg {Array} stylesheets url of stylesheets. set to [] to disable stylesheets - this is usally a good idea  rootURL + '/roojs1/css/undoreset.css',   .
29373      * 
29374      */
29375     stylesheets: false,
29376     
29377     
29378      /**
29379      * @cfg {Array} blacklist of css styles style attributes (blacklist overrides whitelist)
29380      * 
29381      */
29382     cblack: false,
29383     /**
29384      * @cfg {Array} whitelist of css styles style attributes (blacklist overrides whitelist)
29385      * 
29386      */
29387     cwhite: false,
29388     
29389      /**
29390      * @cfg {Array} blacklist of html tags - in addition to standard blacklist.
29391      * 
29392      */
29393     black: false,
29394     /**
29395      * @cfg {Array} whitelist of html tags - in addition to statndard whitelist
29396      * 
29397      */
29398     white: false,
29399     /**
29400      * @cfg {boolean} allowComments - default false - allow comments in HTML source - by default they are stripped - if you are editing email you may need this.
29401      */
29402     allowComments: false,
29403     /**
29404      * @cfg {boolean} enableBlocks - default true - if the block editor (table and figure should be enabled)
29405      */
29406     enableBlocks : true,
29407     
29408     /**
29409      * @cfg {boolean} autoClean - default true - loading and saving will remove quite a bit of formating,
29410      *         if you are doing an email editor, this probably needs disabling, it's designed
29411      */
29412     autoClean: true,
29413     /**
29414      * @cfg {string} bodyCls default '' default classes to add to body of editable area - usually undoreset is a good start..
29415      */
29416     bodyCls : '',
29417     /**
29418      * @cfg {String} language default en - language of text (usefull for rtl languages)
29419      * 
29420      */
29421     language: 'en',
29422     
29423      
29424     // id of frame..
29425     frameId: false,
29426     
29427     // private properties
29428     validationEvent : false,
29429     deferHeight: true,
29430     initialized : false,
29431     activated : false,
29432     
29433     onFocus : Roo.emptyFn,
29434     iframePad:3,
29435     hideMode:'offsets',
29436     
29437     actionMode : 'container', // defaults to hiding it...
29438     
29439     defaultAutoCreate : { // modified by initCompnoent..
29440         tag: "textarea",
29441         style:"width:500px;height:300px;",
29442         autocomplete: "new-password"
29443     },
29444
29445     // private
29446     initComponent : function(){
29447         this.addEvents({
29448             /**
29449              * @event initialize
29450              * Fires when the editor is fully initialized (including the iframe)
29451              * @param {HtmlEditor} this
29452              */
29453             initialize: true,
29454             /**
29455              * @event activate
29456              * Fires when the editor is first receives the focus. Any insertion must wait
29457              * until after this event.
29458              * @param {HtmlEditor} this
29459              */
29460             activate: true,
29461              /**
29462              * @event beforesync
29463              * Fires before the textarea is updated with content from the editor iframe. Return false
29464              * to cancel the sync.
29465              * @param {HtmlEditor} this
29466              * @param {String} html
29467              */
29468             beforesync: true,
29469              /**
29470              * @event beforepush
29471              * Fires before the iframe editor is updated with content from the textarea. Return false
29472              * to cancel the push.
29473              * @param {HtmlEditor} this
29474              * @param {String} html
29475              */
29476             beforepush: true,
29477              /**
29478              * @event sync
29479              * Fires when the textarea is updated with content from the editor iframe.
29480              * @param {HtmlEditor} this
29481              * @param {String} html
29482              */
29483             sync: true,
29484              /**
29485              * @event push
29486              * Fires when the iframe editor is updated with content from the textarea.
29487              * @param {HtmlEditor} this
29488              * @param {String} html
29489              */
29490             push: true,
29491              /**
29492              * @event editmodechange
29493              * Fires when the editor switches edit modes
29494              * @param {HtmlEditor} this
29495              * @param {Boolean} sourceEdit True if source edit, false if standard editing.
29496              */
29497             editmodechange: true,
29498             /**
29499              * @event editorevent
29500              * Fires when on any editor (mouse up/down cursor movement etc.) - used for toolbar hooks.
29501              * @param {HtmlEditor} this
29502              */
29503             editorevent: true,
29504             /**
29505              * @event firstfocus
29506              * Fires when on first focus - needed by toolbars..
29507              * @param {HtmlEditor} this
29508              */
29509             firstfocus: true,
29510             /**
29511              * @event autosave
29512              * Auto save the htmlEditor value as a file into Events
29513              * @param {HtmlEditor} this
29514              */
29515             autosave: true,
29516             /**
29517              * @event savedpreview
29518              * preview the saved version of htmlEditor
29519              * @param {HtmlEditor} this
29520              */
29521             savedpreview: true,
29522             
29523             /**
29524             * @event stylesheetsclick
29525             * Fires when press the Sytlesheets button
29526             * @param {Roo.HtmlEditorCore} this
29527             */
29528             stylesheetsclick: true,
29529             /**
29530             * @event paste
29531             * Fires when press user pastes into the editor
29532             * @param {Roo.HtmlEditorCore} this
29533             */
29534             paste: true 
29535             
29536         });
29537         this.defaultAutoCreate =  {
29538             tag: "textarea",
29539             style:'width: ' + this.width + 'px;height: ' + this.height + 'px;',
29540             autocomplete: "new-password"
29541         };
29542     },
29543
29544     /**
29545      * Protected method that will not generally be called directly. It
29546      * is called when the editor creates its toolbar. Override this method if you need to
29547      * add custom toolbar buttons.
29548      * @param {HtmlEditor} editor
29549      */
29550     createToolbar : function(editor){
29551         Roo.log("create toolbars");
29552         if (!editor.toolbars || !editor.toolbars.length) {
29553             editor.toolbars = [ new Roo.form.HtmlEditor.ToolbarStandard() ]; // can be empty?
29554         }
29555         
29556         for (var i =0 ; i < editor.toolbars.length;i++) {
29557             editor.toolbars[i] = Roo.factory(
29558                     typeof(editor.toolbars[i]) == 'string' ?
29559                         { xtype: editor.toolbars[i]} : editor.toolbars[i],
29560                 Roo.form.HtmlEditor);
29561             editor.toolbars[i].init(editor);
29562         }
29563          
29564         
29565     },
29566     /**
29567      * get the Context selected node
29568      * @returns {DomElement|boolean} selected node if active or false if none
29569      * 
29570      */
29571     getSelectedNode : function()
29572     {
29573         if (this.toolbars.length < 2 || !this.toolbars[1].tb) {
29574             return false;
29575         }
29576         return this.toolbars[1].tb.selectedNode;
29577     
29578     },
29579     // private
29580     onRender : function(ct, position)
29581     {
29582         var _t = this;
29583         Roo.form.HtmlEditor.superclass.onRender.call(this, ct, position);
29584         
29585         this.wrap = this.el.wrap({
29586             cls:'x-html-editor-wrap', cn:{cls:'x-html-editor-tb'}
29587         });
29588         
29589         this.editorcore.onRender(ct, position);
29590          
29591         if (this.resizable) {
29592             this.resizeEl = new Roo.Resizable(this.wrap, {
29593                 pinned : true,
29594                 wrap: true,
29595                 dynamic : true,
29596                 minHeight : this.height,
29597                 height: this.height,
29598                 handles : this.resizable,
29599                 width: this.width,
29600                 listeners : {
29601                     resize : function(r, w, h) {
29602                         _t.onResize(w,h); // -something
29603                     }
29604                 }
29605             });
29606             
29607         }
29608         this.createToolbar(this);
29609        
29610         
29611         if(!this.width){
29612             this.setSize(this.wrap.getSize());
29613         }
29614         if (this.resizeEl) {
29615             this.resizeEl.resizeTo.defer(100, this.resizeEl,[ this.width,this.height ] );
29616             // should trigger onReize..
29617         }
29618         
29619         this.keyNav = new Roo.KeyNav(this.el, {
29620             
29621             "tab" : function(e){
29622                 e.preventDefault();
29623                 
29624                 var value = this.getValue();
29625                 
29626                 var start = this.el.dom.selectionStart;
29627                 var end = this.el.dom.selectionEnd;
29628                 
29629                 if(!e.shiftKey){
29630                     
29631                     this.setValue(value.substring(0, start) + "\t" + value.substring(end));
29632                     this.el.dom.setSelectionRange(end + 1, end + 1);
29633                     return;
29634                 }
29635                 
29636                 var f = value.substring(0, start).split("\t");
29637                 
29638                 if(f.pop().length != 0){
29639                     return;
29640                 }
29641                 
29642                 this.setValue(f.join("\t") + value.substring(end));
29643                 this.el.dom.setSelectionRange(start - 1, start - 1);
29644                 
29645             },
29646             
29647             "home" : function(e){
29648                 e.preventDefault();
29649                 
29650                 var curr = this.el.dom.selectionStart;
29651                 var lines = this.getValue().split("\n");
29652                 
29653                 if(!lines.length){
29654                     return;
29655                 }
29656                 
29657                 if(e.ctrlKey){
29658                     this.el.dom.setSelectionRange(0, 0);
29659                     return;
29660                 }
29661                 
29662                 var pos = 0;
29663                 
29664                 for (var i = 0; i < lines.length;i++) {
29665                     pos += lines[i].length;
29666                     
29667                     if(i != 0){
29668                         pos += 1;
29669                     }
29670                     
29671                     if(pos < curr){
29672                         continue;
29673                     }
29674                     
29675                     pos -= lines[i].length;
29676                     
29677                     break;
29678                 }
29679                 
29680                 if(!e.shiftKey){
29681                     this.el.dom.setSelectionRange(pos, pos);
29682                     return;
29683                 }
29684                 
29685                 this.el.dom.selectionStart = pos;
29686                 this.el.dom.selectionEnd = curr;
29687             },
29688             
29689             "end" : function(e){
29690                 e.preventDefault();
29691                 
29692                 var curr = this.el.dom.selectionStart;
29693                 var lines = this.getValue().split("\n");
29694                 
29695                 if(!lines.length){
29696                     return;
29697                 }
29698                 
29699                 if(e.ctrlKey){
29700                     this.el.dom.setSelectionRange(this.getValue().length, this.getValue().length);
29701                     return;
29702                 }
29703                 
29704                 var pos = 0;
29705                 
29706                 for (var i = 0; i < lines.length;i++) {
29707                     
29708                     pos += lines[i].length;
29709                     
29710                     if(i != 0){
29711                         pos += 1;
29712                     }
29713                     
29714                     if(pos < curr){
29715                         continue;
29716                     }
29717                     
29718                     break;
29719                 }
29720                 
29721                 if(!e.shiftKey){
29722                     this.el.dom.setSelectionRange(pos, pos);
29723                     return;
29724                 }
29725                 
29726                 this.el.dom.selectionStart = curr;
29727                 this.el.dom.selectionEnd = pos;
29728             },
29729
29730             scope : this,
29731
29732             doRelay : function(foo, bar, hname){
29733                 return Roo.KeyNav.prototype.doRelay.apply(this, arguments);
29734             },
29735
29736             forceKeyDown: true
29737         });
29738         
29739 //        if(this.autosave && this.w){
29740 //            this.autoSaveFn = setInterval(this.autosave, 1000);
29741 //        }
29742     },
29743
29744     // private
29745     onResize : function(w, h)
29746     {
29747         Roo.form.HtmlEditor.superclass.onResize.apply(this, arguments);
29748         var ew = false;
29749         var eh = false;
29750         
29751         if(this.el ){
29752             if(typeof w == 'number'){
29753                 var aw = w - this.wrap.getFrameWidth('lr');
29754                 this.el.setWidth(this.adjustWidth('textarea', aw));
29755                 ew = aw;
29756             }
29757             if(typeof h == 'number'){
29758                 var tbh = 0;
29759                 for (var i =0; i < this.toolbars.length;i++) {
29760                     // fixme - ask toolbars for heights?
29761                     tbh += this.toolbars[i].tb.el.getHeight();
29762                     if (this.toolbars[i].footer) {
29763                         tbh += this.toolbars[i].footer.el.getHeight();
29764                     }
29765                 }
29766                 
29767                 
29768                 
29769                 
29770                 var ah = h - this.wrap.getFrameWidth('tb') - tbh;// this.tb.el.getHeight();
29771                 ah -= 5; // knock a few pixes off for look..
29772 //                Roo.log(ah);
29773                 this.el.setHeight(this.adjustWidth('textarea', ah));
29774                 var eh = ah;
29775             }
29776         }
29777         Roo.log('onResize:' + [w,h,ew,eh].join(',') );
29778         this.editorcore.onResize(ew,eh);
29779         
29780     },
29781
29782     /**
29783      * Toggles the editor between standard and source edit mode.
29784      * @param {Boolean} sourceEdit (optional) True for source edit, false for standard
29785      */
29786     toggleSourceEdit : function(sourceEditMode)
29787     {
29788         this.editorcore.toggleSourceEdit(sourceEditMode);
29789         
29790         if(this.editorcore.sourceEditMode){
29791             Roo.log('editor - showing textarea');
29792             
29793 //            Roo.log('in');
29794 //            Roo.log(this.syncValue());
29795             this.editorcore.syncValue();
29796             this.el.removeClass('x-hidden');
29797             this.el.dom.removeAttribute('tabIndex');
29798             this.el.focus();
29799             this.el.dom.scrollTop = 0;
29800             
29801             
29802             for (var i = 0; i < this.toolbars.length; i++) {
29803                 if(this.toolbars[i] instanceof Roo.form.HtmlEditor.ToolbarContext){
29804                     this.toolbars[i].tb.hide();
29805                     this.toolbars[i].footer.hide();
29806                 }
29807             }
29808             
29809         }else{
29810             Roo.log('editor - hiding textarea');
29811 //            Roo.log('out')
29812 //            Roo.log(this.pushValue()); 
29813             this.editorcore.pushValue();
29814             
29815             this.el.addClass('x-hidden');
29816             this.el.dom.setAttribute('tabIndex', -1);
29817             
29818             for (var i = 0; i < this.toolbars.length; i++) {
29819                 if(this.toolbars[i] instanceof Roo.form.HtmlEditor.ToolbarContext){
29820                     this.toolbars[i].tb.show();
29821                     this.toolbars[i].footer.show();
29822                 }
29823             }
29824             
29825             //this.deferFocus();
29826         }
29827         
29828         this.setSize(this.wrap.getSize());
29829         this.onResize(this.wrap.getSize().width, this.wrap.getSize().height);
29830         
29831         this.fireEvent('editmodechange', this, this.editorcore.sourceEditMode);
29832     },
29833  
29834     // private (for BoxComponent)
29835     adjustSize : Roo.BoxComponent.prototype.adjustSize,
29836
29837     // private (for BoxComponent)
29838     getResizeEl : function(){
29839         return this.wrap;
29840     },
29841
29842     // private (for BoxComponent)
29843     getPositionEl : function(){
29844         return this.wrap;
29845     },
29846
29847     // private
29848     initEvents : function(){
29849         this.originalValue = this.getValue();
29850     },
29851
29852     /**
29853      * Overridden and disabled. The editor element does not support standard valid/invalid marking. @hide
29854      * @method
29855      */
29856     markInvalid : Roo.emptyFn,
29857     /**
29858      * Overridden and disabled. The editor element does not support standard valid/invalid marking. @hide
29859      * @method
29860      */
29861     clearInvalid : Roo.emptyFn,
29862
29863     setValue : function(v){
29864         Roo.form.HtmlEditor.superclass.setValue.call(this, v);
29865         this.editorcore.pushValue();
29866     },
29867
29868     /**
29869      * update the language in the body - really done by core
29870      * @param {String} language - eg. en / ar / zh-CN etc..
29871      */
29872     updateLanguage : function(lang)
29873     {
29874         this.language = lang;
29875         this.editorcore.language = lang;
29876         this.editorcore.updateLanguage();
29877      
29878     },
29879     // private
29880     deferFocus : function(){
29881         this.focus.defer(10, this);
29882     },
29883
29884     // doc'ed in Field
29885     focus : function(){
29886         this.editorcore.focus();
29887         
29888     },
29889       
29890
29891     // private
29892     onDestroy : function(){
29893         
29894         
29895         
29896         if(this.rendered){
29897             
29898             for (var i =0; i < this.toolbars.length;i++) {
29899                 // fixme - ask toolbars for heights?
29900                 this.toolbars[i].onDestroy();
29901             }
29902             
29903             this.wrap.dom.innerHTML = '';
29904             this.wrap.remove();
29905         }
29906     },
29907
29908     // private
29909     onFirstFocus : function(){
29910         //Roo.log("onFirstFocus");
29911         this.editorcore.onFirstFocus();
29912          for (var i =0; i < this.toolbars.length;i++) {
29913             this.toolbars[i].onFirstFocus();
29914         }
29915         
29916     },
29917     
29918     // private
29919     syncValue : function()
29920     {
29921         this.editorcore.syncValue();
29922     },
29923     
29924     pushValue : function()
29925     {
29926         this.editorcore.pushValue();
29927     },
29928     
29929     setStylesheets : function(stylesheets)
29930     {
29931         this.editorcore.setStylesheets(stylesheets);
29932     },
29933     
29934     removeStylesheets : function()
29935     {
29936         this.editorcore.removeStylesheets();
29937     }
29938      
29939     
29940     // hide stuff that is not compatible
29941     /**
29942      * @event blur
29943      * @hide
29944      */
29945     /**
29946      * @event change
29947      * @hide
29948      */
29949     /**
29950      * @event focus
29951      * @hide
29952      */
29953     /**
29954      * @event specialkey
29955      * @hide
29956      */
29957     /**
29958      * @cfg {String} fieldClass @hide
29959      */
29960     /**
29961      * @cfg {String} focusClass @hide
29962      */
29963     /**
29964      * @cfg {String} autoCreate @hide
29965      */
29966     /**
29967      * @cfg {String} inputType @hide
29968      */
29969     /**
29970      * @cfg {String} invalidClass @hide
29971      */
29972     /**
29973      * @cfg {String} invalidText @hide
29974      */
29975     /**
29976      * @cfg {String} msgFx @hide
29977      */
29978     /**
29979      * @cfg {String} validateOnBlur @hide
29980      */
29981 });
29982  
29983     /*
29984  * Based on
29985  * Ext JS Library 1.1.1
29986  * Copyright(c) 2006-2007, Ext JS, LLC.
29987  *  
29988  
29989  */
29990
29991 /**
29992  * @class Roo.form.HtmlEditor.ToolbarStandard
29993  * Basic Toolbar
29994
29995  * Usage:
29996  *
29997  new Roo.form.HtmlEditor({
29998     ....
29999     toolbars : [
30000         new Roo.form.HtmlEditorToolbar1({
30001             disable : { fonts: 1 , format: 1, ..., ... , ...],
30002             btns : [ .... ]
30003         })
30004     }
30005      
30006  * 
30007  * @cfg {Object} disable List of elements to disable..
30008  * @cfg {Roo.Toolbar.Item|Roo.Toolbar.Button|Roo.Toolbar.SplitButton|Roo.form.Field} btns[] List of additional buttons.
30009  * 
30010  * 
30011  * NEEDS Extra CSS? 
30012  * .x-html-editor-tb .x-edit-none .x-btn-text { background: none; }
30013  */
30014  
30015 Roo.form.HtmlEditor.ToolbarStandard = function(config)
30016 {
30017     
30018     Roo.apply(this, config);
30019     
30020     // default disabled, based on 'good practice'..
30021     this.disable = this.disable || {};
30022     Roo.applyIf(this.disable, {
30023         fontSize : true,
30024         colors : true,
30025         specialElements : true
30026     });
30027     
30028     
30029     //Roo.form.HtmlEditorToolbar1.superclass.constructor.call(this, editor.wrap.dom.firstChild, [], config);
30030     // dont call parent... till later.
30031 }
30032
30033 Roo.form.HtmlEditor.ToolbarStandard.prototype = {
30034     
30035     tb: false,
30036     
30037     rendered: false,
30038     
30039     editor : false,
30040     editorcore : false,
30041     /**
30042      * @cfg {Object} disable  List of toolbar elements to disable
30043          
30044      */
30045     disable : false,
30046     
30047     
30048      /**
30049      * @cfg {String} createLinkText The default text for the create link prompt
30050      */
30051     createLinkText : 'Please enter the URL for the link:',
30052     /**
30053      * @cfg {String} defaultLinkValue The default value for the create link prompt (defaults to http:/ /)
30054      */
30055     defaultLinkValue : 'http:/'+'/',
30056    
30057     
30058       /**
30059      * @cfg {Array} fontFamilies An array of available font families
30060      */
30061     fontFamilies : [
30062         'Arial',
30063         'Courier New',
30064         'Tahoma',
30065         'Times New Roman',
30066         'Verdana'
30067     ],
30068     
30069     specialChars : [
30070            "&#169;",
30071           "&#174;",     
30072           "&#8482;",    
30073           "&#163;" ,    
30074          // "&#8212;",    
30075           "&#8230;",    
30076           "&#247;" ,    
30077         //  "&#225;" ,     ?? a acute?
30078            "&#8364;"    , //Euro
30079        //   "&#8220;"    ,
30080         //  "&#8221;"    ,
30081         //  "&#8226;"    ,
30082           "&#176;"  //   , // degrees
30083
30084          // "&#233;"     , // e ecute
30085          // "&#250;"     , // u ecute?
30086     ],
30087     
30088     specialElements : [
30089         {
30090             text: "Insert Table",
30091             xtype: 'MenuItem',
30092             xns : Roo.Menu,
30093             ihtml :  '<table><tr><td>Cell</td></tr></table>' 
30094                 
30095         },
30096         {    
30097             text: "Insert Image",
30098             xtype: 'MenuItem',
30099             xns : Roo.Menu,
30100             ihtml : '<img src="about:blank"/>'
30101             
30102         }
30103         
30104          
30105     ],
30106     
30107     
30108     inputElements : [ 
30109             "form", "input:text", "input:hidden", "input:checkbox", "input:radio", "input:password", 
30110             "input:submit", "input:button", "select", "textarea", "label" ],
30111     formats : [
30112         ["p"] ,  
30113         ["h1"],["h2"],["h3"],["h4"],["h5"],["h6"], 
30114         ["pre"],[ "code"], 
30115         ["abbr"],[ "acronym"],[ "address"],[ "cite"],[ "samp"],[ "var"],
30116         ['div'],['span'],
30117         ['sup'],['sub']
30118     ],
30119     
30120     cleanStyles : [
30121         "font-size"
30122     ],
30123      /**
30124      * @cfg {String} defaultFont default font to use.
30125      */
30126     defaultFont: 'tahoma',
30127    
30128     fontSelect : false,
30129     
30130     
30131     formatCombo : false,
30132     
30133     init : function(editor)
30134     {
30135         this.editor = editor;
30136         this.editorcore = editor.editorcore ? editor.editorcore : editor;
30137         var editorcore = this.editorcore;
30138         
30139         var _t = this;
30140         
30141         var fid = editorcore.frameId;
30142         var etb = this;
30143         function btn(id, toggle, handler){
30144             var xid = fid + '-'+ id ;
30145             return {
30146                 id : xid,
30147                 cmd : id,
30148                 cls : 'x-btn-icon x-edit-'+id,
30149                 enableToggle:toggle !== false,
30150                 scope: _t, // was editor...
30151                 handler:handler||_t.relayBtnCmd,
30152                 clickEvent:'mousedown',
30153                 tooltip: etb.buttonTips[id] || undefined, ///tips ???
30154                 tabIndex:-1
30155             };
30156         }
30157         
30158         
30159         
30160         var tb = new Roo.Toolbar(editor.wrap.dom.firstChild);
30161         this.tb = tb;
30162          // stop form submits
30163         tb.el.on('click', function(e){
30164             e.preventDefault(); // what does this do?
30165         });
30166
30167         if(!this.disable.font) { // && !Roo.isSafari){
30168             /* why no safari for fonts 
30169             editor.fontSelect = tb.el.createChild({
30170                 tag:'select',
30171                 tabIndex: -1,
30172                 cls:'x-font-select',
30173                 html: this.createFontOptions()
30174             });
30175             
30176             editor.fontSelect.on('change', function(){
30177                 var font = editor.fontSelect.dom.value;
30178                 editor.relayCmd('fontname', font);
30179                 editor.deferFocus();
30180             }, editor);
30181             
30182             tb.add(
30183                 editor.fontSelect.dom,
30184                 '-'
30185             );
30186             */
30187             
30188         };
30189         if(!this.disable.formats){
30190             this.formatCombo = new Roo.form.ComboBox({
30191                 store: new Roo.data.SimpleStore({
30192                     id : 'tag',
30193                     fields: ['tag'],
30194                     data : this.formats // from states.js
30195                 }),
30196                 blockFocus : true,
30197                 name : '',
30198                 //autoCreate : {tag: "div",  size: "20"},
30199                 displayField:'tag',
30200                 typeAhead: false,
30201                 mode: 'local',
30202                 editable : false,
30203                 triggerAction: 'all',
30204                 emptyText:'Add tag',
30205                 selectOnFocus:true,
30206                 width:135,
30207                 listeners : {
30208                     'select': function(c, r, i) {
30209                         editorcore.insertTag(r.get('tag'));
30210                         editor.focus();
30211                     }
30212                 }
30213
30214             });
30215             tb.addField(this.formatCombo);
30216             
30217         }
30218         
30219         if(!this.disable.format){
30220             tb.add(
30221                 btn('bold'),
30222                 btn('italic'),
30223                 btn('underline'),
30224                 btn('strikethrough')
30225             );
30226         };
30227         if(!this.disable.fontSize){
30228             tb.add(
30229                 '-',
30230                 
30231                 
30232                 btn('increasefontsize', false, editorcore.adjustFont),
30233                 btn('decreasefontsize', false, editorcore.adjustFont)
30234             );
30235         };
30236         
30237         
30238         if(!this.disable.colors){
30239             tb.add(
30240                 '-', {
30241                     id:editorcore.frameId +'-forecolor',
30242                     cls:'x-btn-icon x-edit-forecolor',
30243                     clickEvent:'mousedown',
30244                     tooltip: this.buttonTips['forecolor'] || undefined,
30245                     tabIndex:-1,
30246                     menu : new Roo.menu.ColorMenu({
30247                         allowReselect: true,
30248                         focus: Roo.emptyFn,
30249                         value:'000000',
30250                         plain:true,
30251                         selectHandler: function(cp, color){
30252                             editorcore.execCmd('forecolor', Roo.isSafari || Roo.isIE ? '#'+color : color);
30253                             editor.deferFocus();
30254                         },
30255                         scope: editorcore,
30256                         clickEvent:'mousedown'
30257                     })
30258                 }, {
30259                     id:editorcore.frameId +'backcolor',
30260                     cls:'x-btn-icon x-edit-backcolor',
30261                     clickEvent:'mousedown',
30262                     tooltip: this.buttonTips['backcolor'] || undefined,
30263                     tabIndex:-1,
30264                     menu : new Roo.menu.ColorMenu({
30265                         focus: Roo.emptyFn,
30266                         value:'FFFFFF',
30267                         plain:true,
30268                         allowReselect: true,
30269                         selectHandler: function(cp, color){
30270                             if(Roo.isGecko){
30271                                 editorcore.execCmd('useCSS', false);
30272                                 editorcore.execCmd('hilitecolor', color);
30273                                 editorcore.execCmd('useCSS', true);
30274                                 editor.deferFocus();
30275                             }else{
30276                                 editorcore.execCmd(Roo.isOpera ? 'hilitecolor' : 'backcolor', 
30277                                     Roo.isSafari || Roo.isIE ? '#'+color : color);
30278                                 editor.deferFocus();
30279                             }
30280                         },
30281                         scope:editorcore,
30282                         clickEvent:'mousedown'
30283                     })
30284                 }
30285             );
30286         };
30287         // now add all the items...
30288         
30289
30290         if(!this.disable.alignments){
30291             tb.add(
30292                 '-',
30293                 btn('justifyleft'),
30294                 btn('justifycenter'),
30295                 btn('justifyright')
30296             );
30297         };
30298
30299         //if(!Roo.isSafari){
30300             if(!this.disable.links){
30301                 tb.add(
30302                     '-',
30303                     btn('createlink', false, this.createLink)    /// MOVE TO HERE?!!?!?!?!
30304                 );
30305             };
30306
30307             if(!this.disable.lists){
30308                 tb.add(
30309                     '-',
30310                     btn('insertorderedlist'),
30311                     btn('insertunorderedlist')
30312                 );
30313             }
30314             if(!this.disable.sourceEdit){
30315                 tb.add(
30316                     '-',
30317                     btn('sourceedit', true, function(btn){
30318                         this.toggleSourceEdit(btn.pressed);
30319                     })
30320                 );
30321             }
30322         //}
30323         
30324         var smenu = { };
30325         // special menu.. - needs to be tidied up..
30326         if (!this.disable.special) {
30327             smenu = {
30328                 text: "&#169;",
30329                 cls: 'x-edit-none',
30330                 
30331                 menu : {
30332                     items : []
30333                 }
30334             };
30335             for (var i =0; i < this.specialChars.length; i++) {
30336                 smenu.menu.items.push({
30337                     
30338                     html: this.specialChars[i],
30339                     handler: function(a,b) {
30340                         editorcore.insertAtCursor(String.fromCharCode(a.html.replace('&#','').replace(';', '')));
30341                         //editor.insertAtCursor(a.html);
30342                         
30343                     },
30344                     tabIndex:-1
30345                 });
30346             }
30347             
30348             
30349             tb.add(smenu);
30350             
30351             
30352         }
30353         
30354         var cmenu = { };
30355         if (!this.disable.cleanStyles) {
30356             cmenu = {
30357                 cls: 'x-btn-icon x-btn-clear',
30358                 
30359                 menu : {
30360                     items : []
30361                 }
30362             };
30363             for (var i =0; i < this.cleanStyles.length; i++) {
30364                 cmenu.menu.items.push({
30365                     actiontype : this.cleanStyles[i],
30366                     html: 'Remove ' + this.cleanStyles[i],
30367                     handler: function(a,b) {
30368 //                        Roo.log(a);
30369 //                        Roo.log(b);
30370                         var c = Roo.get(editorcore.doc.body);
30371                         c.select('[style]').each(function(s) {
30372                             s.dom.style.removeProperty(a.actiontype);
30373                         });
30374                         editorcore.syncValue();
30375                     },
30376                     tabIndex:-1
30377                 });
30378             }
30379             cmenu.menu.items.push({
30380                 actiontype : 'tablewidths',
30381                 html: 'Remove Table Widths',
30382                 handler: function(a,b) {
30383                     editorcore.cleanTableWidths();
30384                     editorcore.syncValue();
30385                 },
30386                 tabIndex:-1
30387             });
30388             cmenu.menu.items.push({
30389                 actiontype : 'word',
30390                 html: 'Remove MS Word Formating',
30391                 handler: function(a,b) {
30392                     editorcore.cleanWord();
30393                     editorcore.syncValue();
30394                 },
30395                 tabIndex:-1
30396             });
30397             
30398             cmenu.menu.items.push({
30399                 actiontype : 'all',
30400                 html: 'Remove All Styles',
30401                 handler: function(a,b) {
30402                     
30403                     var c = Roo.get(editorcore.doc.body);
30404                     c.select('[style]').each(function(s) {
30405                         s.dom.removeAttribute('style');
30406                     });
30407                     editorcore.syncValue();
30408                 },
30409                 tabIndex:-1
30410             });
30411             
30412             cmenu.menu.items.push({
30413                 actiontype : 'all',
30414                 html: 'Remove All CSS Classes',
30415                 handler: function(a,b) {
30416                     
30417                     var c = Roo.get(editorcore.doc.body);
30418                     c.select('[class]').each(function(s) {
30419                         s.dom.removeAttribute('class');
30420                     });
30421                     editorcore.cleanWord();
30422                     editorcore.syncValue();
30423                 },
30424                 tabIndex:-1
30425             });
30426             
30427              cmenu.menu.items.push({
30428                 actiontype : 'tidy',
30429                 html: 'Tidy HTML Source',
30430                 handler: function(a,b) {
30431                     new Roo.htmleditor.Tidy(editorcore.doc.body);
30432                     editorcore.syncValue();
30433                 },
30434                 tabIndex:-1
30435             });
30436             
30437             
30438             tb.add(cmenu);
30439         }
30440          
30441         if (!this.disable.specialElements) {
30442             var semenu = {
30443                 text: "Other;",
30444                 cls: 'x-edit-none',
30445                 menu : {
30446                     items : []
30447                 }
30448             };
30449             for (var i =0; i < this.specialElements.length; i++) {
30450                 semenu.menu.items.push(
30451                     Roo.apply({ 
30452                         handler: function(a,b) {
30453                             editor.insertAtCursor(this.ihtml);
30454                         }
30455                     }, this.specialElements[i])
30456                 );
30457                     
30458             }
30459             
30460             tb.add(semenu);
30461             
30462             
30463         }
30464          
30465         
30466         if (this.btns) {
30467             for(var i =0; i< this.btns.length;i++) {
30468                 var b = Roo.factory(this.btns[i],this.btns[i].xns || Roo.form);
30469                 b.cls =  'x-edit-none';
30470                 
30471                 if(typeof(this.btns[i].cls) != 'undefined' && this.btns[i].cls.indexOf('x-init-enable') !== -1){
30472                     b.cls += ' x-init-enable';
30473                 }
30474                 
30475                 b.scope = editorcore;
30476                 tb.add(b);
30477             }
30478         
30479         }
30480         
30481         
30482         
30483         // disable everything...
30484         
30485         this.tb.items.each(function(item){
30486             
30487            if(
30488                 item.id != editorcore.frameId+ '-sourceedit' && 
30489                 (typeof(item.cls) != 'undefined' && item.cls.indexOf('x-init-enable') === -1)
30490             ){
30491                 
30492                 item.disable();
30493             }
30494         });
30495         this.rendered = true;
30496         
30497         // the all the btns;
30498         editor.on('editorevent', this.updateToolbar, this);
30499         // other toolbars need to implement this..
30500         //editor.on('editmodechange', this.updateToolbar, this);
30501     },
30502     
30503     
30504     relayBtnCmd : function(btn) {
30505         this.editorcore.relayCmd(btn.cmd);
30506     },
30507     // private used internally
30508     createLink : function(){
30509         //Roo.log("create link?");
30510         var ec = this.editorcore;
30511         var ar = ec.getAllAncestors();
30512         var n = false;
30513         for(var i = 0;i< ar.length;i++) {
30514             if (ar[i] && ar[i].nodeName == 'A') {
30515                 n = ar[i];
30516                 break;
30517             }
30518         }
30519         
30520         (function() {
30521             
30522             Roo.MessageBox.show({
30523                 title : "Add / Edit Link URL",
30524                 msg : "Enter the url for the link",
30525                 buttons: Roo.MessageBox.OKCANCEL,
30526                 fn: function(btn, url){
30527                     if (btn != 'ok') {
30528                         return;
30529                     }
30530                     if(url && url != 'http:/'+'/'){
30531                         if (n) {
30532                             n.setAttribute('href', url);
30533                         } else {
30534                             ec.relayCmd('createlink', url);
30535                         }
30536                     }
30537                 },
30538                 minWidth:250,
30539                 prompt:true,
30540                 //multiline: multiline,
30541                 modal : true,
30542                 value :  n  ? n.getAttribute('href') : '' 
30543             });
30544             
30545              
30546         }).defer(100, this); // we have to defer this , otherwise the mouse click gives focus to the main window.
30547         
30548     },
30549
30550     
30551     /**
30552      * Protected method that will not generally be called directly. It triggers
30553      * a toolbar update by reading the markup state of the current selection in the editor.
30554      */
30555     updateToolbar: function(){
30556
30557         if(!this.editorcore.activated){
30558             this.editor.onFirstFocus();
30559             return;
30560         }
30561
30562         var btns = this.tb.items.map, 
30563             doc = this.editorcore.doc,
30564             frameId = this.editorcore.frameId;
30565
30566         if(!this.disable.font && !Roo.isSafari){
30567             /*
30568             var name = (doc.queryCommandValue('FontName')||this.editor.defaultFont).toLowerCase();
30569             if(name != this.fontSelect.dom.value){
30570                 this.fontSelect.dom.value = name;
30571             }
30572             */
30573         }
30574         if(!this.disable.format){
30575             btns[frameId + '-bold'].toggle(doc.queryCommandState('bold'));
30576             btns[frameId + '-italic'].toggle(doc.queryCommandState('italic'));
30577             btns[frameId + '-underline'].toggle(doc.queryCommandState('underline'));
30578             btns[frameId + '-strikethrough'].toggle(doc.queryCommandState('strikethrough'));
30579         }
30580         if(!this.disable.alignments){
30581             btns[frameId + '-justifyleft'].toggle(doc.queryCommandState('justifyleft'));
30582             btns[frameId + '-justifycenter'].toggle(doc.queryCommandState('justifycenter'));
30583             btns[frameId + '-justifyright'].toggle(doc.queryCommandState('justifyright'));
30584         }
30585         if(!Roo.isSafari && !this.disable.lists){
30586             btns[frameId + '-insertorderedlist'].toggle(doc.queryCommandState('insertorderedlist'));
30587             btns[frameId + '-insertunorderedlist'].toggle(doc.queryCommandState('insertunorderedlist'));
30588         }
30589         
30590         var ans = this.editorcore.getAllAncestors();
30591         if (this.formatCombo) {
30592             
30593             
30594             var store = this.formatCombo.store;
30595             this.formatCombo.setValue("");
30596             for (var i =0; i < ans.length;i++) {
30597                 if (ans[i] && store.query('tag',ans[i].tagName.toLowerCase(), false).length) {
30598                     // select it..
30599                     this.formatCombo.setValue(ans[i].tagName.toLowerCase());
30600                     break;
30601                 }
30602             }
30603         }
30604         
30605         
30606         
30607         // hides menus... - so this cant be on a menu...
30608         Roo.menu.MenuMgr.hideAll();
30609
30610         //this.editorsyncValue();
30611     },
30612    
30613     
30614     createFontOptions : function(){
30615         var buf = [], fs = this.fontFamilies, ff, lc;
30616         
30617         
30618         
30619         for(var i = 0, len = fs.length; i< len; i++){
30620             ff = fs[i];
30621             lc = ff.toLowerCase();
30622             buf.push(
30623                 '<option value="',lc,'" style="font-family:',ff,';"',
30624                     (this.defaultFont == lc ? ' selected="true">' : '>'),
30625                     ff,
30626                 '</option>'
30627             );
30628         }
30629         return buf.join('');
30630     },
30631     
30632     toggleSourceEdit : function(sourceEditMode){
30633         
30634         Roo.log("toolbar toogle");
30635         if(sourceEditMode === undefined){
30636             sourceEditMode = !this.sourceEditMode;
30637         }
30638         this.sourceEditMode = sourceEditMode === true;
30639         var btn = this.tb.items.get(this.editorcore.frameId +'-sourceedit');
30640         // just toggle the button?
30641         if(btn.pressed !== this.sourceEditMode){
30642             btn.toggle(this.sourceEditMode);
30643             return;
30644         }
30645         
30646         if(sourceEditMode){
30647             Roo.log("disabling buttons");
30648             this.tb.items.each(function(item){
30649                 if(item.cmd != 'sourceedit' && (typeof(item.cls) != 'undefined' && item.cls.indexOf('x-init-enable') === -1)){
30650                     item.disable();
30651                 }
30652             });
30653           
30654         }else{
30655             Roo.log("enabling buttons");
30656             if(this.editorcore.initialized){
30657                 this.tb.items.each(function(item){
30658                     item.enable();
30659                 });
30660                 // initialize 'blocks'
30661                 Roo.each(Roo.get(this.editorcore.doc.body).query('*[data-block]'), function(e) {
30662                     Roo.htmleditor.Block.factory(e).updateElement(e);
30663                 },this);
30664             
30665             }
30666             
30667         }
30668         Roo.log("calling toggole on editor");
30669         // tell the editor that it's been pressed..
30670         this.editor.toggleSourceEdit(sourceEditMode);
30671        
30672     },
30673      /**
30674      * Object collection of toolbar tooltips for the buttons in the editor. The key
30675      * is the command id associated with that button and the value is a valid QuickTips object.
30676      * For example:
30677 <pre><code>
30678 {
30679     bold : {
30680         title: 'Bold (Ctrl+B)',
30681         text: 'Make the selected text bold.',
30682         cls: 'x-html-editor-tip'
30683     },
30684     italic : {
30685         title: 'Italic (Ctrl+I)',
30686         text: 'Make the selected text italic.',
30687         cls: 'x-html-editor-tip'
30688     },
30689     ...
30690 </code></pre>
30691     * @type Object
30692      */
30693     buttonTips : {
30694         bold : {
30695             title: 'Bold (Ctrl+B)',
30696             text: 'Make the selected text bold.',
30697             cls: 'x-html-editor-tip'
30698         },
30699         italic : {
30700             title: 'Italic (Ctrl+I)',
30701             text: 'Make the selected text italic.',
30702             cls: 'x-html-editor-tip'
30703         },
30704         underline : {
30705             title: 'Underline (Ctrl+U)',
30706             text: 'Underline the selected text.',
30707             cls: 'x-html-editor-tip'
30708         },
30709         strikethrough : {
30710             title: 'Strikethrough',
30711             text: 'Strikethrough the selected text.',
30712             cls: 'x-html-editor-tip'
30713         },
30714         increasefontsize : {
30715             title: 'Grow Text',
30716             text: 'Increase the font size.',
30717             cls: 'x-html-editor-tip'
30718         },
30719         decreasefontsize : {
30720             title: 'Shrink Text',
30721             text: 'Decrease the font size.',
30722             cls: 'x-html-editor-tip'
30723         },
30724         backcolor : {
30725             title: 'Text Highlight Color',
30726             text: 'Change the background color of the selected text.',
30727             cls: 'x-html-editor-tip'
30728         },
30729         forecolor : {
30730             title: 'Font Color',
30731             text: 'Change the color of the selected text.',
30732             cls: 'x-html-editor-tip'
30733         },
30734         justifyleft : {
30735             title: 'Align Text Left',
30736             text: 'Align text to the left.',
30737             cls: 'x-html-editor-tip'
30738         },
30739         justifycenter : {
30740             title: 'Center Text',
30741             text: 'Center text in the editor.',
30742             cls: 'x-html-editor-tip'
30743         },
30744         justifyright : {
30745             title: 'Align Text Right',
30746             text: 'Align text to the right.',
30747             cls: 'x-html-editor-tip'
30748         },
30749         insertunorderedlist : {
30750             title: 'Bullet List',
30751             text: 'Start a bulleted list.',
30752             cls: 'x-html-editor-tip'
30753         },
30754         insertorderedlist : {
30755             title: 'Numbered List',
30756             text: 'Start a numbered list.',
30757             cls: 'x-html-editor-tip'
30758         },
30759         createlink : {
30760             title: 'Hyperlink',
30761             text: 'Make the selected text a hyperlink.',
30762             cls: 'x-html-editor-tip'
30763         },
30764         sourceedit : {
30765             title: 'Source Edit',
30766             text: 'Switch to source editing mode.',
30767             cls: 'x-html-editor-tip'
30768         }
30769     },
30770     // private
30771     onDestroy : function(){
30772         if(this.rendered){
30773             
30774             this.tb.items.each(function(item){
30775                 if(item.menu){
30776                     item.menu.removeAll();
30777                     if(item.menu.el){
30778                         item.menu.el.destroy();
30779                     }
30780                 }
30781                 item.destroy();
30782             });
30783              
30784         }
30785     },
30786     onFirstFocus: function() {
30787         this.tb.items.each(function(item){
30788            item.enable();
30789         });
30790     }
30791 };
30792
30793
30794
30795
30796 // <script type="text/javascript">
30797 /*
30798  * Based on
30799  * Ext JS Library 1.1.1
30800  * Copyright(c) 2006-2007, Ext JS, LLC.
30801  *  
30802  
30803  */
30804
30805  
30806 /**
30807  * @class Roo.form.HtmlEditor.ToolbarContext
30808  * Context Toolbar
30809  * 
30810  * Usage:
30811  *
30812  new Roo.form.HtmlEditor({
30813     ....
30814     toolbars : [
30815         { xtype: 'ToolbarStandard', styles : {} }
30816         { xtype: 'ToolbarContext', disable : {} }
30817     ]
30818 })
30819
30820      
30821  * 
30822  * @config : {Object} disable List of elements to disable.. (not done yet.)
30823  * @config : {Object} styles  Map of styles available.
30824  * 
30825  */
30826
30827 Roo.form.HtmlEditor.ToolbarContext = function(config)
30828 {
30829     
30830     Roo.apply(this, config);
30831     //Roo.form.HtmlEditorToolbar1.superclass.constructor.call(this, editor.wrap.dom.firstChild, [], config);
30832     // dont call parent... till later.
30833     this.styles = this.styles || {};
30834 }
30835
30836  
30837
30838 Roo.form.HtmlEditor.ToolbarContext.types = {
30839     'IMG' : [
30840         {
30841             name : 'width',
30842             title: "Width",
30843             width: 40
30844         },
30845         {
30846             name : 'height',
30847             title: "Height",
30848             width: 40
30849         },
30850         {
30851             name : 'align',
30852             title: "Align",
30853             opts : [ [""],[ "left"],[ "right"],[ "center"],[ "top"]],
30854             width : 80
30855             
30856         },
30857         {
30858             name : 'border',
30859             title: "Border",
30860             width: 40
30861         },
30862         {
30863             name : 'alt',
30864             title: "Alt",
30865             width: 120
30866         },
30867         {
30868             name : 'src',
30869             title: "Src",
30870             width: 220
30871         }
30872         
30873     ],
30874     
30875     'FIGURE' : [
30876         {
30877             name : 'align',
30878             title: "Align",
30879             opts : [ [""],[ "left"],[ "right"],[ "center"],[ "top"]],
30880             width : 80  
30881         }
30882     ],
30883     'A' : [
30884         {
30885             name : 'name',
30886             title: "Name",
30887             width: 50
30888         },
30889         {
30890             name : 'target',
30891             title: "Target",
30892             width: 120
30893         },
30894         {
30895             name : 'href',
30896             title: "Href",
30897             width: 220
30898         } // border?
30899         
30900     ],
30901     
30902     'INPUT' : [
30903         {
30904             name : 'name',
30905             title: "name",
30906             width: 120
30907         },
30908         {
30909             name : 'value',
30910             title: "Value",
30911             width: 120
30912         },
30913         {
30914             name : 'width',
30915             title: "Width",
30916             width: 40
30917         }
30918     ],
30919     'LABEL' : [
30920          {
30921             name : 'for',
30922             title: "For",
30923             width: 120
30924         }
30925     ],
30926     'TEXTAREA' : [
30927         {
30928             name : 'name',
30929             title: "name",
30930             width: 120
30931         },
30932         {
30933             name : 'rows',
30934             title: "Rows",
30935             width: 20
30936         },
30937         {
30938             name : 'cols',
30939             title: "Cols",
30940             width: 20
30941         }
30942     ],
30943     'SELECT' : [
30944         {
30945             name : 'name',
30946             title: "name",
30947             width: 120
30948         },
30949         {
30950             name : 'selectoptions',
30951             title: "Options",
30952             width: 200
30953         }
30954     ],
30955     
30956     // should we really allow this??
30957     // should this just be 
30958     'BODY' : [
30959         
30960         {
30961             name : 'title',
30962             title: "Title",
30963             width: 200,
30964             disabled : true
30965         }
30966     ],
30967  
30968     '*' : [
30969         // empty.
30970     ]
30971
30972 };
30973
30974 // this should be configurable.. - you can either set it up using stores, or modify options somehwere..
30975 Roo.form.HtmlEditor.ToolbarContext.stores = false;
30976
30977 Roo.form.HtmlEditor.ToolbarContext.options = {
30978         'font-family'  : [ 
30979                 [ 'Helvetica,Arial,sans-serif', 'Helvetica'],
30980                 [ 'Courier New', 'Courier New'],
30981                 [ 'Tahoma', 'Tahoma'],
30982                 [ 'Times New Roman,serif', 'Times'],
30983                 [ 'Verdana','Verdana' ]
30984         ]
30985 };
30986
30987 // fixme - these need to be configurable..
30988  
30989
30990 //Roo.form.HtmlEditor.ToolbarContext.types
30991
30992
30993 Roo.apply(Roo.form.HtmlEditor.ToolbarContext.prototype,  {
30994     
30995     tb: false,
30996     
30997     rendered: false,
30998     
30999     editor : false,
31000     editorcore : false,
31001     /**
31002      * @cfg {Object} disable  List of toolbar elements to disable
31003          
31004      */
31005     disable : false,
31006     /**
31007      * @cfg {Object} styles List of styles 
31008      *    eg. { '*' : [ 'headline' ] , 'TD' : [ 'underline', 'double-underline' ] } 
31009      *
31010      * These must be defined in the page, so they get rendered correctly..
31011      * .headline { }
31012      * TD.underline { }
31013      * 
31014      */
31015     styles : false,
31016     
31017     options: false,
31018     
31019     toolbars : false,
31020     
31021     init : function(editor)
31022     {
31023         this.editor = editor;
31024         this.editorcore = editor.editorcore ? editor.editorcore : editor;
31025         var editorcore = this.editorcore;
31026         
31027         var fid = editorcore.frameId;
31028         var etb = this;
31029         function btn(id, toggle, handler){
31030             var xid = fid + '-'+ id ;
31031             return {
31032                 id : xid,
31033                 cmd : id,
31034                 cls : 'x-btn-icon x-edit-'+id,
31035                 enableToggle:toggle !== false,
31036                 scope: editorcore, // was editor...
31037                 handler:handler||editorcore.relayBtnCmd,
31038                 clickEvent:'mousedown',
31039                 tooltip: etb.buttonTips[id] || undefined, ///tips ???
31040                 tabIndex:-1
31041             };
31042         }
31043         // create a new element.
31044         var wdiv = editor.wrap.createChild({
31045                 tag: 'div'
31046             }, editor.wrap.dom.firstChild.nextSibling, true);
31047         
31048         // can we do this more than once??
31049         
31050          // stop form submits
31051       
31052  
31053         // disable everything...
31054         var ty= Roo.form.HtmlEditor.ToolbarContext.types;
31055         this.toolbars = {};
31056         // block toolbars are built in updateToolbar when needed.
31057         for (var i in  ty) {
31058             
31059             this.toolbars[i] = this.buildToolbar(ty[i],i);
31060         }
31061         this.tb = this.toolbars.BODY;
31062         this.tb.el.show();
31063         this.buildFooter();
31064         this.footer.show();
31065         editor.on('hide', function( ) { this.footer.hide() }, this);
31066         editor.on('show', function( ) { this.footer.show() }, this);
31067         
31068          
31069         this.rendered = true;
31070         
31071         // the all the btns;
31072         editor.on('editorevent', this.updateToolbar, this);
31073         // other toolbars need to implement this..
31074         //editor.on('editmodechange', this.updateToolbar, this);
31075     },
31076     
31077     
31078     
31079     /**
31080      * Protected method that will not generally be called directly. It triggers
31081      * a toolbar update by reading the markup state of the current selection in the editor.
31082      *
31083      * Note you can force an update by calling on('editorevent', scope, false)
31084      */
31085     updateToolbar: function(editor ,ev, sel)
31086     {
31087         
31088         if (ev) {
31089             ev.stopEvent(); // se if we can stop this looping with mutiple events.
31090         }
31091         
31092         //Roo.log(ev);
31093         // capture mouse up - this is handy for selecting images..
31094         // perhaps should go somewhere else...
31095         if(!this.editorcore.activated){
31096              this.editor.onFirstFocus();
31097             return;
31098         }
31099         //Roo.log(ev ? ev.target : 'NOTARGET');
31100         
31101         
31102         // http://developer.yahoo.com/yui/docs/simple-editor.js.html
31103         // selectNode - might want to handle IE?
31104         
31105         
31106         
31107         if (ev &&
31108             (ev.type == 'mouseup' || ev.type == 'click' ) &&
31109             ev.target && ev.target.tagName != 'BODY' ) { // && ev.target.tagName == 'IMG') {
31110             // they have click on an image...
31111             // let's see if we can change the selection...
31112             sel = ev.target;
31113             
31114             // this triggers looping?
31115             //this.editorcore.selectNode(sel);
31116              
31117         }
31118         
31119         // this forces an id..
31120         Array.from(this.editorcore.doc.body.querySelectorAll('.roo-ed-selection')).forEach(function(e) {
31121              e.classList.remove('roo-ed-selection');
31122         });
31123         //Roo.select('.roo-ed-selection', false, this.editorcore.doc).removeClass('roo-ed-selection');
31124         //Roo.get(node).addClass('roo-ed-selection');
31125       
31126         //var updateFooter = sel ? false : true; 
31127         
31128         
31129         var ans = this.editorcore.getAllAncestors();
31130         
31131         // pick
31132         var ty = Roo.form.HtmlEditor.ToolbarContext.types;
31133         
31134         if (!sel) { 
31135             sel = ans.length ? (ans[0] ?  ans[0]  : ans[1]) : this.editorcore.doc.body;
31136             sel = sel ? sel : this.editorcore.doc.body;
31137             sel = sel.tagName.length ? sel : this.editorcore.doc.body;
31138             
31139         }
31140         
31141         var tn = sel.tagName.toUpperCase();
31142         var lastSel = this.tb.selectedNode;
31143         this.tb.selectedNode = sel;
31144         var left_label = tn;
31145         
31146         // ok see if we are editing a block?
31147         
31148         var db = false;
31149         // you are not actually selecting the block.
31150         if (sel && sel.hasAttribute('data-block')) {
31151             db = sel;
31152         } else if (sel && sel.closest('[data-block]')) {
31153             
31154             db = sel.closest('[data-block]');
31155             //var cepar = sel.closest('[contenteditable=true]');
31156             //if (db && cepar && cepar.tagName != 'BODY') {
31157             //   db = false; // we are inside an editable block.. = not sure how we are going to handle nested blocks!?
31158             //}   
31159         }
31160         
31161         
31162         var block = false;
31163         //if (db && !sel.hasAttribute('contenteditable') && sel.getAttribute('contenteditable') != 'true' ) {
31164         if (db && this.editorcore.enableBlocks) {
31165             block = Roo.htmleditor.Block.factory(db);
31166             
31167             
31168             if (block) {
31169                  db.className = (
31170                         db.classList.length > 0  ? db.className + ' ' : ''
31171                     )  + 'roo-ed-selection';
31172                  
31173                  // since we removed it earlier... its not there..
31174                 tn = 'BLOCK.' + db.getAttribute('data-block');
31175                 
31176                 //this.editorcore.selectNode(db);
31177                 if (typeof(this.toolbars[tn]) == 'undefined') {
31178                    this.toolbars[tn] = this.buildToolbar( false  ,tn ,block.friendly_name, block);
31179                 }
31180                 this.toolbars[tn].selectedNode = db;
31181                 left_label = block.friendly_name;
31182                 ans = this.editorcore.getAllAncestors();
31183             }
31184             
31185                 
31186             
31187         }
31188         
31189         
31190         if (this.tb.name == tn && lastSel == this.tb.selectedNode && ev !== false) {
31191             return; // no change?
31192         }
31193         
31194         
31195           
31196         this.tb.el.hide();
31197         ///console.log("show: " + tn);
31198         this.tb =  typeof(this.toolbars[tn]) != 'undefined' ? this.toolbars[tn] : this.toolbars['*'];
31199         
31200         this.tb.el.show();
31201         // update name
31202         this.tb.items.first().el.innerHTML = left_label + ':&nbsp;';
31203         
31204         
31205         // update attributes
31206         if (block && this.tb.fields) {
31207              
31208             this.tb.fields.each(function(e) {
31209                 e.setValue(block[e.name]);
31210             });
31211             
31212             
31213         } else  if (this.tb.fields && this.tb.selectedNode) {
31214             this.tb.fields.each( function(e) {
31215                 if (e.stylename) {
31216                     e.setValue(this.tb.selectedNode.style[e.stylename]);
31217                     return;
31218                 } 
31219                 e.setValue(this.tb.selectedNode.getAttribute(e.attrname));
31220             }, this);
31221             this.updateToolbarStyles(this.tb.selectedNode);  
31222         }
31223         
31224         
31225        
31226         Roo.menu.MenuMgr.hideAll();
31227
31228         
31229         
31230     
31231         // update the footer
31232         //
31233         this.updateFooter(ans);
31234              
31235     },
31236     
31237     updateToolbarStyles : function(sel)
31238     {
31239         var hasStyles = false;
31240         for(var i in this.styles) {
31241             hasStyles = true;
31242             break;
31243         }
31244         
31245         // update styles
31246         if (hasStyles && this.tb.hasStyles) { 
31247             var st = this.tb.fields.item(0);
31248             
31249             st.store.removeAll();
31250             var cn = sel.className.split(/\s+/);
31251             
31252             var avs = [];
31253             if (this.styles['*']) {
31254                 
31255                 Roo.each(this.styles['*'], function(v) {
31256                     avs.push( [ v , cn.indexOf(v) > -1 ? 1 : 0 ] );         
31257                 });
31258             }
31259             if (this.styles[tn]) { 
31260                 Roo.each(this.styles[tn], function(v) {
31261                     avs.push( [ v , cn.indexOf(v) > -1 ? 1 : 0 ] );         
31262                 });
31263             }
31264             
31265             st.store.loadData(avs);
31266             st.collapse();
31267             st.setValue(cn);
31268         }
31269     },
31270     
31271      
31272     updateFooter : function(ans)
31273     {
31274         var html = '';
31275         if (ans === false) {
31276             this.footDisp.dom.innerHTML = '';
31277             return;
31278         }
31279         
31280         this.footerEls = ans.reverse();
31281         Roo.each(this.footerEls, function(a,i) {
31282             if (!a) { return; }
31283             html += html.length ? ' &gt; '  :  '';
31284             
31285             html += '<span class="x-ed-loc-' + i + '">' + a.tagName + '</span>';
31286             
31287         });
31288        
31289         // 
31290         var sz = this.footDisp.up('td').getSize();
31291         this.footDisp.dom.style.width = (sz.width -10) + 'px';
31292         this.footDisp.dom.style.marginLeft = '5px';
31293         
31294         this.footDisp.dom.style.overflow = 'hidden';
31295         
31296         this.footDisp.dom.innerHTML = html;
31297             
31298         
31299     },
31300    
31301        
31302     // private
31303     onDestroy : function(){
31304         if(this.rendered){
31305             
31306             this.tb.items.each(function(item){
31307                 if(item.menu){
31308                     item.menu.removeAll();
31309                     if(item.menu.el){
31310                         item.menu.el.destroy();
31311                     }
31312                 }
31313                 item.destroy();
31314             });
31315              
31316         }
31317     },
31318     onFirstFocus: function() {
31319         // need to do this for all the toolbars..
31320         this.tb.items.each(function(item){
31321            item.enable();
31322         });
31323     },
31324     buildToolbar: function(tlist, nm, friendly_name, block)
31325     {
31326         var editor = this.editor;
31327         var editorcore = this.editorcore;
31328          // create a new element.
31329         var wdiv = editor.wrap.createChild({
31330                 tag: 'div'
31331             }, editor.wrap.dom.firstChild.nextSibling, true);
31332         
31333        
31334         var tb = new Roo.Toolbar(wdiv);
31335         ///this.tb = tb; // << this sets the active toolbar..
31336         if (tlist === false && block) {
31337             tlist = block.contextMenu(this);
31338         }
31339         
31340         tb.hasStyles = false;
31341         tb.name = nm;
31342         
31343         tb.add((typeof(friendly_name) == 'undefined' ? nm : friendly_name) + ":&nbsp;");
31344         
31345         var styles = Array.from(this.styles);
31346         
31347         
31348         // styles...
31349         if (styles && styles.length) {
31350             tb.hasStyles = true;
31351             // this needs a multi-select checkbox...
31352             tb.addField( new Roo.form.ComboBox({
31353                 store: new Roo.data.SimpleStore({
31354                     id : 'val',
31355                     fields: ['val', 'selected'],
31356                     data : [] 
31357                 }),
31358                 name : '-roo-edit-className',
31359                 attrname : 'className',
31360                 displayField: 'val',
31361                 typeAhead: false,
31362                 mode: 'local',
31363                 editable : false,
31364                 triggerAction: 'all',
31365                 emptyText:'Select Style',
31366                 selectOnFocus:true,
31367                 width: 130,
31368                 listeners : {
31369                     'select': function(c, r, i) {
31370                         // initial support only for on class per el..
31371                         tb.selectedNode.className =  r ? r.get('val') : '';
31372                         editorcore.syncValue();
31373                     }
31374                 }
31375     
31376             }));
31377         }
31378         
31379         var tbc = Roo.form.HtmlEditor.ToolbarContext;
31380         
31381         
31382         for (var i = 0; i < tlist.length; i++) {
31383             
31384             // newer versions will use xtype cfg to create menus.
31385             if (typeof(tlist[i].xtype) != 'undefined') {
31386                 
31387                 tb[typeof(tlist[i].name)== 'undefined' ? 'add' : 'addField'](Roo.factory(tlist[i]));
31388                 
31389                 
31390                 continue;
31391             }
31392             
31393             var item = tlist[i];
31394             tb.add(item.title + ":&nbsp;");
31395             
31396             
31397             //optname == used so you can configure the options available..
31398             var opts = item.opts ? item.opts : false;
31399             if (item.optname) { // use the b
31400                 opts = Roo.form.HtmlEditor.ToolbarContext.options[item.optname];
31401            
31402             }
31403             
31404             if (opts) {
31405                 // opts == pulldown..
31406                 tb.addField( new Roo.form.ComboBox({
31407                     store:   typeof(tbc.stores[i]) != 'undefined' ?  Roo.factory(tbc.stores[i],Roo.data) : new Roo.data.SimpleStore({
31408                         id : 'val',
31409                         fields: ['val', 'display'],
31410                         data : opts  
31411                     }),
31412                     name : '-roo-edit-' + tlist[i].name,
31413                     
31414                     attrname : tlist[i].name,
31415                     stylename : item.style ? item.style : false,
31416                     
31417                     displayField: item.displayField ? item.displayField : 'val',
31418                     valueField :  'val',
31419                     typeAhead: false,
31420                     mode: typeof(tbc.stores[tlist[i].name]) != 'undefined'  ? 'remote' : 'local',
31421                     editable : false,
31422                     triggerAction: 'all',
31423                     emptyText:'Select',
31424                     selectOnFocus:true,
31425                     width: item.width ? item.width  : 130,
31426                     listeners : {
31427                         'select': function(c, r, i) {
31428                              
31429                             
31430                             if (c.stylename) {
31431                                 tb.selectedNode.style[c.stylename] =  r.get('val');
31432                                 editorcore.syncValue();
31433                                 return;
31434                             }
31435                             if (r === false) {
31436                                 tb.selectedNode.removeAttribute(c.attrname);
31437                                 editorcore.syncValue();
31438                                 return;
31439                             }
31440                             tb.selectedNode.setAttribute(c.attrname, r.get('val'));
31441                             editorcore.syncValue();
31442                         }
31443                     }
31444
31445                 }));
31446                 continue;
31447                     
31448                  
31449                 /*
31450                 tb.addField( new Roo.form.TextField({
31451                     name: i,
31452                     width: 100,
31453                     //allowBlank:false,
31454                     value: ''
31455                 }));
31456                 continue;
31457                 */
31458             }
31459             tb.addField( new Roo.form.TextField({
31460                 name: '-roo-edit-' + tlist[i].name,
31461                 attrname : tlist[i].name,
31462                 
31463                 width: item.width,
31464                 //allowBlank:true,
31465                 value: '',
31466                 listeners: {
31467                     'change' : function(f, nv, ov) {
31468                         
31469                          
31470                         tb.selectedNode.setAttribute(f.attrname, nv);
31471                         editorcore.syncValue();
31472                     }
31473                 }
31474             }));
31475              
31476         }
31477         
31478         var _this = this;
31479         var show_delete = !block || block.deleteTitle !== false;
31480         if(nm == 'BODY'){
31481             show_delete = false;
31482             tb.addSeparator();
31483         
31484             tb.addButton( {
31485                 text: 'Stylesheets',
31486
31487                 listeners : {
31488                     click : function ()
31489                     {
31490                         _this.editor.fireEvent('stylesheetsclick', _this.editor);
31491                     }
31492                 }
31493             });
31494         }
31495         
31496         tb.addFill();
31497         if (show_delete) {
31498             tb.addButton({
31499                 text: block && block.deleteTitle ? block.deleteTitle  : 'Remove Block or Formating', // remove the tag, and puts the children outside...
31500         
31501                 listeners : {
31502                     click : function ()
31503                     {
31504                         var sn = tb.selectedNode;
31505                         if (block) {
31506                             sn = Roo.htmleditor.Block.factory(tb.selectedNode).removeNode();
31507                             
31508                         }
31509                         if (!sn) {
31510                             return;
31511                         }
31512                         var stn =  sn.childNodes[0] || sn.nextSibling || sn.previousSibling || sn.parentNode;
31513                         if (sn.hasAttribute('data-block')) {
31514                             stn =  sn.nextSibling || sn.previousSibling || sn.parentNode;
31515                             sn.parentNode.removeChild(sn);
31516                             
31517                         } else if (sn && sn.tagName != 'BODY') {
31518                             // remove and keep parents.
31519                             a = new Roo.htmleditor.FilterKeepChildren({tag : false});
31520                             a.replaceTag(sn);
31521                         }
31522                         
31523                         
31524                         var range = editorcore.createRange();
31525             
31526                         range.setStart(stn,0);
31527                         range.setEnd(stn,0); 
31528                         var selection = editorcore.getSelection();
31529                         selection.removeAllRanges();
31530                         selection.addRange(range);
31531                         
31532                         
31533                         //_this.updateToolbar(null, null, pn);
31534                         _this.updateToolbar(null, null, null);
31535                         _this.updateFooter(false);
31536                         
31537                     }
31538                 }
31539                 
31540                         
31541                     
31542                 
31543             });
31544         }    
31545         
31546         tb.el.on('click', function(e){
31547             e.preventDefault(); // what does this do?
31548         });
31549         tb.el.setVisibilityMode( Roo.Element.DISPLAY);
31550         tb.el.hide();
31551         
31552         // dont need to disable them... as they will get hidden
31553         return tb;
31554          
31555         
31556     },
31557     buildFooter : function()
31558     {
31559         
31560         var fel = this.editor.wrap.createChild();
31561         this.footer = new Roo.Toolbar(fel);
31562         // toolbar has scrolly on left / right?
31563         var footDisp= new Roo.Toolbar.Fill();
31564         var _t = this;
31565         this.footer.add(
31566             {
31567                 text : '&lt;',
31568                 xtype: 'Button',
31569                 handler : function() {
31570                     _t.footDisp.scrollTo('left',0,true)
31571                 }
31572             }
31573         );
31574         this.footer.add( footDisp );
31575         this.footer.add( 
31576             {
31577                 text : '&gt;',
31578                 xtype: 'Button',
31579                 handler : function() {
31580                     // no animation..
31581                     _t.footDisp.select('span').last().scrollIntoView(_t.footDisp,true);
31582                 }
31583             }
31584         );
31585         var fel = Roo.get(footDisp.el);
31586         fel.addClass('x-editor-context');
31587         this.footDispWrap = fel; 
31588         this.footDispWrap.overflow  = 'hidden';
31589         
31590         this.footDisp = fel.createChild();
31591         this.footDispWrap.on('click', this.onContextClick, this)
31592         
31593         
31594     },
31595     // when the footer contect changes
31596     onContextClick : function (ev,dom)
31597     {
31598         ev.preventDefault();
31599         var  cn = dom.className;
31600         //Roo.log(cn);
31601         if (!cn.match(/x-ed-loc-/)) {
31602             return;
31603         }
31604         var n = cn.split('-').pop();
31605         var ans = this.footerEls;
31606         var sel = ans[n];
31607         
31608         this.editorcore.selectNode(sel);
31609         
31610         
31611         this.updateToolbar(null, null, sel);
31612         
31613         
31614     }
31615     
31616     
31617     
31618     
31619     
31620 });
31621
31622
31623
31624
31625
31626 /*
31627  * Based on:
31628  * Ext JS Library 1.1.1
31629  * Copyright(c) 2006-2007, Ext JS, LLC.
31630  *
31631  * Originally Released Under LGPL - original licence link has changed is not relivant.
31632  *
31633  * Fork - LGPL
31634  * <script type="text/javascript">
31635  */
31636  
31637 /**
31638  * @class Roo.form.BasicForm
31639  * @extends Roo.util.Observable
31640  * Supplies the functionality to do "actions" on forms and initialize Roo.form.Field types on existing markup.
31641  * @constructor
31642  * @param {String/HTMLElement/Roo.Element} el The form element or its id
31643  * @param {Object} config Configuration options
31644  */
31645 Roo.form.BasicForm = function(el, config){
31646     this.allItems = [];
31647     this.childForms = [];
31648     Roo.apply(this, config);
31649     /*
31650      * The Roo.form.Field items in this form.
31651      * @type MixedCollection
31652      */
31653      
31654      
31655     this.items = new Roo.util.MixedCollection(false, function(o){
31656         return o.id || (o.id = Roo.id());
31657     });
31658     this.addEvents({
31659         /**
31660          * @event beforeaction
31661          * Fires before any action is performed. Return false to cancel the action.
31662          * @param {Form} this
31663          * @param {Action} action The action to be performed
31664          */
31665         beforeaction: true,
31666         /**
31667          * @event actionfailed
31668          * Fires when an action fails.
31669          * @param {Form} this
31670          * @param {Action} action The action that failed
31671          */
31672         actionfailed : true,
31673         /**
31674          * @event actioncomplete
31675          * Fires when an action is completed.
31676          * @param {Form} this
31677          * @param {Action} action The action that completed
31678          */
31679         actioncomplete : true
31680     });
31681     if(el){
31682         this.initEl(el);
31683     }
31684     Roo.form.BasicForm.superclass.constructor.call(this);
31685     
31686     Roo.form.BasicForm.popover.apply();
31687 };
31688
31689 Roo.extend(Roo.form.BasicForm, Roo.util.Observable, {
31690     /**
31691      * @cfg {String} method
31692      * The request method to use (GET or POST) for form actions if one isn't supplied in the action options.
31693      */
31694     /**
31695      * @cfg {DataReader} reader
31696      * An Roo.data.DataReader (e.g. {@link Roo.data.XmlReader}) to be used to read data when executing "load" actions.
31697      * This is optional as there is built-in support for processing JSON.
31698      */
31699     /**
31700      * @cfg {DataReader} errorReader
31701      * An Roo.data.DataReader (e.g. {@link Roo.data.XmlReader}) to be used to read data when reading validation errors on "submit" actions.
31702      * This is completely optional as there is built-in support for processing JSON.
31703      */
31704     /**
31705      * @cfg {String} url
31706      * The URL to use for form actions if one isn't supplied in the action options.
31707      */
31708     /**
31709      * @cfg {Boolean} fileUpload
31710      * Set to true if this form is a file upload.
31711      */
31712      
31713     /**
31714      * @cfg {Object} baseParams
31715      * Parameters to pass with all requests. e.g. baseParams: {id: '123', foo: 'bar'}.
31716      */
31717      /**
31718      
31719     /**
31720      * @cfg {Number} timeout Timeout for form actions in seconds (default is 30 seconds).
31721      */
31722     timeout: 30,
31723
31724     // private
31725     activeAction : null,
31726
31727     /**
31728      * @cfg {Boolean} trackResetOnLoad If set to true, form.reset() resets to the last loaded
31729      * or setValues() data instead of when the form was first created.
31730      */
31731     trackResetOnLoad : false,
31732     
31733     
31734     /**
31735      * childForms - used for multi-tab forms
31736      * @type {Array}
31737      */
31738     childForms : false,
31739     
31740     /**
31741      * allItems - full list of fields.
31742      * @type {Array}
31743      */
31744     allItems : false,
31745     
31746     /**
31747      * By default wait messages are displayed with Roo.MessageBox.wait. You can target a specific
31748      * element by passing it or its id or mask the form itself by passing in true.
31749      * @type Mixed
31750      */
31751     waitMsgTarget : false,
31752     
31753     /**
31754      * @type Boolean
31755      */
31756     disableMask : false,
31757     
31758     /**
31759      * @cfg {Boolean} errorMask Should the form be masked (and the active element highlighted on error - default false
31760      */
31761     errorMask : false,
31762     
31763     /**
31764      * @cfg {Number} maskOffset space around form element to mask if there is an error Default 100
31765      */
31766     maskOffset : 100,
31767
31768     // private
31769     initEl : function(el){
31770         this.el = Roo.get(el);
31771         this.id = this.el.id || Roo.id();
31772         this.el.on('submit', this.onSubmit, this);
31773         this.el.addClass('x-form');
31774     },
31775
31776     // private
31777     onSubmit : function(e){
31778         e.stopEvent();
31779     },
31780
31781     /**
31782      * Returns true if client-side validation on the form is successful.
31783      * @return Boolean
31784      */
31785     isValid : function(){
31786         var valid = true;
31787         var target = false;
31788         this.items.each(function(f){
31789             if(f.validate()){
31790                 return;
31791             }
31792             
31793             valid = false;
31794                 
31795             if(!target && f.el.isVisible(true)){
31796                 target = f;
31797             }
31798         });
31799         
31800         if(this.errorMask && !valid){
31801             Roo.form.BasicForm.popover.mask(this, target);
31802         }
31803         
31804         return valid;
31805     },
31806     /**
31807      * Returns array of invalid form fields.
31808      * @return Array
31809      */
31810     
31811     invalidFields : function()
31812     {
31813         var ret = [];
31814         this.items.each(function(f){
31815             if(f.validate()){
31816                 return;
31817             }
31818             ret.push(f);
31819             
31820         });
31821         
31822         return ret;
31823     },
31824     
31825     
31826     /**
31827      * DEPRICATED Returns true if any fields in this form have changed since their original load. 
31828      * @return Boolean
31829      */
31830     isDirty : function(){
31831         var dirty = false;
31832         this.items.each(function(f){
31833            if(f.isDirty()){
31834                dirty = true;
31835                return false;
31836            }
31837         });
31838         return dirty;
31839     },
31840     
31841     /**
31842      * Returns true if any fields in this form have changed since their original load. (New version)
31843      * @return Boolean
31844      */
31845     
31846     hasChanged : function()
31847     {
31848         var dirty = false;
31849         this.items.each(function(f){
31850            if(f.hasChanged()){
31851                dirty = true;
31852                return false;
31853            }
31854         });
31855         return dirty;
31856         
31857     },
31858     /**
31859      * Resets all hasChanged to 'false' -
31860      * The old 'isDirty' used 'original value..' however this breaks reset() and a few other things.
31861      * So hasChanged storage is only to be used for this purpose
31862      * @return Boolean
31863      */
31864     resetHasChanged : function()
31865     {
31866         this.items.each(function(f){
31867            f.resetHasChanged();
31868         });
31869         
31870     },
31871     
31872     
31873     /**
31874      * Performs a predefined action (submit or load) or custom actions you define on this form.
31875      * @param {String} actionName The name of the action type
31876      * @param {Object} options (optional) The options to pass to the action.  All of the config options listed
31877      * below are supported by both the submit and load actions unless otherwise noted (custom actions could also
31878      * accept other config options):
31879      * <pre>
31880 Property          Type             Description
31881 ----------------  ---------------  ----------------------------------------------------------------------------------
31882 url               String           The url for the action (defaults to the form's url)
31883 method            String           The form method to use (defaults to the form's method, or POST if not defined)
31884 params            String/Object    The params to pass (defaults to the form's baseParams, or none if not defined)
31885 clientValidation  Boolean          Applies to submit only.  Pass true to call form.isValid() prior to posting to
31886                                    validate the form on the client (defaults to false)
31887      * </pre>
31888      * @return {BasicForm} this
31889      */
31890     doAction : function(action, options){
31891         if(typeof action == 'string'){
31892             action = new Roo.form.Action.ACTION_TYPES[action](this, options);
31893         }
31894         if(this.fireEvent('beforeaction', this, action) !== false){
31895             this.beforeAction(action);
31896             action.run.defer(100, action);
31897         }
31898         return this;
31899     },
31900
31901     /**
31902      * Shortcut to do a submit action.
31903      * @param {Object} options The options to pass to the action (see {@link #doAction} for details)
31904      * @return {BasicForm} this
31905      */
31906     submit : function(options){
31907         this.doAction('submit', options);
31908         return this;
31909     },
31910
31911     /**
31912      * Shortcut to do a load action.
31913      * @param {Object} options The options to pass to the action (see {@link #doAction} for details)
31914      * @return {BasicForm} this
31915      */
31916     load : function(options){
31917         this.doAction('load', options);
31918         return this;
31919     },
31920
31921     /**
31922      * Persists the values in this form into the passed Roo.data.Record object in a beginEdit/endEdit block.
31923      * @param {Record} record The record to edit
31924      * @return {BasicForm} this
31925      */
31926     updateRecord : function(record){
31927         record.beginEdit();
31928         var fs = record.fields;
31929         fs.each(function(f){
31930             var field = this.findField(f.name);
31931             if(field){
31932                 record.set(f.name, field.getValue());
31933             }
31934         }, this);
31935         record.endEdit();
31936         return this;
31937     },
31938
31939     /**
31940      * Loads an Roo.data.Record into this form.
31941      * @param {Record} record The record to load
31942      * @return {BasicForm} this
31943      */
31944     loadRecord : function(record){
31945         this.setValues(record.data);
31946         return this;
31947     },
31948
31949     // private
31950     beforeAction : function(action){
31951         var o = action.options;
31952         
31953         if(!this.disableMask) {
31954             if(this.waitMsgTarget === true){
31955                 this.el.mask(o.waitMsg || "Sending", 'x-mask-loading');
31956             }else if(this.waitMsgTarget){
31957                 this.waitMsgTarget = Roo.get(this.waitMsgTarget);
31958                 this.waitMsgTarget.mask(o.waitMsg || "Sending", 'x-mask-loading');
31959             }else {
31960                 Roo.MessageBox.wait(o.waitMsg || "Sending", o.waitTitle || this.waitTitle || 'Please Wait...');
31961             }
31962         }
31963         
31964          
31965     },
31966
31967     // private
31968     afterAction : function(action, success){
31969         this.activeAction = null;
31970         var o = action.options;
31971         
31972         if(!this.disableMask) {
31973             if(this.waitMsgTarget === true){
31974                 this.el.unmask();
31975             }else if(this.waitMsgTarget){
31976                 this.waitMsgTarget.unmask();
31977             }else{
31978                 Roo.MessageBox.updateProgress(1);
31979                 Roo.MessageBox.hide();
31980             }
31981         }
31982         
31983         if(success){
31984             if(o.reset){
31985                 this.reset();
31986             }
31987             Roo.callback(o.success, o.scope, [this, action]);
31988             this.fireEvent('actioncomplete', this, action);
31989             
31990         }else{
31991             
31992             // failure condition..
31993             // we have a scenario where updates need confirming.
31994             // eg. if a locking scenario exists..
31995             // we look for { errors : { needs_confirm : true }} in the response.
31996             if (
31997                 (typeof(action.result) != 'undefined')  &&
31998                 (typeof(action.result.errors) != 'undefined')  &&
31999                 (typeof(action.result.errors.needs_confirm) != 'undefined')
32000            ){
32001                 var _t = this;
32002                 Roo.MessageBox.confirm(
32003                     "Change requires confirmation",
32004                     action.result.errorMsg,
32005                     function(r) {
32006                         if (r != 'yes') {
32007                             return;
32008                         }
32009                         _t.doAction('submit', { params :  { _submit_confirmed : 1 } }  );
32010                     }
32011                     
32012                 );
32013                 
32014                 
32015                 
32016                 return;
32017             }
32018             
32019             Roo.callback(o.failure, o.scope, [this, action]);
32020             // show an error message if no failed handler is set..
32021             if (!this.hasListener('actionfailed')) {
32022                 Roo.MessageBox.alert("Error",
32023                     (typeof(action.result) != 'undefined' && typeof(action.result.errorMsg) != 'undefined') ?
32024                         action.result.errorMsg :
32025                         "Saving Failed, please check your entries or try again"
32026                 );
32027             }
32028             
32029             this.fireEvent('actionfailed', this, action);
32030         }
32031         
32032     },
32033
32034     /**
32035      * Find a Roo.form.Field in this form by id, dataIndex, name or hiddenName
32036      * @param {String} id The value to search for
32037      * @return Field
32038      */
32039     findField : function(id){
32040         var field = this.items.get(id);
32041         if(!field){
32042             this.items.each(function(f){
32043                 if(f.isFormField && (f.dataIndex == id || f.id == id || f.getName() == id)){
32044                     field = f;
32045                     return false;
32046                 }
32047             });
32048         }
32049         return field || null;
32050     },
32051
32052     /**
32053      * Add a secondary form to this one, 
32054      * Used to provide tabbed forms. One form is primary, with hidden values 
32055      * which mirror the elements from the other forms.
32056      * 
32057      * @param {Roo.form.Form} form to add.
32058      * 
32059      */
32060     addForm : function(form)
32061     {
32062        
32063         if (this.childForms.indexOf(form) > -1) {
32064             // already added..
32065             return;
32066         }
32067         this.childForms.push(form);
32068         var n = '';
32069         Roo.each(form.allItems, function (fe) {
32070             
32071             n = typeof(fe.getName) == 'undefined' ? fe.name : fe.getName();
32072             if (this.findField(n)) { // already added..
32073                 return;
32074             }
32075             var add = new Roo.form.Hidden({
32076                 name : n
32077             });
32078             add.render(this.el);
32079             
32080             this.add( add );
32081         }, this);
32082         
32083     },
32084     /**
32085      * Mark fields in this form invalid in bulk.
32086      * @param {Array/Object} errors Either an array in the form [{id:'fieldId', msg:'The message'},...] or an object hash of {id: msg, id2: msg2}
32087      * @return {BasicForm} this
32088      */
32089     markInvalid : function(errors){
32090         if(errors instanceof Array){
32091             for(var i = 0, len = errors.length; i < len; i++){
32092                 var fieldError = errors[i];
32093                 var f = this.findField(fieldError.id);
32094                 if(f){
32095                     f.markInvalid(fieldError.msg);
32096                 }
32097             }
32098         }else{
32099             var field, id;
32100             for(id in errors){
32101                 if(typeof errors[id] != 'function' && (field = this.findField(id))){
32102                     field.markInvalid(errors[id]);
32103                 }
32104             }
32105         }
32106         Roo.each(this.childForms || [], function (f) {
32107             f.markInvalid(errors);
32108         });
32109         
32110         return this;
32111     },
32112
32113     /**
32114      * Set values for fields in this form in bulk.
32115      * @param {Array/Object} values Either an array in the form [{id:'fieldId', value:'foo'},...] or an object hash of {id: value, id2: value2}
32116      * @return {BasicForm} this
32117      */
32118     setValues : function(values){
32119         if(values instanceof Array){ // array of objects
32120             for(var i = 0, len = values.length; i < len; i++){
32121                 var v = values[i];
32122                 var f = this.findField(v.id);
32123                 if(f){
32124                     f.setValue(v.value);
32125                     if(this.trackResetOnLoad){
32126                         f.originalValue = f.getValue();
32127                     }
32128                 }
32129             }
32130         }else{ // object hash
32131             var field, id;
32132             for(id in values){
32133                 if(typeof values[id] != 'function' && (field = this.findField(id))){
32134                     
32135                     
32136                     
32137                     
32138                     if (field.setFromData && 
32139                         field.valueField && 
32140                         field.displayField &&
32141                         // combos' with local stores can 
32142                         // be queried via setValue()
32143                         // to set their value..
32144                         (field.store && !field.store.isLocal)
32145                         ) {
32146                         // it's a combo
32147                         var sd = { };
32148                         sd[field.valueField] = typeof(values[field.hiddenName]) == 'undefined' ? '' : values[field.hiddenName];
32149                         sd[field.displayField] = typeof(values[field.name]) == 'undefined' ? '' : values[field.name];
32150                         field.setFromData(sd);
32151                         
32152                     } else if (field.inputType && field.inputType == 'radio') {
32153                         
32154                         field.setValue(values[id]);
32155                     } else {
32156                         field.setValue(values[id]);
32157                     }
32158                     
32159                     
32160                     if(this.trackResetOnLoad){
32161                         field.originalValue = field.getValue();
32162                     }
32163                 }
32164             }
32165         }
32166         this.resetHasChanged();
32167         
32168         
32169         Roo.each(this.childForms || [], function (f) {
32170             f.setValues(values);
32171             f.resetHasChanged();
32172         });
32173                 
32174         return this;
32175     },
32176  
32177     /**
32178      * Returns the fields in this form as an object with key/value pairs. If multiple fields exist with the same name
32179      * they are returned as an array.
32180      * @param {Boolean} asString (def)
32181      * @return {Object}
32182      */
32183     getValues : function(asString)
32184     {
32185         if (this.childForms) {
32186             // copy values from the child forms
32187             Roo.each(this.childForms, function (f) {
32188                 this.setValues(f.getFieldValues()); // get the full set of data, as we might be copying comboboxes from external into this one.
32189             }, this);
32190         }
32191         
32192         // use formdata
32193         if (typeof(FormData) != 'undefined' && asString !== true) {
32194             // this relies on a 'recent' version of chrome apparently...
32195             try {
32196                 var fd = (new FormData(this.el.dom)).entries();
32197                 var ret = {};
32198                 var ent = fd.next();
32199                 while (!ent.done) {
32200                     ret[ent.value[0]] = ent.value[1]; // not sure how this will handle duplicates..
32201                     ent = fd.next();
32202                 };
32203                 return ret;
32204             } catch(e) {
32205                 
32206             }
32207             
32208         }
32209         
32210         
32211         var fs = Roo.lib.Ajax.serializeForm(this.el.dom);
32212         if(asString === true){
32213             return fs;
32214         }
32215         return Roo.urlDecode(fs);
32216     },
32217     
32218     /**
32219      * Returns the fields in this form as an object with key/value pairs. 
32220      * This differs from getValues as it calls getValue on each child item, rather than using dom data.
32221      * Normally this will not return readOnly data 
32222      * @param {Boolean} with_readonly return readonly field data.
32223      * @return {Object}
32224      */
32225     getFieldValues : function(with_readonly)
32226     {
32227         if (this.childForms) {
32228             // copy values from the child forms
32229             // should this call getFieldValues - probably not as we do not currently copy
32230             // hidden fields when we generate..
32231             Roo.each(this.childForms, function (f) {
32232                 this.setValues(f.getFieldValues());
32233             }, this);
32234         }
32235         
32236         var ret = {};
32237         this.items.each(function(f){
32238             
32239             if (f.readOnly && with_readonly !== true) {
32240                 return; // skip read only values. - this is in theory to stop 'old' values being copied over new ones
32241                         // if a subform contains a copy of them.
32242                         // if you have subforms with the same editable data, you will need to copy the data back
32243                         // and forth.
32244             }
32245             
32246             if (!f.getName()) {
32247                 return;
32248             }
32249             var v = f.getValue();
32250             if (f.inputType =='radio') {
32251                 if (typeof(ret[f.getName()]) == 'undefined') {
32252                     ret[f.getName()] = ''; // empty..
32253                 }
32254                 
32255                 if (!f.el.dom.checked) {
32256                     return;
32257                     
32258                 }
32259                 v = f.el.dom.value;
32260                 
32261             }
32262             
32263             // not sure if this supported any more..
32264             if ((typeof(v) == 'object') && f.getRawValue) {
32265                 v = f.getRawValue() ; // dates..
32266             }
32267             // combo boxes where name != hiddenName...
32268             if (f.name != f.getName()) {
32269                 ret[f.name] = f.getRawValue();
32270             }
32271             ret[f.getName()] = v;
32272         });
32273         
32274         return ret;
32275     },
32276
32277     /**
32278      * Clears all invalid messages in this form.
32279      * @return {BasicForm} this
32280      */
32281     clearInvalid : function(){
32282         this.items.each(function(f){
32283            f.clearInvalid();
32284         });
32285         
32286         Roo.each(this.childForms || [], function (f) {
32287             f.clearInvalid();
32288         });
32289         
32290         
32291         return this;
32292     },
32293
32294     /**
32295      * Resets this form.
32296      * @return {BasicForm} this
32297      */
32298     reset : function(){
32299         this.items.each(function(f){
32300             f.reset();
32301         });
32302         
32303         Roo.each(this.childForms || [], function (f) {
32304             f.reset();
32305         });
32306         this.resetHasChanged();
32307         
32308         return this;
32309     },
32310
32311     /**
32312      * Add Roo.form components to this form.
32313      * @param {Field} field1
32314      * @param {Field} field2 (optional)
32315      * @param {Field} etc (optional)
32316      * @return {BasicForm} this
32317      */
32318     add : function(){
32319         this.items.addAll(Array.prototype.slice.call(arguments, 0));
32320         return this;
32321     },
32322
32323
32324     /**
32325      * Removes a field from the items collection (does NOT remove its markup).
32326      * @param {Field} field
32327      * @return {BasicForm} this
32328      */
32329     remove : function(field){
32330         this.items.remove(field);
32331         return this;
32332     },
32333
32334     /**
32335      * Looks at the fields in this form, checks them for an id attribute,
32336      * and calls applyTo on the existing dom element with that id.
32337      * @return {BasicForm} this
32338      */
32339     render : function(){
32340         this.items.each(function(f){
32341             if(f.isFormField && !f.rendered && document.getElementById(f.id)){ // if the element exists
32342                 f.applyTo(f.id);
32343             }
32344         });
32345         return this;
32346     },
32347
32348     /**
32349      * Calls {@link Ext#apply} for all fields in this form with the passed object.
32350      * @param {Object} values
32351      * @return {BasicForm} this
32352      */
32353     applyToFields : function(o){
32354         this.items.each(function(f){
32355            Roo.apply(f, o);
32356         });
32357         return this;
32358     },
32359
32360     /**
32361      * Calls {@link Ext#applyIf} for all field in this form with the passed object.
32362      * @param {Object} values
32363      * @return {BasicForm} this
32364      */
32365     applyIfToFields : function(o){
32366         this.items.each(function(f){
32367            Roo.applyIf(f, o);
32368         });
32369         return this;
32370     }
32371 });
32372
32373 // back compat
32374 Roo.BasicForm = Roo.form.BasicForm;
32375
32376 Roo.apply(Roo.form.BasicForm, {
32377     
32378     popover : {
32379         
32380         padding : 5,
32381         
32382         isApplied : false,
32383         
32384         isMasked : false,
32385         
32386         form : false,
32387         
32388         target : false,
32389         
32390         intervalID : false,
32391         
32392         maskEl : false,
32393         
32394         apply : function()
32395         {
32396             if(this.isApplied){
32397                 return;
32398             }
32399             
32400             this.maskEl = {
32401                 top : Roo.DomHelper.append(Roo.get(document.body), { tag: "div", cls:"x-dlg-mask roo-form-top-mask" }, true),
32402                 left : Roo.DomHelper.append(Roo.get(document.body), { tag: "div", cls:"x-dlg-mask roo-form-left-mask" }, true),
32403                 bottom : Roo.DomHelper.append(Roo.get(document.body), { tag: "div", cls:"x-dlg-mask roo-form-bottom-mask" }, true),
32404                 right : Roo.DomHelper.append(Roo.get(document.body), { tag: "div", cls:"x-dlg-mask roo-form-right-mask" }, true)
32405             };
32406             
32407             this.maskEl.top.enableDisplayMode("block");
32408             this.maskEl.left.enableDisplayMode("block");
32409             this.maskEl.bottom.enableDisplayMode("block");
32410             this.maskEl.right.enableDisplayMode("block");
32411             
32412             Roo.get(document.body).on('click', function(){
32413                 this.unmask();
32414             }, this);
32415             
32416             Roo.get(document.body).on('touchstart', function(){
32417                 this.unmask();
32418             }, this);
32419             
32420             this.isApplied = true
32421         },
32422         
32423         mask : function(form, target)
32424         {
32425             this.form = form;
32426             
32427             this.target = target;
32428             
32429             if(!this.form.errorMask || !target.el){
32430                 return;
32431             }
32432             
32433             var scrollable = this.target.el.findScrollableParent() || this.target.el.findParent('div.x-layout-active-content', 100, true) || Roo.get(document.body);
32434             
32435             var ot = this.target.el.calcOffsetsTo(scrollable);
32436             
32437             var scrollTo = ot[1] - this.form.maskOffset;
32438             
32439             scrollTo = Math.min(scrollTo, scrollable.dom.scrollHeight);
32440             
32441             scrollable.scrollTo('top', scrollTo);
32442             
32443             var el = this.target.wrap || this.target.el;
32444             
32445             var box = el.getBox();
32446             
32447             this.maskEl.top.setStyle('position', 'absolute');
32448             this.maskEl.top.setStyle('z-index', 10000);
32449             this.maskEl.top.setSize(Roo.lib.Dom.getDocumentWidth(), box.y - this.padding);
32450             this.maskEl.top.setLeft(0);
32451             this.maskEl.top.setTop(0);
32452             this.maskEl.top.show();
32453             
32454             this.maskEl.left.setStyle('position', 'absolute');
32455             this.maskEl.left.setStyle('z-index', 10000);
32456             this.maskEl.left.setSize(box.x - this.padding, box.height + this.padding * 2);
32457             this.maskEl.left.setLeft(0);
32458             this.maskEl.left.setTop(box.y - this.padding);
32459             this.maskEl.left.show();
32460
32461             this.maskEl.bottom.setStyle('position', 'absolute');
32462             this.maskEl.bottom.setStyle('z-index', 10000);
32463             this.maskEl.bottom.setSize(Roo.lib.Dom.getDocumentWidth(), Roo.lib.Dom.getDocumentHeight() - box.bottom - this.padding);
32464             this.maskEl.bottom.setLeft(0);
32465             this.maskEl.bottom.setTop(box.bottom + this.padding);
32466             this.maskEl.bottom.show();
32467
32468             this.maskEl.right.setStyle('position', 'absolute');
32469             this.maskEl.right.setStyle('z-index', 10000);
32470             this.maskEl.right.setSize(Roo.lib.Dom.getDocumentWidth() - box.right - this.padding, box.height + this.padding * 2);
32471             this.maskEl.right.setLeft(box.right + this.padding);
32472             this.maskEl.right.setTop(box.y - this.padding);
32473             this.maskEl.right.show();
32474
32475             this.intervalID = window.setInterval(function() {
32476                 Roo.form.BasicForm.popover.unmask();
32477             }, 10000);
32478
32479             window.onwheel = function(){ return false;};
32480             
32481             (function(){ this.isMasked = true; }).defer(500, this);
32482             
32483         },
32484         
32485         unmask : function()
32486         {
32487             if(!this.isApplied || !this.isMasked || !this.form || !this.target || !this.form.errorMask){
32488                 return;
32489             }
32490             
32491             this.maskEl.top.setStyle('position', 'absolute');
32492             this.maskEl.top.setSize(0, 0).setXY([0, 0]);
32493             this.maskEl.top.hide();
32494
32495             this.maskEl.left.setStyle('position', 'absolute');
32496             this.maskEl.left.setSize(0, 0).setXY([0, 0]);
32497             this.maskEl.left.hide();
32498
32499             this.maskEl.bottom.setStyle('position', 'absolute');
32500             this.maskEl.bottom.setSize(0, 0).setXY([0, 0]);
32501             this.maskEl.bottom.hide();
32502
32503             this.maskEl.right.setStyle('position', 'absolute');
32504             this.maskEl.right.setSize(0, 0).setXY([0, 0]);
32505             this.maskEl.right.hide();
32506             
32507             window.onwheel = function(){ return true;};
32508             
32509             if(this.intervalID){
32510                 window.clearInterval(this.intervalID);
32511                 this.intervalID = false;
32512             }
32513             
32514             this.isMasked = false;
32515             
32516         }
32517         
32518     }
32519     
32520 });/*
32521  * Based on:
32522  * Ext JS Library 1.1.1
32523  * Copyright(c) 2006-2007, Ext JS, LLC.
32524  *
32525  * Originally Released Under LGPL - original licence link has changed is not relivant.
32526  *
32527  * Fork - LGPL
32528  * <script type="text/javascript">
32529  */
32530
32531 /**
32532  * @class Roo.form.Form
32533  * @extends Roo.form.BasicForm
32534  * @children Roo.form.Column Roo.form.FieldSet Roo.form.Row Roo.form.Field Roo.Button Roo.form.TextItem
32535  * Adds the ability to dynamically render forms with JavaScript to {@link Roo.form.BasicForm}.
32536  * @constructor
32537  * @param {Object} config Configuration options
32538  */
32539 Roo.form.Form = function(config){
32540     var xitems =  [];
32541     if (config.items) {
32542         xitems = config.items;
32543         delete config.items;
32544     }
32545    
32546     
32547     Roo.form.Form.superclass.constructor.call(this, null, config);
32548     this.url = this.url || this.action;
32549     if(!this.root){
32550         this.root = new Roo.form.Layout(Roo.applyIf({
32551             id: Roo.id()
32552         }, config));
32553     }
32554     this.active = this.root;
32555     /**
32556      * Array of all the buttons that have been added to this form via {@link addButton}
32557      * @type Array
32558      */
32559     this.buttons = [];
32560     this.allItems = [];
32561     this.addEvents({
32562         /**
32563          * @event clientvalidation
32564          * If the monitorValid config option is true, this event fires repetitively to notify of valid state
32565          * @param {Form} this
32566          * @param {Boolean} valid true if the form has passed client-side validation
32567          */
32568         clientvalidation: true,
32569         /**
32570          * @event rendered
32571          * Fires when the form is rendered
32572          * @param {Roo.form.Form} form
32573          */
32574         rendered : true
32575     });
32576     
32577     if (this.progressUrl) {
32578             // push a hidden field onto the list of fields..
32579             this.addxtype( {
32580                     xns: Roo.form, 
32581                     xtype : 'Hidden', 
32582                     name : 'UPLOAD_IDENTIFIER' 
32583             });
32584         }
32585         
32586     
32587     Roo.each(xitems, this.addxtype, this);
32588     
32589 };
32590
32591 Roo.extend(Roo.form.Form, Roo.form.BasicForm, {
32592      /**
32593      * @cfg {Roo.Button} buttons[] buttons at bottom of form
32594      */
32595     
32596     /**
32597      * @cfg {Number} labelWidth The width of labels. This property cascades to child containers.
32598      */
32599     /**
32600      * @cfg {String} itemCls A css class to apply to the x-form-item of fields. This property cascades to child containers.
32601      */
32602     /**
32603      * @cfg {String} buttonAlign (left|center|right)  Valid values are "left," "center" and "right" (defaults to "center")
32604      */
32605     buttonAlign:'center',
32606
32607     /**
32608      * @cfg {Number} minButtonWidth Minimum width of all buttons in pixels (defaults to 75)
32609      */
32610     minButtonWidth:75,
32611
32612     /**
32613      * @cfg {String} labelAlign (left|top|right) Valid values are "left," "top" and "right" (defaults to "left").
32614      * This property cascades to child containers if not set.
32615      */
32616     labelAlign:'left',
32617
32618     /**
32619      * @cfg {Boolean} monitorValid If true the form monitors its valid state <b>client-side</b> and
32620      * fires a looping event with that state. This is required to bind buttons to the valid
32621      * state using the config value formBind:true on the button.
32622      */
32623     monitorValid : false,
32624
32625     /**
32626      * @cfg {Number} monitorPoll The milliseconds to poll valid state, ignored if monitorValid is not true (defaults to 200)
32627      */
32628     monitorPoll : 200,
32629     
32630     /**
32631      * @cfg {String} progressUrl - Url to return progress data 
32632      */
32633     
32634     progressUrl : false,
32635     /**
32636      * @cfg {boolean|FormData} formData - true to use new 'FormData' post, or set to a new FormData({dom form}) Object, if
32637      * sending a formdata with extra parameters - eg uploaded elements.
32638      */
32639     
32640     formData : false,
32641     
32642     /**
32643      * Opens a new {@link Roo.form.Column} container in the layout stack. If fields are passed after the config, the
32644      * fields are added and the column is closed. If no fields are passed the column remains open
32645      * until end() is called.
32646      * @param {Object} config The config to pass to the column
32647      * @param {Field} field1 (optional)
32648      * @param {Field} field2 (optional)
32649      * @param {Field} etc (optional)
32650      * @return Column The column container object
32651      */
32652     column : function(c){
32653         var col = new Roo.form.Column(c);
32654         this.start(col);
32655         if(arguments.length > 1){ // duplicate code required because of Opera
32656             this.add.apply(this, Array.prototype.slice.call(arguments, 1));
32657             this.end();
32658         }
32659         return col;
32660     },
32661
32662     /**
32663      * Opens a new {@link Roo.form.FieldSet} container in the layout stack. If fields are passed after the config, the
32664      * fields are added and the fieldset is closed. If no fields are passed the fieldset remains open
32665      * until end() is called.
32666      * @param {Object} config The config to pass to the fieldset
32667      * @param {Field} field1 (optional)
32668      * @param {Field} field2 (optional)
32669      * @param {Field} etc (optional)
32670      * @return FieldSet The fieldset container object
32671      */
32672     fieldset : function(c){
32673         var fs = new Roo.form.FieldSet(c);
32674         this.start(fs);
32675         if(arguments.length > 1){ // duplicate code required because of Opera
32676             this.add.apply(this, Array.prototype.slice.call(arguments, 1));
32677             this.end();
32678         }
32679         return fs;
32680     },
32681
32682     /**
32683      * Opens a new {@link Roo.form.Layout} container in the layout stack. If fields are passed after the config, the
32684      * fields are added and the container is closed. If no fields are passed the container remains open
32685      * until end() is called.
32686      * @param {Object} config The config to pass to the Layout
32687      * @param {Field} field1 (optional)
32688      * @param {Field} field2 (optional)
32689      * @param {Field} etc (optional)
32690      * @return Layout The container object
32691      */
32692     container : function(c){
32693         var l = new Roo.form.Layout(c);
32694         this.start(l);
32695         if(arguments.length > 1){ // duplicate code required because of Opera
32696             this.add.apply(this, Array.prototype.slice.call(arguments, 1));
32697             this.end();
32698         }
32699         return l;
32700     },
32701
32702     /**
32703      * Opens the passed container in the layout stack. The container can be any {@link Roo.form.Layout} or subclass.
32704      * @param {Object} container A Roo.form.Layout or subclass of Layout
32705      * @return {Form} this
32706      */
32707     start : function(c){
32708         // cascade label info
32709         Roo.applyIf(c, {'labelAlign': this.active.labelAlign, 'labelWidth': this.active.labelWidth, 'itemCls': this.active.itemCls});
32710         this.active.stack.push(c);
32711         c.ownerCt = this.active;
32712         this.active = c;
32713         return this;
32714     },
32715
32716     /**
32717      * Closes the current open container
32718      * @return {Form} this
32719      */
32720     end : function(){
32721         if(this.active == this.root){
32722             return this;
32723         }
32724         this.active = this.active.ownerCt;
32725         return this;
32726     },
32727
32728     /**
32729      * Add Roo.form components to the current open container (e.g. column, fieldset, etc.).  Fields added via this method
32730      * can also be passed with an additional property of fieldLabel, which if supplied, will provide the text to display
32731      * as the label of the field.
32732      * @param {Field} field1
32733      * @param {Field} field2 (optional)
32734      * @param {Field} etc. (optional)
32735      * @return {Form} this
32736      */
32737     add : function(){
32738         this.active.stack.push.apply(this.active.stack, arguments);
32739         this.allItems.push.apply(this.allItems,arguments);
32740         var r = [];
32741         for(var i = 0, a = arguments, len = a.length; i < len; i++) {
32742             if(a[i].isFormField){
32743                 r.push(a[i]);
32744             }
32745         }
32746         if(r.length > 0){
32747             Roo.form.Form.superclass.add.apply(this, r);
32748         }
32749         return this;
32750     },
32751     
32752
32753     
32754     
32755     
32756      /**
32757      * Find any element that has been added to a form, using it's ID or name
32758      * This can include framesets, columns etc. along with regular fields..
32759      * @param {String} id - id or name to find.
32760      
32761      * @return {Element} e - or false if nothing found.
32762      */
32763     findbyId : function(id)
32764     {
32765         var ret = false;
32766         if (!id) {
32767             return ret;
32768         }
32769         Roo.each(this.allItems, function(f){
32770             if (f.id == id || f.name == id ){
32771                 ret = f;
32772                 return false;
32773             }
32774         });
32775         return ret;
32776     },
32777
32778     
32779     
32780     /**
32781      * Render this form into the passed container. This should only be called once!
32782      * @param {String/HTMLElement/Element} container The element this component should be rendered into
32783      * @return {Form} this
32784      */
32785     render : function(ct)
32786     {
32787         
32788         
32789         
32790         ct = Roo.get(ct);
32791         var o = this.autoCreate || {
32792             tag: 'form',
32793             method : this.method || 'POST',
32794             id : this.id || Roo.id()
32795         };
32796         this.initEl(ct.createChild(o));
32797
32798         this.root.render(this.el);
32799         
32800        
32801              
32802         this.items.each(function(f){
32803             f.render('x-form-el-'+f.id);
32804         });
32805
32806         if(this.buttons.length > 0){
32807             // tables are required to maintain order and for correct IE layout
32808             var tb = this.el.createChild({cls:'x-form-btns-ct', cn: {
32809                 cls:"x-form-btns x-form-btns-"+this.buttonAlign,
32810                 html:'<table cellspacing="0"><tbody><tr></tr></tbody></table><div class="x-clear"></div>'
32811             }}, null, true);
32812             var tr = tb.getElementsByTagName('tr')[0];
32813             for(var i = 0, len = this.buttons.length; i < len; i++) {
32814                 var b = this.buttons[i];
32815                 var td = document.createElement('td');
32816                 td.className = 'x-form-btn-td';
32817                 b.render(tr.appendChild(td));
32818             }
32819         }
32820         if(this.monitorValid){ // initialize after render
32821             this.startMonitoring();
32822         }
32823         this.fireEvent('rendered', this);
32824         return this;
32825     },
32826
32827     /**
32828      * Adds a button to the footer of the form - this <b>must</b> be called before the form is rendered.
32829      * @param {String/Object} config A string becomes the button text, an object can either be a Button config
32830      * object or a valid Roo.DomHelper element config
32831      * @param {Function} handler The function called when the button is clicked
32832      * @param {Object} scope (optional) The scope of the handler function
32833      * @return {Roo.Button}
32834      */
32835     addButton : function(config, handler, scope){
32836         var bc = {
32837             handler: handler,
32838             scope: scope,
32839             minWidth: this.minButtonWidth,
32840             hideParent:true
32841         };
32842         if(typeof config == "string"){
32843             bc.text = config;
32844         }else{
32845             Roo.apply(bc, config);
32846         }
32847         var btn = new Roo.Button(null, bc);
32848         this.buttons.push(btn);
32849         return btn;
32850     },
32851
32852      /**
32853      * Adds a series of form elements (using the xtype property as the factory method.
32854      * Valid xtypes are:  TextField, TextArea .... Button, Layout, FieldSet, Column, (and 'end' to close a block)
32855      * @param {Object} config 
32856      */
32857     
32858     addxtype : function()
32859     {
32860         var ar = Array.prototype.slice.call(arguments, 0);
32861         var ret = false;
32862         for(var i = 0; i < ar.length; i++) {
32863             if (!ar[i]) {
32864                 continue; // skip -- if this happends something invalid got sent, we 
32865                 // should ignore it, as basically that interface element will not show up
32866                 // and that should be pretty obvious!!
32867             }
32868             
32869             if (Roo.form[ar[i].xtype]) {
32870                 ar[i].form = this;
32871                 var fe = Roo.factory(ar[i], Roo.form);
32872                 if (!ret) {
32873                     ret = fe;
32874                 }
32875                 fe.form = this;
32876                 if (fe.store) {
32877                     fe.store.form = this;
32878                 }
32879                 if (fe.isLayout) {  
32880                          
32881                     this.start(fe);
32882                     this.allItems.push(fe);
32883                     if (fe.items && fe.addxtype) {
32884                         fe.addxtype.apply(fe, fe.items);
32885                         delete fe.items;
32886                     }
32887                      this.end();
32888                     continue;
32889                 }
32890                 
32891                 
32892                  
32893                 this.add(fe);
32894               //  console.log('adding ' + ar[i].xtype);
32895             }
32896             if (ar[i].xtype == 'Button') {  
32897                 //console.log('adding button');
32898                 //console.log(ar[i]);
32899                 this.addButton(ar[i]);
32900                 this.allItems.push(fe);
32901                 continue;
32902             }
32903             
32904             if (ar[i].xtype == 'end') { // so we can add fieldsets... / layout etc.
32905                 alert('end is not supported on xtype any more, use items');
32906             //    this.end();
32907             //    //console.log('adding end');
32908             }
32909             
32910         }
32911         return ret;
32912     },
32913     
32914     /**
32915      * Starts monitoring of the valid state of this form. Usually this is done by passing the config
32916      * option "monitorValid"
32917      */
32918     startMonitoring : function(){
32919         if(!this.bound){
32920             this.bound = true;
32921             Roo.TaskMgr.start({
32922                 run : this.bindHandler,
32923                 interval : this.monitorPoll || 200,
32924                 scope: this
32925             });
32926         }
32927     },
32928
32929     /**
32930      * Stops monitoring of the valid state of this form
32931      */
32932     stopMonitoring : function(){
32933         this.bound = false;
32934     },
32935
32936     // private
32937     bindHandler : function(){
32938         if(!this.bound){
32939             return false; // stops binding
32940         }
32941         var valid = true;
32942         this.items.each(function(f){
32943             if(!f.isValid(true)){
32944                 valid = false;
32945                 return false;
32946             }
32947         });
32948         for(var i = 0, len = this.buttons.length; i < len; i++){
32949             var btn = this.buttons[i];
32950             if(btn.formBind === true && btn.disabled === valid){
32951                 btn.setDisabled(!valid);
32952             }
32953         }
32954         this.fireEvent('clientvalidation', this, valid);
32955     }
32956     
32957     
32958     
32959     
32960     
32961     
32962     
32963     
32964 });
32965
32966
32967 // back compat
32968 Roo.Form = Roo.form.Form;
32969 /*
32970  * Based on:
32971  * Ext JS Library 1.1.1
32972  * Copyright(c) 2006-2007, Ext JS, LLC.
32973  *
32974  * Originally Released Under LGPL - original licence link has changed is not relivant.
32975  *
32976  * Fork - LGPL
32977  * <script type="text/javascript">
32978  */
32979
32980 // as we use this in bootstrap.
32981 Roo.namespace('Roo.form');
32982  /**
32983  * @class Roo.form.Action
32984  * Internal Class used to handle form actions
32985  * @constructor
32986  * @param {Roo.form.BasicForm} el The form element or its id
32987  * @param {Object} config Configuration options
32988  */
32989
32990  
32991  
32992 // define the action interface
32993 Roo.form.Action = function(form, options){
32994     this.form = form;
32995     this.options = options || {};
32996 };
32997 /**
32998  * Client Validation Failed
32999  * @const 
33000  */
33001 Roo.form.Action.CLIENT_INVALID = 'client';
33002 /**
33003  * Server Validation Failed
33004  * @const 
33005  */
33006 Roo.form.Action.SERVER_INVALID = 'server';
33007  /**
33008  * Connect to Server Failed
33009  * @const 
33010  */
33011 Roo.form.Action.CONNECT_FAILURE = 'connect';
33012 /**
33013  * Reading Data from Server Failed
33014  * @const 
33015  */
33016 Roo.form.Action.LOAD_FAILURE = 'load';
33017
33018 Roo.form.Action.prototype = {
33019     type : 'default',
33020     failureType : undefined,
33021     response : undefined,
33022     result : undefined,
33023
33024     // interface method
33025     run : function(options){
33026
33027     },
33028
33029     // interface method
33030     success : function(response){
33031
33032     },
33033
33034     // interface method
33035     handleResponse : function(response){
33036
33037     },
33038
33039     // default connection failure
33040     failure : function(response){
33041         
33042         this.response = response;
33043         this.failureType = Roo.form.Action.CONNECT_FAILURE;
33044         this.form.afterAction(this, false);
33045     },
33046
33047     processResponse : function(response){
33048         this.response = response;
33049         if(!response.responseText){
33050             return true;
33051         }
33052         this.result = this.handleResponse(response);
33053         return this.result;
33054     },
33055
33056     // utility functions used internally
33057     getUrl : function(appendParams){
33058         var url = this.options.url || this.form.url || this.form.el.dom.action;
33059         if(appendParams){
33060             var p = this.getParams();
33061             if(p){
33062                 url += (url.indexOf('?') != -1 ? '&' : '?') + p;
33063             }
33064         }
33065         return url;
33066     },
33067
33068     getMethod : function(){
33069         return (this.options.method || this.form.method || this.form.el.dom.method || 'POST').toUpperCase();
33070     },
33071
33072     getParams : function(){
33073         var bp = this.form.baseParams;
33074         var p = this.options.params;
33075         if(p){
33076             if(typeof p == "object"){
33077                 p = Roo.urlEncode(Roo.applyIf(p, bp));
33078             }else if(typeof p == 'string' && bp){
33079                 p += '&' + Roo.urlEncode(bp);
33080             }
33081         }else if(bp){
33082             p = Roo.urlEncode(bp);
33083         }
33084         return p;
33085     },
33086
33087     createCallback : function(){
33088         return {
33089             success: this.success,
33090             failure: this.failure,
33091             scope: this,
33092             timeout: (this.form.timeout*1000),
33093             upload: this.form.fileUpload ? this.success : undefined
33094         };
33095     }
33096 };
33097
33098 Roo.form.Action.Submit = function(form, options){
33099     Roo.form.Action.Submit.superclass.constructor.call(this, form, options);
33100 };
33101
33102 Roo.extend(Roo.form.Action.Submit, Roo.form.Action, {
33103     type : 'submit',
33104
33105     haveProgress : false,
33106     uploadComplete : false,
33107     
33108     // uploadProgress indicator.
33109     uploadProgress : function()
33110     {
33111         if (!this.form.progressUrl) {
33112             return;
33113         }
33114         
33115         if (!this.haveProgress) {
33116             Roo.MessageBox.progress("Uploading", "Uploading");
33117         }
33118         if (this.uploadComplete) {
33119            Roo.MessageBox.hide();
33120            return;
33121         }
33122         
33123         this.haveProgress = true;
33124    
33125         var uid = this.form.findField('UPLOAD_IDENTIFIER').getValue();
33126         
33127         var c = new Roo.data.Connection();
33128         c.request({
33129             url : this.form.progressUrl,
33130             params: {
33131                 id : uid
33132             },
33133             method: 'GET',
33134             success : function(req){
33135                //console.log(data);
33136                 var rdata = false;
33137                 var edata;
33138                 try  {
33139                    rdata = Roo.decode(req.responseText)
33140                 } catch (e) {
33141                     Roo.log("Invalid data from server..");
33142                     Roo.log(edata);
33143                     return;
33144                 }
33145                 if (!rdata || !rdata.success) {
33146                     Roo.log(rdata);
33147                     Roo.MessageBox.alert(Roo.encode(rdata));
33148                     return;
33149                 }
33150                 var data = rdata.data;
33151                 
33152                 if (this.uploadComplete) {
33153                    Roo.MessageBox.hide();
33154                    return;
33155                 }
33156                    
33157                 if (data){
33158                     Roo.MessageBox.updateProgress(data.bytes_uploaded/data.bytes_total,
33159                        Math.floor((data.bytes_total - data.bytes_uploaded)/1000) + 'k remaining'
33160                     );
33161                 }
33162                 this.uploadProgress.defer(2000,this);
33163             },
33164        
33165             failure: function(data) {
33166                 Roo.log('progress url failed ');
33167                 Roo.log(data);
33168             },
33169             scope : this
33170         });
33171            
33172     },
33173     
33174     
33175     run : function()
33176     {
33177         // run get Values on the form, so it syncs any secondary forms.
33178         this.form.getValues();
33179         
33180         var o = this.options;
33181         var method = this.getMethod();
33182         var isPost = method == 'POST';
33183         if(o.clientValidation === false || this.form.isValid()){
33184             
33185             if (this.form.progressUrl) {
33186                 this.form.findField('UPLOAD_IDENTIFIER').setValue(
33187                     (new Date() * 1) + '' + Math.random());
33188                     
33189             } 
33190             
33191             
33192             Roo.Ajax.request(Roo.apply(this.createCallback(), {
33193                 form:this.form.el.dom,
33194                 url:this.getUrl(!isPost),
33195                 method: method,
33196                 params:isPost ? this.getParams() : null,
33197                 isUpload: this.form.fileUpload,
33198                 formData : this.form.formData
33199             }));
33200             
33201             this.uploadProgress();
33202
33203         }else if (o.clientValidation !== false){ // client validation failed
33204             this.failureType = Roo.form.Action.CLIENT_INVALID;
33205             this.form.afterAction(this, false);
33206         }
33207     },
33208
33209     success : function(response)
33210     {
33211         this.uploadComplete= true;
33212         if (this.haveProgress) {
33213             Roo.MessageBox.hide();
33214         }
33215         
33216         
33217         var result = this.processResponse(response);
33218         if(result === true || result.success){
33219             this.form.afterAction(this, true);
33220             return;
33221         }
33222         if(result.errors){
33223             this.form.markInvalid(result.errors);
33224             this.failureType = Roo.form.Action.SERVER_INVALID;
33225         }
33226         this.form.afterAction(this, false);
33227     },
33228     failure : function(response)
33229     {
33230         this.uploadComplete= true;
33231         if (this.haveProgress) {
33232             Roo.MessageBox.hide();
33233         }
33234         
33235         this.response = response;
33236         this.failureType = Roo.form.Action.CONNECT_FAILURE;
33237         this.form.afterAction(this, false);
33238     },
33239     
33240     handleResponse : function(response){
33241         if(this.form.errorReader){
33242             var rs = this.form.errorReader.read(response);
33243             var errors = [];
33244             if(rs.records){
33245                 for(var i = 0, len = rs.records.length; i < len; i++) {
33246                     var r = rs.records[i];
33247                     errors[i] = r.data;
33248                 }
33249             }
33250             if(errors.length < 1){
33251                 errors = null;
33252             }
33253             return {
33254                 success : rs.success,
33255                 errors : errors
33256             };
33257         }
33258         var ret = false;
33259         try {
33260             var rt = response.responseText;
33261             if (rt.match(/^\<!--\[CDATA\[/)) {
33262                 rt = rt.replace(/^\<!--\[CDATA\[/,'');
33263                 rt = rt.replace(/\]\]--\>$/,'');
33264             }
33265             
33266             ret = Roo.decode(rt);
33267         } catch (e) {
33268             ret = {
33269                 success: false,
33270                 errorMsg: "Failed to read server message: " + (response ? response.responseText : ' - no message'),
33271                 errors : []
33272             };
33273         }
33274         return ret;
33275         
33276     }
33277 });
33278
33279
33280 Roo.form.Action.Load = function(form, options){
33281     Roo.form.Action.Load.superclass.constructor.call(this, form, options);
33282     this.reader = this.form.reader;
33283 };
33284
33285 Roo.extend(Roo.form.Action.Load, Roo.form.Action, {
33286     type : 'load',
33287
33288     run : function(){
33289         
33290         Roo.Ajax.request(Roo.apply(
33291                 this.createCallback(), {
33292                     method:this.getMethod(),
33293                     url:this.getUrl(false),
33294                     params:this.getParams()
33295         }));
33296     },
33297
33298     success : function(response){
33299         
33300         var result = this.processResponse(response);
33301         if(result === true || !result.success || !result.data){
33302             this.failureType = Roo.form.Action.LOAD_FAILURE;
33303             this.form.afterAction(this, false);
33304             return;
33305         }
33306         this.form.clearInvalid();
33307         this.form.setValues(result.data);
33308         this.form.afterAction(this, true);
33309     },
33310
33311     handleResponse : function(response){
33312         if(this.form.reader){
33313             var rs = this.form.reader.read(response);
33314             var data = rs.records && rs.records[0] ? rs.records[0].data : null;
33315             return {
33316                 success : rs.success,
33317                 data : data
33318             };
33319         }
33320         return Roo.decode(response.responseText);
33321     }
33322 });
33323
33324 Roo.form.Action.ACTION_TYPES = {
33325     'load' : Roo.form.Action.Load,
33326     'submit' : Roo.form.Action.Submit
33327 };/*
33328  * Based on:
33329  * Ext JS Library 1.1.1
33330  * Copyright(c) 2006-2007, Ext JS, LLC.
33331  *
33332  * Originally Released Under LGPL - original licence link has changed is not relivant.
33333  *
33334  * Fork - LGPL
33335  * <script type="text/javascript">
33336  */
33337  
33338 /**
33339  * @class Roo.form.Layout
33340  * @extends Roo.Component
33341  * @children Roo.form.Column Roo.form.Row Roo.form.Field Roo.Button Roo.form.TextItem Roo.form.FieldSet
33342  * Creates a container for layout and rendering of fields in an {@link Roo.form.Form}.
33343  * @constructor
33344  * @param {Object} config Configuration options
33345  */
33346 Roo.form.Layout = function(config){
33347     var xitems = [];
33348     if (config.items) {
33349         xitems = config.items;
33350         delete config.items;
33351     }
33352     Roo.form.Layout.superclass.constructor.call(this, config);
33353     this.stack = [];
33354     Roo.each(xitems, this.addxtype, this);
33355      
33356 };
33357
33358 Roo.extend(Roo.form.Layout, Roo.Component, {
33359     /**
33360      * @cfg {String/Object} autoCreate
33361      * A DomHelper element spec used to autocreate the layout (defaults to {tag: 'div', cls: 'x-form-ct'})
33362      */
33363     /**
33364      * @cfg {String/Object/Function} style
33365      * A style specification string, e.g. "width:100px", or object in the form {width:"100px"}, or
33366      * a function which returns such a specification.
33367      */
33368     /**
33369      * @cfg {String} labelAlign (left|top|right)
33370      * Valid values are "left," "top" and "right" (defaults to "left")
33371      */
33372     /**
33373      * @cfg {Number} labelWidth
33374      * Fixed width in pixels of all field labels (defaults to undefined)
33375      */
33376     /**
33377      * @cfg {Boolean} clear
33378      * True to add a clearing element at the end of this layout, equivalent to CSS clear: both (defaults to true)
33379      */
33380     clear : true,
33381     /**
33382      * @cfg {String} labelSeparator
33383      * The separator to use after field labels (defaults to ':')
33384      */
33385     labelSeparator : ':',
33386     /**
33387      * @cfg {Boolean} hideLabels
33388      * True to suppress the display of field labels in this layout (defaults to false)
33389      */
33390     hideLabels : false,
33391
33392     // private
33393     defaultAutoCreate : {tag: 'div', cls: 'x-form-ct'},
33394     
33395     isLayout : true,
33396     
33397     // private
33398     onRender : function(ct, position){
33399         if(this.el){ // from markup
33400             this.el = Roo.get(this.el);
33401         }else {  // generate
33402             var cfg = this.getAutoCreate();
33403             this.el = ct.createChild(cfg, position);
33404         }
33405         if(this.style){
33406             this.el.applyStyles(this.style);
33407         }
33408         if(this.labelAlign){
33409             this.el.addClass('x-form-label-'+this.labelAlign);
33410         }
33411         if(this.hideLabels){
33412             this.labelStyle = "display:none";
33413             this.elementStyle = "padding-left:0;";
33414         }else{
33415             if(typeof this.labelWidth == 'number'){
33416                 this.labelStyle = "width:"+this.labelWidth+"px;";
33417                 this.elementStyle = "padding-left:"+((this.labelWidth+(typeof this.labelPad == 'number' ? this.labelPad : 5))+'px')+";";
33418             }
33419             if(this.labelAlign == 'top'){
33420                 this.labelStyle = "width:auto;";
33421                 this.elementStyle = "padding-left:0;";
33422             }
33423         }
33424         var stack = this.stack;
33425         var slen = stack.length;
33426         if(slen > 0){
33427             if(!this.fieldTpl){
33428                 var t = new Roo.Template(
33429                     '<div class="x-form-item {5}">',
33430                         '<label for="{0}" style="{2}">{1}{4}</label>',
33431                         '<div class="x-form-element" id="x-form-el-{0}" style="{3}">',
33432                         '</div>',
33433                     '</div><div class="x-form-clear-left"></div>'
33434                 );
33435                 t.disableFormats = true;
33436                 t.compile();
33437                 Roo.form.Layout.prototype.fieldTpl = t;
33438             }
33439             for(var i = 0; i < slen; i++) {
33440                 if(stack[i].isFormField){
33441                     this.renderField(stack[i]);
33442                 }else{
33443                     this.renderComponent(stack[i]);
33444                 }
33445             }
33446         }
33447         if(this.clear){
33448             this.el.createChild({cls:'x-form-clear'});
33449         }
33450     },
33451
33452     // private
33453     renderField : function(f){
33454         f.fieldEl = Roo.get(this.fieldTpl.append(this.el, [
33455                f.id, //0
33456                f.fieldLabel, //1
33457                f.labelStyle||this.labelStyle||'', //2
33458                this.elementStyle||'', //3
33459                typeof f.labelSeparator == 'undefined' ? this.labelSeparator : f.labelSeparator, //4
33460                f.itemCls||this.itemCls||''  //5
33461        ], true).getPrevSibling());
33462     },
33463
33464     // private
33465     renderComponent : function(c){
33466         c.render(c.isLayout ? this.el : this.el.createChild());    
33467     },
33468     /**
33469      * Adds a object form elements (using the xtype property as the factory method.)
33470      * Valid xtypes are:  TextField, TextArea .... Button, Layout, FieldSet, Column
33471      * @param {Object} config 
33472      */
33473     addxtype : function(o)
33474     {
33475         // create the lement.
33476         o.form = this.form;
33477         var fe = Roo.factory(o, Roo.form);
33478         this.form.allItems.push(fe);
33479         this.stack.push(fe);
33480         
33481         if (fe.isFormField) {
33482             this.form.items.add(fe);
33483         }
33484          
33485         return fe;
33486     }
33487 });
33488
33489
33490 /**
33491  * @class Roo.form.Column
33492  * @extends Roo.form.Layout
33493  * @children Roo.form.Row Roo.form.Field Roo.Button Roo.form.TextItem Roo.form.FieldSet
33494  * Creates a column container for layout and rendering of fields in an {@link Roo.form.Form}.
33495  * @constructor
33496  * @param {Object} config Configuration options
33497  */
33498 Roo.form.Column = function(config){
33499     Roo.form.Column.superclass.constructor.call(this, config);
33500 };
33501
33502 Roo.extend(Roo.form.Column, Roo.form.Layout, {
33503     /**
33504      * @cfg {Number/String} width
33505      * The fixed width of the column in pixels or CSS value (defaults to "auto")
33506      */
33507     /**
33508      * @cfg {String/Object} autoCreate
33509      * A DomHelper element spec used to autocreate the column (defaults to {tag: 'div', cls: 'x-form-ct x-form-column'})
33510      */
33511
33512     // private
33513     defaultAutoCreate : {tag: 'div', cls: 'x-form-ct x-form-column'},
33514
33515     // private
33516     onRender : function(ct, position){
33517         Roo.form.Column.superclass.onRender.call(this, ct, position);
33518         if(this.width){
33519             this.el.setWidth(this.width);
33520         }
33521     }
33522 });
33523
33524 /**
33525  * @class Roo.form.Row
33526  * @extends Roo.form.Layout
33527  * @children Roo.form.Column Roo.form.Row Roo.form.Field Roo.Button Roo.form.TextItem Roo.form.FieldSet
33528  * Creates a row container for layout and rendering of fields in an {@link Roo.form.Form}.
33529  * @constructor
33530  * @param {Object} config Configuration options
33531  */
33532
33533  
33534 Roo.form.Row = function(config){
33535     Roo.form.Row.superclass.constructor.call(this, config);
33536 };
33537  
33538 Roo.extend(Roo.form.Row, Roo.form.Layout, {
33539       /**
33540      * @cfg {Number/String} width
33541      * The fixed width of the column in pixels or CSS value (defaults to "auto")
33542      */
33543     /**
33544      * @cfg {Number/String} height
33545      * The fixed height of the column in pixels or CSS value (defaults to "auto")
33546      */
33547     defaultAutoCreate : {tag: 'div', cls: 'x-form-ct x-form-row'},
33548     
33549     padWidth : 20,
33550     // private
33551     onRender : function(ct, position){
33552         //console.log('row render');
33553         if(!this.rowTpl){
33554             var t = new Roo.Template(
33555                 '<div class="x-form-item {5}" style="float:left;width:{6}px">',
33556                     '<label for="{0}" style="{2}">{1}{4}</label>',
33557                     '<div class="x-form-element" id="x-form-el-{0}" style="{3}">',
33558                     '</div>',
33559                 '</div>'
33560             );
33561             t.disableFormats = true;
33562             t.compile();
33563             Roo.form.Layout.prototype.rowTpl = t;
33564         }
33565         this.fieldTpl = this.rowTpl;
33566         
33567         //console.log('lw' + this.labelWidth +', la:' + this.labelAlign);
33568         var labelWidth = 100;
33569         
33570         if ((this.labelAlign != 'top')) {
33571             if (typeof this.labelWidth == 'number') {
33572                 labelWidth = this.labelWidth
33573             }
33574             this.padWidth =  20 + labelWidth;
33575             
33576         }
33577         
33578         Roo.form.Column.superclass.onRender.call(this, ct, position);
33579         if(this.width){
33580             this.el.setWidth(this.width);
33581         }
33582         if(this.height){
33583             this.el.setHeight(this.height);
33584         }
33585     },
33586     
33587     // private
33588     renderField : function(f){
33589         f.fieldEl = this.fieldTpl.append(this.el, [
33590                f.id, f.fieldLabel,
33591                f.labelStyle||this.labelStyle||'',
33592                this.elementStyle||'',
33593                typeof f.labelSeparator == 'undefined' ? this.labelSeparator : f.labelSeparator,
33594                f.itemCls||this.itemCls||'',
33595                f.width ? f.width + this.padWidth : 160 + this.padWidth
33596        ],true);
33597     }
33598 });
33599  
33600
33601 /**
33602  * @class Roo.form.FieldSet
33603  * @extends Roo.form.Layout
33604  * @children Roo.form.Column Roo.form.Row Roo.form.Field Roo.Button Roo.form.TextItem
33605  * Creates a fieldset container for layout and rendering of fields in an {@link Roo.form.Form}.
33606  * @constructor
33607  * @param {Object} config Configuration options
33608  */
33609 Roo.form.FieldSet = function(config){
33610     Roo.form.FieldSet.superclass.constructor.call(this, config);
33611 };
33612
33613 Roo.extend(Roo.form.FieldSet, Roo.form.Layout, {
33614     /**
33615      * @cfg {String} legend
33616      * The text to display as the legend for the FieldSet (defaults to '')
33617      */
33618     /**
33619      * @cfg {String/Object} autoCreate
33620      * A DomHelper element spec used to autocreate the fieldset (defaults to {tag: 'fieldset', cn: {tag:'legend'}})
33621      */
33622
33623     // private
33624     defaultAutoCreate : {tag: 'fieldset', cn: {tag:'legend'}},
33625
33626     // private
33627     onRender : function(ct, position){
33628         Roo.form.FieldSet.superclass.onRender.call(this, ct, position);
33629         if(this.legend){
33630             this.setLegend(this.legend);
33631         }
33632     },
33633
33634     // private
33635     setLegend : function(text){
33636         if(this.rendered){
33637             this.el.child('legend').update(text);
33638         }
33639     }
33640 });/*
33641  * Based on:
33642  * Ext JS Library 1.1.1
33643  * Copyright(c) 2006-2007, Ext JS, LLC.
33644  *
33645  * Originally Released Under LGPL - original licence link has changed is not relivant.
33646  *
33647  * Fork - LGPL
33648  * <script type="text/javascript">
33649  */
33650 /**
33651  * @class Roo.form.VTypes
33652  * Overridable validation definitions. The validations provided are basic and intended to be easily customizable and extended.
33653  * @static
33654  */
33655 Roo.form.VTypes = function(){
33656     // closure these in so they are only created once.
33657     var alpha = /^[a-zA-Z_]+$/;
33658     var alphanum = /^[a-zA-Z0-9_]+$/;
33659     var email = /^([\w'-]+)(\.[\w'-]+)*@([\w-]+\.){1,5}([A-Za-z]){2,24}$/;
33660     var url = /^(((https?)|(ftp)):\/\/([\-\w]+\.)+\w{2,3}(\/[%\-\w]+(\.\w{2,})?)*(([\w\-\.\?\\\/+@&#;`~=%!]*)(\.\w{2,})?)*\/?)/i;
33661     var urlWeb = /^((https?):\/\/([\-\w]+\.)+\w{2,3}(\/[%\-\w]+(\.\w{2,})?)*(([\w\-\.\?\\\/+@&#;`~=%!]*)(\.\w{2,})?)*\/?)/i;
33662
33663     // All these messages and functions are configurable
33664     return {
33665         /**
33666          * The function used to validate email addresses
33667          * @param {String} value The email address
33668          */
33669         email : function(v){
33670             return email.test(v);
33671         },
33672         /**
33673          * The error text to display when the email validation function returns false
33674          * @type String
33675          */
33676         emailText : 'This field should be an e-mail address in the format "user@domain.com"',
33677         /**
33678          * The keystroke filter mask to be applied on email input
33679          * @type RegExp
33680          */
33681         emailMask : /[a-z0-9_\.\-@]/i,
33682
33683         /**
33684          * The function used to validate URLs
33685          * @param {String} value The URL
33686          */
33687         url : function(v){
33688             return url.test(v);
33689         },
33690         /**
33691          * The funciton used to validate URLs (only allow schemes 'https' and 'http')
33692          * @param {String} v The URL
33693          */
33694         urlWeb : function(v) {
33695             return urlWeb.test(v);
33696         },
33697         /**
33698          * The error text to display when the url validation function returns false
33699          * @type String
33700          */
33701         urlText : 'This field should be a URL in the format "http:/'+'/www.domain.com"',
33702         
33703         /**
33704          * The function used to validate alpha values
33705          * @param {String} value The value
33706          */
33707         alpha : function(v){
33708             return alpha.test(v);
33709         },
33710         /**
33711          * The error text to display when the alpha validation function returns false
33712          * @type String
33713          */
33714         alphaText : 'This field should only contain letters and _',
33715         /**
33716          * The keystroke filter mask to be applied on alpha input
33717          * @type RegExp
33718          */
33719         alphaMask : /[a-z_]/i,
33720
33721         /**
33722          * The function used to validate alphanumeric values
33723          * @param {String} value The value
33724          */
33725         alphanum : function(v){
33726             return alphanum.test(v);
33727         },
33728         /**
33729          * The error text to display when the alphanumeric validation function returns false
33730          * @type String
33731          */
33732         alphanumText : 'This field should only contain letters, numbers and _',
33733         /**
33734          * The keystroke filter mask to be applied on alphanumeric input
33735          * @type RegExp
33736          */
33737         alphanumMask : /[a-z0-9_]/i
33738     };
33739 }();//<script type="text/javascript">
33740
33741 /**
33742  * @class Roo.form.FCKeditor
33743  * @extends Roo.form.TextArea
33744  * Wrapper around the FCKEditor http://www.fckeditor.net
33745  * @constructor
33746  * Creates a new FCKeditor
33747  * @param {Object} config Configuration options
33748  */
33749 Roo.form.FCKeditor = function(config){
33750     Roo.form.FCKeditor.superclass.constructor.call(this, config);
33751     this.addEvents({
33752          /**
33753          * @event editorinit
33754          * Fired when the editor is initialized - you can add extra handlers here..
33755          * @param {FCKeditor} this
33756          * @param {Object} the FCK object.
33757          */
33758         editorinit : true
33759     });
33760     
33761     
33762 };
33763 Roo.form.FCKeditor.editors = { };
33764 Roo.extend(Roo.form.FCKeditor, Roo.form.TextArea,
33765 {
33766     //defaultAutoCreate : {
33767     //    tag : "textarea",style   : "width:100px;height:60px;" ,autocomplete    : "off"
33768     //},
33769     // private
33770     /**
33771      * @cfg {Object} fck options - see fck manual for details.
33772      */
33773     fckconfig : false,
33774     
33775     /**
33776      * @cfg {Object} fck toolbar set (Basic or Default)
33777      */
33778     toolbarSet : 'Basic',
33779     /**
33780      * @cfg {Object} fck BasePath
33781      */ 
33782     basePath : '/fckeditor/',
33783     
33784     
33785     frame : false,
33786     
33787     value : '',
33788     
33789    
33790     onRender : function(ct, position)
33791     {
33792         if(!this.el){
33793             this.defaultAutoCreate = {
33794                 tag: "textarea",
33795                 style:"width:300px;height:60px;",
33796                 autocomplete: "new-password"
33797             };
33798         }
33799         Roo.form.FCKeditor.superclass.onRender.call(this, ct, position);
33800         /*
33801         if(this.grow){
33802             this.textSizeEl = Roo.DomHelper.append(document.body, {tag: "pre", cls: "x-form-grow-sizer"});
33803             if(this.preventScrollbars){
33804                 this.el.setStyle("overflow", "hidden");
33805             }
33806             this.el.setHeight(this.growMin);
33807         }
33808         */
33809         //console.log('onrender' + this.getId() );
33810         Roo.form.FCKeditor.editors[this.getId()] = this;
33811          
33812
33813         this.replaceTextarea() ;
33814         
33815     },
33816     
33817     getEditor : function() {
33818         return this.fckEditor;
33819     },
33820     /**
33821      * Sets a data value into the field and validates it.  To set the value directly without validation see {@link #setRawValue}.
33822      * @param {Mixed} value The value to set
33823      */
33824     
33825     
33826     setValue : function(value)
33827     {
33828         //console.log('setValue: ' + value);
33829         
33830         if(typeof(value) == 'undefined') { // not sure why this is happending...
33831             return;
33832         }
33833         Roo.form.FCKeditor.superclass.setValue.apply(this,[value]);
33834         
33835         //if(!this.el || !this.getEditor()) {
33836         //    this.value = value;
33837             //this.setValue.defer(100,this,[value]);    
33838         //    return;
33839         //} 
33840         
33841         if(!this.getEditor()) {
33842             return;
33843         }
33844         
33845         this.getEditor().SetData(value);
33846         
33847         //
33848
33849     },
33850
33851     /**
33852      * Returns the normalized data value (undefined or emptyText will be returned as '').  To return the raw value see {@link #getRawValue}.
33853      * @return {Mixed} value The field value
33854      */
33855     getValue : function()
33856     {
33857         
33858         if (this.frame && this.frame.dom.style.display == 'none') {
33859             return Roo.form.FCKeditor.superclass.getValue.call(this);
33860         }
33861         
33862         if(!this.el || !this.getEditor()) {
33863            
33864            // this.getValue.defer(100,this); 
33865             return this.value;
33866         }
33867        
33868         
33869         var value=this.getEditor().GetData();
33870         Roo.form.FCKeditor.superclass.setValue.apply(this,[value]);
33871         return Roo.form.FCKeditor.superclass.getValue.call(this);
33872         
33873
33874     },
33875
33876     /**
33877      * Returns the raw data value which may or may not be a valid, defined value.  To return a normalized value see {@link #getValue}.
33878      * @return {Mixed} value The field value
33879      */
33880     getRawValue : function()
33881     {
33882         if (this.frame && this.frame.dom.style.display == 'none') {
33883             return Roo.form.FCKeditor.superclass.getRawValue.call(this);
33884         }
33885         
33886         if(!this.el || !this.getEditor()) {
33887             //this.getRawValue.defer(100,this); 
33888             return this.value;
33889             return;
33890         }
33891         
33892         
33893         
33894         var value=this.getEditor().GetData();
33895         Roo.form.FCKeditor.superclass.setRawValue.apply(this,[value]);
33896         return Roo.form.FCKeditor.superclass.getRawValue.call(this);
33897          
33898     },
33899     
33900     setSize : function(w,h) {
33901         
33902         
33903         
33904         //if (this.frame && this.frame.dom.style.display == 'none') {
33905         //    Roo.form.FCKeditor.superclass.setSize.apply(this, [w, h]);
33906         //    return;
33907         //}
33908         //if(!this.el || !this.getEditor()) {
33909         //    this.setSize.defer(100,this, [w,h]); 
33910         //    return;
33911         //}
33912         
33913         
33914         
33915         Roo.form.FCKeditor.superclass.setSize.apply(this, [w, h]);
33916         
33917         this.frame.dom.setAttribute('width', w);
33918         this.frame.dom.setAttribute('height', h);
33919         this.frame.setSize(w,h);
33920         
33921     },
33922     
33923     toggleSourceEdit : function(value) {
33924         
33925       
33926          
33927         this.el.dom.style.display = value ? '' : 'none';
33928         this.frame.dom.style.display = value ?  'none' : '';
33929         
33930     },
33931     
33932     
33933     focus: function(tag)
33934     {
33935         if (this.frame.dom.style.display == 'none') {
33936             return Roo.form.FCKeditor.superclass.focus.call(this);
33937         }
33938         if(!this.el || !this.getEditor()) {
33939             this.focus.defer(100,this, [tag]); 
33940             return;
33941         }
33942         
33943         
33944         
33945         
33946         var tgs = this.getEditor().EditorDocument.getElementsByTagName(tag);
33947         this.getEditor().Focus();
33948         if (tgs.length) {
33949             if (!this.getEditor().Selection.GetSelection()) {
33950                 this.focus.defer(100,this, [tag]); 
33951                 return;
33952             }
33953             
33954             
33955             var r = this.getEditor().EditorDocument.createRange();
33956             r.setStart(tgs[0],0);
33957             r.setEnd(tgs[0],0);
33958             this.getEditor().Selection.GetSelection().removeAllRanges();
33959             this.getEditor().Selection.GetSelection().addRange(r);
33960             this.getEditor().Focus();
33961         }
33962         
33963     },
33964     
33965     
33966     
33967     replaceTextarea : function()
33968     {
33969         if ( document.getElementById( this.getId() + '___Frame' ) ) {
33970             return ;
33971         }
33972         //if ( !this.checkBrowser || this._isCompatibleBrowser() )
33973         //{
33974             // We must check the elements firstly using the Id and then the name.
33975         var oTextarea = document.getElementById( this.getId() );
33976         
33977         var colElementsByName = document.getElementsByName( this.getId() ) ;
33978          
33979         oTextarea.style.display = 'none' ;
33980
33981         if ( oTextarea.tabIndex ) {            
33982             this.TabIndex = oTextarea.tabIndex ;
33983         }
33984         
33985         this._insertHtmlBefore( this._getConfigHtml(), oTextarea ) ;
33986         this._insertHtmlBefore( this._getIFrameHtml(), oTextarea ) ;
33987         this.frame = Roo.get(this.getId() + '___Frame')
33988     },
33989     
33990     _getConfigHtml : function()
33991     {
33992         var sConfig = '' ;
33993
33994         for ( var o in this.fckconfig ) {
33995             sConfig += sConfig.length > 0  ? '&amp;' : '';
33996             sConfig += encodeURIComponent( o ) + '=' + encodeURIComponent( this.fckconfig[o] ) ;
33997         }
33998
33999         return '<input type="hidden" id="' + this.getId() + '___Config" value="' + sConfig + '" style="display:none" />' ;
34000     },
34001     
34002     
34003     _getIFrameHtml : function()
34004     {
34005         var sFile = 'fckeditor.html' ;
34006         /* no idea what this is about..
34007         try
34008         {
34009             if ( (/fcksource=true/i).test( window.top.location.search ) )
34010                 sFile = 'fckeditor.original.html' ;
34011         }
34012         catch (e) { 
34013         */
34014
34015         var sLink = this.basePath + 'editor/' + sFile + '?InstanceName=' + encodeURIComponent( this.getId() ) ;
34016         sLink += this.toolbarSet ? ( '&amp;Toolbar=' + this.toolbarSet)  : '';
34017         
34018         
34019         var html = '<iframe id="' + this.getId() +
34020             '___Frame" src="' + sLink +
34021             '" width="' + this.width +
34022             '" height="' + this.height + '"' +
34023             (this.tabIndex ?  ' tabindex="' + this.tabIndex + '"' :'' ) +
34024             ' frameborder="0" scrolling="no"></iframe>' ;
34025
34026         return html ;
34027     },
34028     
34029     _insertHtmlBefore : function( html, element )
34030     {
34031         if ( element.insertAdjacentHTML )       {
34032             // IE
34033             element.insertAdjacentHTML( 'beforeBegin', html ) ;
34034         } else { // Gecko
34035             var oRange = document.createRange() ;
34036             oRange.setStartBefore( element ) ;
34037             var oFragment = oRange.createContextualFragment( html );
34038             element.parentNode.insertBefore( oFragment, element ) ;
34039         }
34040     }
34041     
34042     
34043   
34044     
34045     
34046     
34047     
34048
34049 });
34050
34051 //Roo.reg('fckeditor', Roo.form.FCKeditor);
34052
34053 function FCKeditor_OnComplete(editorInstance){
34054     var f = Roo.form.FCKeditor.editors[editorInstance.Name];
34055     f.fckEditor = editorInstance;
34056     //console.log("loaded");
34057     f.fireEvent('editorinit', f, editorInstance);
34058
34059   
34060
34061  
34062
34063
34064
34065
34066
34067
34068
34069
34070
34071
34072
34073
34074
34075
34076
34077 //<script type="text/javascript">
34078 /**
34079  * @class Roo.form.GridField
34080  * @extends Roo.form.Field
34081  * Embed a grid (or editable grid into a form)
34082  * STATUS ALPHA
34083  * 
34084  * This embeds a grid in a form, the value of the field should be the json encoded array of rows
34085  * it needs 
34086  * xgrid.store = Roo.data.Store
34087  * xgrid.store.proxy = Roo.data.MemoryProxy (data = [] )
34088  * xgrid.store.reader = Roo.data.JsonReader 
34089  * 
34090  * 
34091  * @constructor
34092  * Creates a new GridField
34093  * @param {Object} config Configuration options
34094  */
34095 Roo.form.GridField = function(config){
34096     Roo.form.GridField.superclass.constructor.call(this, config);
34097      
34098 };
34099
34100 Roo.extend(Roo.form.GridField, Roo.form.Field,  {
34101     /**
34102      * @cfg {Number} width  - used to restrict width of grid..
34103      */
34104     width : 100,
34105     /**
34106      * @cfg {Number} height - used to restrict height of grid..
34107      */
34108     height : 50,
34109      /**
34110      * @cfg {Object} xgrid (xtype'd description of grid) { xtype : 'Grid', dataSource: .... }
34111          * 
34112          *}
34113      */
34114     xgrid : false, 
34115     /**
34116      * @cfg {String/Object} autoCreate A DomHelper element spec, or true for a default element spec (defaults to
34117      * {tag: "input", type: "checkbox", autocomplete: "off"})
34118      */
34119    // defaultAutoCreate : { tag: 'div' },
34120     defaultAutoCreate : { tag: 'input', type: 'hidden', autocomplete: 'new-password'},
34121     /**
34122      * @cfg {String} addTitle Text to include for adding a title.
34123      */
34124     addTitle : false,
34125     //
34126     onResize : function(){
34127         Roo.form.Field.superclass.onResize.apply(this, arguments);
34128     },
34129
34130     initEvents : function(){
34131         // Roo.form.Checkbox.superclass.initEvents.call(this);
34132         // has no events...
34133        
34134     },
34135
34136
34137     getResizeEl : function(){
34138         return this.wrap;
34139     },
34140
34141     getPositionEl : function(){
34142         return this.wrap;
34143     },
34144
34145     // private
34146     onRender : function(ct, position){
34147         
34148         this.style = this.style || 'overflow: hidden; border:1px solid #c3daf9;';
34149         var style = this.style;
34150         delete this.style;
34151         
34152         Roo.form.GridField.superclass.onRender.call(this, ct, position);
34153         this.wrap = this.el.wrap({cls: ''}); // not sure why ive done thsi...
34154         this.viewEl = this.wrap.createChild({ tag: 'div' });
34155         if (style) {
34156             this.viewEl.applyStyles(style);
34157         }
34158         if (this.width) {
34159             this.viewEl.setWidth(this.width);
34160         }
34161         if (this.height) {
34162             this.viewEl.setHeight(this.height);
34163         }
34164         //if(this.inputValue !== undefined){
34165         //this.setValue(this.value);
34166         
34167         
34168         this.grid = new Roo.grid[this.xgrid.xtype](this.viewEl, this.xgrid);
34169         
34170         
34171         this.grid.render();
34172         this.grid.getDataSource().on('remove', this.refreshValue, this);
34173         this.grid.getDataSource().on('update', this.refreshValue, this);
34174         this.grid.on('afteredit', this.refreshValue, this);
34175  
34176     },
34177      
34178     
34179     /**
34180      * Sets the value of the item. 
34181      * @param {String} either an object  or a string..
34182      */
34183     setValue : function(v){
34184         //this.value = v;
34185         v = v || []; // empty set..
34186         // this does not seem smart - it really only affects memoryproxy grids..
34187         if (this.grid && this.grid.getDataSource() && typeof(v) != 'undefined') {
34188             var ds = this.grid.getDataSource();
34189             // assumes a json reader..
34190             var data = {}
34191             data[ds.reader.meta.root ] =  typeof(v) == 'string' ? Roo.decode(v) : v;
34192             ds.loadData( data);
34193         }
34194         // clear selection so it does not get stale.
34195         if (this.grid.sm) { 
34196             this.grid.sm.clearSelections();
34197         }
34198         
34199         Roo.form.GridField.superclass.setValue.call(this, v);
34200         this.refreshValue();
34201         // should load data in the grid really....
34202     },
34203     
34204     // private
34205     refreshValue: function() {
34206          var val = [];
34207         this.grid.getDataSource().each(function(r) {
34208             val.push(r.data);
34209         });
34210         this.el.dom.value = Roo.encode(val);
34211     }
34212     
34213      
34214     
34215     
34216 });/*
34217  * Based on:
34218  * Ext JS Library 1.1.1
34219  * Copyright(c) 2006-2007, Ext JS, LLC.
34220  *
34221  * Originally Released Under LGPL - original licence link has changed is not relivant.
34222  *
34223  * Fork - LGPL
34224  * <script type="text/javascript">
34225  */
34226 /**
34227  * @class Roo.form.DisplayField
34228  * @extends Roo.form.Field
34229  * A generic Field to display non-editable data.
34230  * @cfg {Boolean} closable (true|false) default false
34231  * @constructor
34232  * Creates a new Display Field item.
34233  * @param {Object} config Configuration options
34234  */
34235 Roo.form.DisplayField = function(config){
34236     Roo.form.DisplayField.superclass.constructor.call(this, config);
34237     
34238     this.addEvents({
34239         /**
34240          * @event close
34241          * Fires after the click the close btn
34242              * @param {Roo.form.DisplayField} this
34243              */
34244         close : true
34245     });
34246 };
34247
34248 Roo.extend(Roo.form.DisplayField, Roo.form.TextField,  {
34249     inputType:      'hidden',
34250     allowBlank:     true,
34251     readOnly:         true,
34252     
34253  
34254     /**
34255      * @cfg {String} focusClass The CSS class to use when the checkbox receives focus (defaults to undefined)
34256      */
34257     focusClass : undefined,
34258     /**
34259      * @cfg {String} fieldClass The default CSS class for the checkbox (defaults to "x-form-field")
34260      */
34261     fieldClass: 'x-form-field',
34262     
34263      /**
34264      * @cfg {Function} valueRenderer The renderer for the field (so you can reformat output). should return raw HTML
34265      */
34266     valueRenderer: undefined,
34267     
34268     width: 100,
34269     /**
34270      * @cfg {String/Object} autoCreate A DomHelper element spec, or true for a default element spec (defaults to
34271      * {tag: "input", type: "checkbox", autocomplete: "off"})
34272      */
34273      
34274  //   defaultAutoCreate : { tag: 'input', type: 'hidden', autocomplete: 'off'},
34275  
34276     closable : false,
34277     
34278     onResize : function(){
34279         Roo.form.DisplayField.superclass.onResize.apply(this, arguments);
34280         
34281     },
34282
34283     initEvents : function(){
34284         // Roo.form.Checkbox.superclass.initEvents.call(this);
34285         // has no events...
34286         
34287         if(this.closable){
34288             this.closeEl.on('click', this.onClose, this);
34289         }
34290        
34291     },
34292
34293
34294     getResizeEl : function(){
34295         return this.wrap;
34296     },
34297
34298     getPositionEl : function(){
34299         return this.wrap;
34300     },
34301
34302     // private
34303     onRender : function(ct, position){
34304         
34305         Roo.form.DisplayField.superclass.onRender.call(this, ct, position);
34306         //if(this.inputValue !== undefined){
34307         this.wrap = this.el.wrap();
34308         
34309         this.viewEl = this.wrap.createChild({ tag: 'div', cls: 'x-form-displayfield'});
34310         
34311         if(this.closable){
34312             this.closeEl = this.wrap.createChild({ tag: 'div', cls: 'x-dlg-close'});
34313         }
34314         
34315         if (this.bodyStyle) {
34316             this.viewEl.applyStyles(this.bodyStyle);
34317         }
34318         //this.viewEl.setStyle('padding', '2px');
34319         
34320         this.setValue(this.value);
34321         
34322     },
34323 /*
34324     // private
34325     initValue : Roo.emptyFn,
34326
34327   */
34328
34329         // private
34330     onClick : function(){
34331         
34332     },
34333
34334     /**
34335      * Sets the checked state of the checkbox.
34336      * @param {Boolean/String} checked True, 'true', '1', or 'on' to check the checkbox, any other value will uncheck it.
34337      */
34338     setValue : function(v){
34339         this.value = v;
34340         var html = this.valueRenderer ?  this.valueRenderer(v) : String.format('{0}', v);
34341         // this might be called before we have a dom element..
34342         if (!this.viewEl) {
34343             return;
34344         }
34345         this.viewEl.dom.innerHTML = html;
34346         Roo.form.DisplayField.superclass.setValue.call(this, v);
34347
34348     },
34349     
34350     onClose : function(e)
34351     {
34352         e.preventDefault();
34353         
34354         this.fireEvent('close', this);
34355     }
34356 });/*
34357  * 
34358  * Licence- LGPL
34359  * 
34360  */
34361
34362 /**
34363  * @class Roo.form.DayPicker
34364  * @extends Roo.form.Field
34365  * A Day picker show [M] [T] [W] ....
34366  * @constructor
34367  * Creates a new Day Picker
34368  * @param {Object} config Configuration options
34369  */
34370 Roo.form.DayPicker= function(config){
34371     Roo.form.DayPicker.superclass.constructor.call(this, config);
34372      
34373 };
34374
34375 Roo.extend(Roo.form.DayPicker, Roo.form.Field,  {
34376     /**
34377      * @cfg {String} focusClass The CSS class to use when the checkbox receives focus (defaults to undefined)
34378      */
34379     focusClass : undefined,
34380     /**
34381      * @cfg {String} fieldClass The default CSS class for the checkbox (defaults to "x-form-field")
34382      */
34383     fieldClass: "x-form-field",
34384    
34385     /**
34386      * @cfg {String/Object} autoCreate A DomHelper element spec, or true for a default element spec (defaults to
34387      * {tag: "input", type: "checkbox", autocomplete: "off"})
34388      */
34389     defaultAutoCreate : { tag: "input", type: 'hidden', autocomplete: "new-password"},
34390     
34391    
34392     actionMode : 'viewEl', 
34393     //
34394     // private
34395  
34396     inputType : 'hidden',
34397     
34398      
34399     inputElement: false, // real input element?
34400     basedOn: false, // ????
34401     
34402     isFormField: true, // not sure where this is needed!!!!
34403
34404     onResize : function(){
34405         Roo.form.Checkbox.superclass.onResize.apply(this, arguments);
34406         if(!this.boxLabel){
34407             this.el.alignTo(this.wrap, 'c-c');
34408         }
34409     },
34410
34411     initEvents : function(){
34412         Roo.form.Checkbox.superclass.initEvents.call(this);
34413         this.el.on("click", this.onClick,  this);
34414         this.el.on("change", this.onClick,  this);
34415     },
34416
34417
34418     getResizeEl : function(){
34419         return this.wrap;
34420     },
34421
34422     getPositionEl : function(){
34423         return this.wrap;
34424     },
34425
34426     
34427     // private
34428     onRender : function(ct, position){
34429         Roo.form.Checkbox.superclass.onRender.call(this, ct, position);
34430        
34431         this.wrap = this.el.wrap({cls: 'x-form-daypick-item '});
34432         
34433         var r1 = '<table><tr>';
34434         var r2 = '<tr class="x-form-daypick-icons">';
34435         for (var i=0; i < 7; i++) {
34436             r1+= '<td><div>' + Date.dayNames[i].substring(0,3) + '</div></td>';
34437             r2+= '<td><img class="x-menu-item-icon" src="' + Roo.BLANK_IMAGE_URL  +'"></td>';
34438         }
34439         
34440         var viewEl = this.wrap.createChild( r1 + '</tr>' + r2 + '</tr></table>');
34441         viewEl.select('img').on('click', this.onClick, this);
34442         this.viewEl = viewEl;   
34443         
34444         
34445         // this will not work on Chrome!!!
34446         this.el.on('DOMAttrModified', this.setFromHidden,  this); //ff
34447         this.el.on('propertychange', this.setFromHidden,  this);  //ie
34448         
34449         
34450           
34451
34452     },
34453
34454     // private
34455     initValue : Roo.emptyFn,
34456
34457     /**
34458      * Returns the checked state of the checkbox.
34459      * @return {Boolean} True if checked, else false
34460      */
34461     getValue : function(){
34462         return this.el.dom.value;
34463         
34464     },
34465
34466         // private
34467     onClick : function(e){ 
34468         //this.setChecked(!this.checked);
34469         Roo.get(e.target).toggleClass('x-menu-item-checked');
34470         this.refreshValue();
34471         //if(this.el.dom.checked != this.checked){
34472         //    this.setValue(this.el.dom.checked);
34473        // }
34474     },
34475     
34476     // private
34477     refreshValue : function()
34478     {
34479         var val = '';
34480         this.viewEl.select('img',true).each(function(e,i,n)  {
34481             val += e.is(".x-menu-item-checked") ? String(n) : '';
34482         });
34483         this.setValue(val, true);
34484     },
34485
34486     /**
34487      * Sets the checked state of the checkbox.
34488      * On is always based on a string comparison between inputValue and the param.
34489      * @param {Boolean/String} value - the value to set 
34490      * @param {Boolean/String} suppressEvent - whether to suppress the checkchange event.
34491      */
34492     setValue : function(v,suppressEvent){
34493         if (!this.el.dom) {
34494             return;
34495         }
34496         var old = this.el.dom.value ;
34497         this.el.dom.value = v;
34498         if (suppressEvent) {
34499             return ;
34500         }
34501          
34502         // update display..
34503         this.viewEl.select('img',true).each(function(e,i,n)  {
34504             
34505             var on = e.is(".x-menu-item-checked");
34506             var newv = v.indexOf(String(n)) > -1;
34507             if (on != newv) {
34508                 e.toggleClass('x-menu-item-checked');
34509             }
34510             
34511         });
34512         
34513         
34514         this.fireEvent('change', this, v, old);
34515         
34516         
34517     },
34518    
34519     // handle setting of hidden value by some other method!!?!?
34520     setFromHidden: function()
34521     {
34522         if(!this.el){
34523             return;
34524         }
34525         //console.log("SET FROM HIDDEN");
34526         //alert('setFrom hidden');
34527         this.setValue(this.el.dom.value);
34528     },
34529     
34530     onDestroy : function()
34531     {
34532         if(this.viewEl){
34533             Roo.get(this.viewEl).remove();
34534         }
34535          
34536         Roo.form.DayPicker.superclass.onDestroy.call(this);
34537     }
34538
34539 });/*
34540  * RooJS Library 1.1.1
34541  * Copyright(c) 2008-2011  Alan Knowles
34542  *
34543  * License - LGPL
34544  */
34545  
34546
34547 /**
34548  * @class Roo.form.ComboCheck
34549  * @extends Roo.form.ComboBox
34550  * A combobox for multiple select items.
34551  *
34552  * FIXME - could do with a reset button..
34553  * 
34554  * @constructor
34555  * Create a new ComboCheck
34556  * @param {Object} config Configuration options
34557  */
34558 Roo.form.ComboCheck = function(config){
34559     Roo.form.ComboCheck.superclass.constructor.call(this, config);
34560     // should verify some data...
34561     // like
34562     // hiddenName = required..
34563     // displayField = required
34564     // valudField == required
34565     var req= [ 'hiddenName', 'displayField', 'valueField' ];
34566     var _t = this;
34567     Roo.each(req, function(e) {
34568         if ((typeof(_t[e]) == 'undefined' ) || !_t[e].length) {
34569             throw "Roo.form.ComboCheck : missing value for: " + e;
34570         }
34571     });
34572     
34573     
34574 };
34575
34576 Roo.extend(Roo.form.ComboCheck, Roo.form.ComboBox, {
34577      
34578      
34579     editable : false,
34580      
34581     selectedClass: 'x-menu-item-checked', 
34582     
34583     // private
34584     onRender : function(ct, position){
34585         var _t = this;
34586         
34587         
34588         
34589         if(!this.tpl){
34590             var cls = 'x-combo-list';
34591
34592             
34593             this.tpl =  new Roo.Template({
34594                 html :  '<div class="'+cls+'-item x-menu-check-item">' +
34595                    '<img class="x-menu-item-icon" style="margin: 0px;" src="' + Roo.BLANK_IMAGE_URL + '">' + 
34596                    '<span>{' + this.displayField + '}</span>' +
34597                     '</div>' 
34598                 
34599             });
34600         }
34601  
34602         
34603         Roo.form.ComboCheck.superclass.onRender.call(this, ct, position);
34604         this.view.singleSelect = false;
34605         this.view.multiSelect = true;
34606         this.view.toggleSelect = true;
34607         this.pageTb.add(new Roo.Toolbar.Fill(),{
34608             
34609             text: 'Select All',
34610             handler: function() {
34611                 _t.selectAll();
34612             }
34613         },
34614         {
34615             text: 'Done',
34616             handler: function() {
34617                 _t.collapse();
34618             }
34619         });
34620     },
34621     
34622     cleanLeadingSpace : function(e)
34623     {
34624         // this is disabled, as it retriggers setvalue on blur
34625         return;
34626     },
34627     doForce : function() {
34628         // no idea what this did, but it blanks out our values.
34629         return;
34630     },
34631     onViewOver : function(e, t){
34632         // do nothing...
34633         return;
34634         
34635     },
34636     
34637     onViewClick : function(doFocus,index){
34638         return;
34639         
34640     },
34641     select: function () {
34642         //Roo.log("SELECT CALLED");
34643     },
34644      
34645     selectByValue : function(xv, scrollIntoView){
34646         var ar = this.getValueArray();
34647         var sels = [];
34648         
34649         Roo.each(ar, function(v) {
34650             if(v === undefined || v === null){
34651                 return;
34652             }
34653             var r = this.findRecord(this.valueField, v);
34654             if(r){
34655                 sels.push(this.store.indexOf(r))
34656                 
34657             }
34658         },this);
34659         this.view.select(sels);
34660         return false;
34661     },
34662     
34663     selectAll : function()
34664     {
34665         var sels = [];
34666         this.store.each(function(r,i) {
34667             sels.push(i);
34668         });
34669         this.view.select(sels);
34670         this.collapse();
34671         return false;
34672
34673     },
34674     
34675     onSelect : function(record, index){
34676        // Roo.log("onselect Called");
34677        // this is only called by the clear button now..
34678         this.view.clearSelections();
34679         this.setValue('[]');
34680         if (this.value != this.valueBefore) {
34681             this.fireEvent('change', this, this.value, this.valueBefore);
34682             this.valueBefore = this.value;
34683         }
34684     },
34685     getValueArray : function()
34686     {
34687         var ar = [] ;
34688         
34689         try {
34690             //Roo.log(this.value);
34691             if (typeof(this.value) == 'undefined') {
34692                 return [];
34693             }
34694             var ar = Roo.decode(this.value);
34695             return  ar instanceof Array ? ar : []; //?? valid?
34696             
34697         } catch(e) {
34698             Roo.log(e + "\nRoo.form.ComboCheck:getValueArray  invalid data:" + this.getValue());
34699             return [];
34700         }
34701          
34702     },
34703     expand : function ()
34704     {
34705         
34706         Roo.form.ComboCheck.superclass.expand.call(this);
34707         this.valueBefore = typeof(this.value) == 'undefined' ? '' : this.value;
34708         //this.valueBefore = typeof(this.valueBefore) == 'undefined' ? '' : this.valueBefore;
34709         
34710
34711     },
34712     
34713     collapse : function(){
34714         Roo.form.ComboCheck.superclass.collapse.call(this);
34715         var sl = this.view.getSelectedIndexes();
34716         var st = this.store;
34717         var nv = [];
34718         var tv = [];
34719         var r;
34720         Roo.each(sl, function(i) {
34721             r = st.getAt(i);
34722             nv.push(r.get(this.valueField));
34723         },this);
34724         this.setValue(Roo.encode(nv));
34725         if (this.value != this.valueBefore) {
34726
34727             this.fireEvent('change', this, this.value, this.valueBefore);
34728             this.valueBefore = this.value;
34729         }
34730         
34731     },
34732     
34733     setValue : function(v){
34734         // Roo.log(v);
34735         this.value = v;
34736         
34737         var vals = this.getValueArray();
34738         var tv = [];
34739         Roo.each(vals, function(k) {
34740             var r = this.findRecord(this.valueField, k);
34741             if(r){
34742                 tv.push(r.data[this.displayField]);
34743             }else if(this.valueNotFoundText !== undefined){
34744                 tv.push( this.valueNotFoundText );
34745             }
34746         },this);
34747        // Roo.log(tv);
34748         
34749         Roo.form.ComboBox.superclass.setValue.call(this, tv.join(', '));
34750         this.hiddenField.value = v;
34751         this.value = v;
34752     }
34753     
34754 });/*
34755  * Based on:
34756  * Ext JS Library 1.1.1
34757  * Copyright(c) 2006-2007, Ext JS, LLC.
34758  *
34759  * Originally Released Under LGPL - original licence link has changed is not relivant.
34760  *
34761  * Fork - LGPL
34762  * <script type="text/javascript">
34763  */
34764  
34765 /**
34766  * @class Roo.form.Signature
34767  * @extends Roo.form.Field
34768  * Signature field.  
34769  * @constructor
34770  * 
34771  * @param {Object} config Configuration options
34772  */
34773
34774 Roo.form.Signature = function(config){
34775     Roo.form.Signature.superclass.constructor.call(this, config);
34776     
34777     this.addEvents({// not in used??
34778          /**
34779          * @event confirm
34780          * Fires when the 'confirm' icon is pressed (add a listener to enable add button)
34781              * @param {Roo.form.Signature} combo This combo box
34782              */
34783         'confirm' : true,
34784         /**
34785          * @event reset
34786          * Fires when the 'edit' icon is pressed (add a listener to enable add button)
34787              * @param {Roo.form.ComboBox} combo This combo box
34788              * @param {Roo.data.Record|false} record The data record returned from the underlying store (or false on nothing selected)
34789              */
34790         'reset' : true
34791     });
34792 };
34793
34794 Roo.extend(Roo.form.Signature, Roo.form.Field,  {
34795     /**
34796      * @cfg {Object} labels Label to use when rendering a form.
34797      * defaults to 
34798      * labels : { 
34799      *      clear : "Clear",
34800      *      confirm : "Confirm"
34801      *  }
34802      */
34803     labels : { 
34804         clear : "Clear",
34805         confirm : "Confirm"
34806     },
34807     /**
34808      * @cfg {Number} width The signature panel width (defaults to 300)
34809      */
34810     width: 300,
34811     /**
34812      * @cfg {Number} height The signature panel height (defaults to 100)
34813      */
34814     height : 100,
34815     /**
34816      * @cfg {Boolean} allowBlank False to validate that the value length > 0 (defaults to false)
34817      */
34818     allowBlank : false,
34819     
34820     //private
34821     // {Object} signPanel The signature SVG panel element (defaults to {})
34822     signPanel : {},
34823     // {Boolean} isMouseDown False to validate that the mouse down event (defaults to false)
34824     isMouseDown : false,
34825     // {Boolean} isConfirmed validate the signature is confirmed or not for submitting form (defaults to false)
34826     isConfirmed : false,
34827     // {String} signatureTmp SVG mapping string (defaults to empty string)
34828     signatureTmp : '',
34829     
34830     
34831     defaultAutoCreate : { // modified by initCompnoent..
34832         tag: "input",
34833         type:"hidden"
34834     },
34835
34836     // private
34837     onRender : function(ct, position){
34838         
34839         Roo.form.Signature.superclass.onRender.call(this, ct, position);
34840         
34841         this.wrap = this.el.wrap({
34842             cls:'x-form-signature-wrap', style : 'width: ' + this.width + 'px', cn:{cls:'x-form-signature'}
34843         });
34844         
34845         this.createToolbar(this);
34846         this.signPanel = this.wrap.createChild({
34847                 tag: 'div',
34848                 style: 'width: ' + this.width + 'px; height: ' + this.height + 'px; border: 0;'
34849             }, this.el
34850         );
34851             
34852         this.svgID = Roo.id();
34853         this.svgEl = this.signPanel.createChild({
34854               xmlns : 'http://www.w3.org/2000/svg',
34855               tag : 'svg',
34856               id : this.svgID + "-svg",
34857               width: this.width,
34858               height: this.height,
34859               viewBox: '0 0 '+this.width+' '+this.height,
34860               cn : [
34861                 {
34862                     tag: "rect",
34863                     id: this.svgID + "-svg-r",
34864                     width: this.width,
34865                     height: this.height,
34866                     fill: "#ffa"
34867                 },
34868                 {
34869                     tag: "line",
34870                     id: this.svgID + "-svg-l",
34871                     x1: "0", // start
34872                     y1: (this.height*0.8), // start set the line in 80% of height
34873                     x2: this.width, // end
34874                     y2: (this.height*0.8), // end set the line in 80% of height
34875                     'stroke': "#666",
34876                     'stroke-width': "1",
34877                     'stroke-dasharray': "3",
34878                     'shape-rendering': "crispEdges",
34879                     'pointer-events': "none"
34880                 },
34881                 {
34882                     tag: "path",
34883                     id: this.svgID + "-svg-p",
34884                     'stroke': "navy",
34885                     'stroke-width': "3",
34886                     'fill': "none",
34887                     'pointer-events': 'none'
34888                 }
34889               ]
34890         });
34891         this.createSVG();
34892         this.svgBox = this.svgEl.dom.getScreenCTM();
34893     },
34894     createSVG : function(){ 
34895         var svg = this.signPanel;
34896         var r = svg.select('#'+ this.svgID + '-svg-r', true).first().dom;
34897         var t = this;
34898
34899         r.addEventListener('mousedown', function(e) { return t.down(e); }, false);
34900         r.addEventListener('mousemove', function(e) { return t.move(e); }, false);
34901         r.addEventListener('mouseup', function(e) { return t.up(e); }, false);
34902         r.addEventListener('mouseout', function(e) { return t.up(e); }, false);
34903         r.addEventListener('touchstart', function(e) { return t.down(e); }, false);
34904         r.addEventListener('touchmove', function(e) { return t.move(e); }, false);
34905         r.addEventListener('touchend', function(e) { return t.up(e); }, false);
34906         
34907     },
34908     isTouchEvent : function(e){
34909         return e.type.match(/^touch/);
34910     },
34911     getCoords : function (e) {
34912         var pt    = this.svgEl.dom.createSVGPoint();
34913         pt.x = e.clientX; 
34914         pt.y = e.clientY;
34915         if (this.isTouchEvent(e)) {
34916             pt.x =  e.targetTouches[0].clientX;
34917             pt.y = e.targetTouches[0].clientY;
34918         }
34919         var a = this.svgEl.dom.getScreenCTM();
34920         var b = a.inverse();
34921         var mx = pt.matrixTransform(b);
34922         return mx.x + ',' + mx.y;
34923     },
34924     //mouse event headler 
34925     down : function (e) {
34926         this.signatureTmp += 'M' + this.getCoords(e) + ' ';
34927         this.signPanel.select('#'+ this.svgID + '-svg-p', true).first().attr('d', this.signatureTmp);
34928         
34929         this.isMouseDown = true;
34930         
34931         e.preventDefault();
34932     },
34933     move : function (e) {
34934         if (this.isMouseDown) {
34935             this.signatureTmp += 'L' + this.getCoords(e) + ' ';
34936             this.signPanel.select('#'+ this.svgID + '-svg-p', true).first().attr( 'd', this.signatureTmp);
34937         }
34938         
34939         e.preventDefault();
34940     },
34941     up : function (e) {
34942         this.isMouseDown = false;
34943         var sp = this.signatureTmp.split(' ');
34944         
34945         if(sp.length > 1){
34946             if(!sp[sp.length-2].match(/^L/)){
34947                 sp.pop();
34948                 sp.pop();
34949                 sp.push("");
34950                 this.signatureTmp = sp.join(" ");
34951             }
34952         }
34953         if(this.getValue() != this.signatureTmp){
34954             this.signPanel.select('#'+ this.svgID + '-svg-r', true).first().attr('fill', '#ffa');
34955             this.isConfirmed = false;
34956         }
34957         e.preventDefault();
34958     },
34959     
34960     /**
34961      * Protected method that will not generally be called directly. It
34962      * is called when the editor creates its toolbar. Override this method if you need to
34963      * add custom toolbar buttons.
34964      * @param {HtmlEditor} editor
34965      */
34966     createToolbar : function(editor){
34967          function btn(id, toggle, handler){
34968             var xid = fid + '-'+ id ;
34969             return {
34970                 id : xid,
34971                 cmd : id,
34972                 cls : 'x-btn-icon x-edit-'+id,
34973                 enableToggle:toggle !== false,
34974                 scope: editor, // was editor...
34975                 handler:handler||editor.relayBtnCmd,
34976                 clickEvent:'mousedown',
34977                 tooltip: etb.buttonTips[id] || undefined, ///tips ???
34978                 tabIndex:-1
34979             };
34980         }
34981         
34982         
34983         var tb = new Roo.Toolbar(editor.wrap.dom.firstChild);
34984         this.tb = tb;
34985         this.tb.add(
34986            {
34987                 cls : ' x-signature-btn x-signature-'+id,
34988                 scope: editor, // was editor...
34989                 handler: this.reset,
34990                 clickEvent:'mousedown',
34991                 text: this.labels.clear
34992             },
34993             {
34994                  xtype : 'Fill',
34995                  xns: Roo.Toolbar
34996             }, 
34997             {
34998                 cls : '  x-signature-btn x-signature-'+id,
34999                 scope: editor, // was editor...
35000                 handler: this.confirmHandler,
35001                 clickEvent:'mousedown',
35002                 text: this.labels.confirm
35003             }
35004         );
35005     
35006     },
35007     //public
35008     /**
35009      * when user is clicked confirm then show this image.....
35010      * 
35011      * @return {String} Image Data URI
35012      */
35013     getImageDataURI : function(){
35014         var svg = this.svgEl.dom.parentNode.innerHTML;
35015         var src = 'data:image/svg+xml;base64,'+window.btoa(svg);
35016         return src; 
35017     },
35018     /**
35019      * 
35020      * @return {Boolean} this.isConfirmed
35021      */
35022     getConfirmed : function(){
35023         return this.isConfirmed;
35024     },
35025     /**
35026      * 
35027      * @return {Number} this.width
35028      */
35029     getWidth : function(){
35030         return this.width;
35031     },
35032     /**
35033      * 
35034      * @return {Number} this.height
35035      */
35036     getHeight : function(){
35037         return this.height;
35038     },
35039     // private
35040     getSignature : function(){
35041         return this.signatureTmp;
35042     },
35043     // private
35044     reset : function(){
35045         this.signatureTmp = '';
35046         this.signPanel.select('#'+ this.svgID + '-svg-r', true).first().attr('fill', '#ffa');
35047         this.signPanel.select('#'+ this.svgID + '-svg-p', true).first().attr( 'd', '');
35048         this.isConfirmed = false;
35049         Roo.form.Signature.superclass.reset.call(this);
35050     },
35051     setSignature : function(s){
35052         this.signatureTmp = s;
35053         this.signPanel.select('#'+ this.svgID + '-svg-r', true).first().attr('fill', '#ffa');
35054         this.signPanel.select('#'+ this.svgID + '-svg-p', true).first().attr( 'd', s);
35055         this.setValue(s);
35056         this.isConfirmed = false;
35057         Roo.form.Signature.superclass.reset.call(this);
35058     }, 
35059     test : function(){
35060 //        Roo.log(this.signPanel.dom.contentWindow.up())
35061     },
35062     //private
35063     setConfirmed : function(){
35064         
35065         
35066         
35067 //        Roo.log(Roo.get(this.signPanel.dom.contentWindow.r).attr('fill', '#cfc'));
35068     },
35069     // private
35070     confirmHandler : function(){
35071         if(!this.getSignature()){
35072             return;
35073         }
35074         
35075         this.signPanel.select('#'+ this.svgID + '-svg-r', true).first().attr('fill', '#cfc');
35076         this.setValue(this.getSignature());
35077         this.isConfirmed = true;
35078         
35079         this.fireEvent('confirm', this);
35080     },
35081     // private
35082     // Subclasses should provide the validation implementation by overriding this
35083     validateValue : function(value){
35084         if(this.allowBlank){
35085             return true;
35086         }
35087         
35088         if(this.isConfirmed){
35089             return true;
35090         }
35091         return false;
35092     }
35093 });/*
35094  * Based on:
35095  * Ext JS Library 1.1.1
35096  * Copyright(c) 2006-2007, Ext JS, LLC.
35097  *
35098  * Originally Released Under LGPL - original licence link has changed is not relivant.
35099  *
35100  * Fork - LGPL
35101  * <script type="text/javascript">
35102  */
35103  
35104
35105 /**
35106  * @class Roo.form.ComboBox
35107  * @extends Roo.form.TriggerField
35108  * A combobox control with support for autocomplete, remote-loading, paging and many other features.
35109  * @constructor
35110  * Create a new ComboBox.
35111  * @param {Object} config Configuration options
35112  */
35113 Roo.form.Select = function(config){
35114     Roo.form.Select.superclass.constructor.call(this, config);
35115      
35116 };
35117
35118 Roo.extend(Roo.form.Select , Roo.form.ComboBox, {
35119     /**
35120      * @cfg {String/HTMLElement/Element} transform The id, DOM node or element of an existing select to convert to a ComboBox
35121      */
35122     /**
35123      * @cfg {Boolean} lazyRender True to prevent the ComboBox from rendering until requested (should always be used when
35124      * rendering into an Roo.Editor, defaults to false)
35125      */
35126     /**
35127      * @cfg {Boolean/Object} autoCreate A DomHelper element spec, or true for a default element spec (defaults to:
35128      * {tag: "input", type: "text", size: "24", autocomplete: "off"})
35129      */
35130     /**
35131      * @cfg {Roo.data.Store} store The data store to which this combo is bound (defaults to undefined)
35132      */
35133     /**
35134      * @cfg {String} title If supplied, a header element is created containing this text and added into the top of
35135      * the dropdown list (defaults to undefined, with no header element)
35136      */
35137
35138      /**
35139      * @cfg {String/Roo.Template} tpl The template to use to render the output
35140      */
35141      
35142     // private
35143     defaultAutoCreate : {tag: "select"  },
35144     /**
35145      * @cfg {Number} listWidth The width in pixels of the dropdown list (defaults to the width of the ComboBox field)
35146      */
35147     listWidth: undefined,
35148     /**
35149      * @cfg {String} displayField The underlying data field name to bind to this CombBox (defaults to undefined if
35150      * mode = 'remote' or 'text' if mode = 'local')
35151      */
35152     displayField: undefined,
35153     /**
35154      * @cfg {String} valueField The underlying data value name to bind to this CombBox (defaults to undefined if
35155      * mode = 'remote' or 'value' if mode = 'local'). 
35156      * Note: use of a valueField requires the user make a selection
35157      * in order for a value to be mapped.
35158      */
35159     valueField: undefined,
35160     
35161     
35162     /**
35163      * @cfg {String} hiddenName If specified, a hidden form field with this name is dynamically generated to store the
35164      * field's data value (defaults to the underlying DOM element's name)
35165      */
35166     hiddenName: undefined,
35167     /**
35168      * @cfg {String} listClass CSS class to apply to the dropdown list element (defaults to '')
35169      */
35170     listClass: '',
35171     /**
35172      * @cfg {String} selectedClass CSS class to apply to the selected item in the dropdown list (defaults to 'x-combo-selected')
35173      */
35174     selectedClass: 'x-combo-selected',
35175     /**
35176      * @cfg {String} triggerClass An additional CSS class used to style the trigger button.  The trigger will always get the
35177      * class 'x-form-trigger' and triggerClass will be <b>appended</b> if specified (defaults to 'x-form-arrow-trigger'
35178      * which displays a downward arrow icon).
35179      */
35180     triggerClass : 'x-form-arrow-trigger',
35181     /**
35182      * @cfg {Boolean/String} shadow True or "sides" for the default effect, "frame" for 4-way shadow, and "drop" for bottom-right
35183      */
35184     shadow:'sides',
35185     /**
35186      * @cfg {String} listAlign A valid anchor position value. See {@link Roo.Element#alignTo} for details on supported
35187      * anchor positions (defaults to 'tl-bl')
35188      */
35189     listAlign: 'tl-bl?',
35190     /**
35191      * @cfg {Number} maxHeight The maximum height in pixels of the dropdown list before scrollbars are shown (defaults to 300)
35192      */
35193     maxHeight: 300,
35194     /**
35195      * @cfg {String} triggerAction The action to execute when the trigger field is activated.  Use 'all' to run the
35196      * query specified by the allQuery config option (defaults to 'query')
35197      */
35198     triggerAction: 'query',
35199     /**
35200      * @cfg {Number} minChars The minimum number of characters the user must type before autocomplete and typeahead activate
35201      * (defaults to 4, does not apply if editable = false)
35202      */
35203     minChars : 4,
35204     /**
35205      * @cfg {Boolean} typeAhead True to populate and autoselect the remainder of the text being typed after a configurable
35206      * delay (typeAheadDelay) if it matches a known value (defaults to false)
35207      */
35208     typeAhead: false,
35209     /**
35210      * @cfg {Number} queryDelay The length of time in milliseconds to delay between the start of typing and sending the
35211      * query to filter the dropdown list (defaults to 500 if mode = 'remote' or 10 if mode = 'local')
35212      */
35213     queryDelay: 500,
35214     /**
35215      * @cfg {Number} pageSize If greater than 0, a paging toolbar is displayed in the footer of the dropdown list and the
35216      * filter queries will execute with page start and limit parameters.  Only applies when mode = 'remote' (defaults to 0)
35217      */
35218     pageSize: 0,
35219     /**
35220      * @cfg {Boolean} selectOnFocus True to select any existing text in the field immediately on focus.  Only applies
35221      * when editable = true (defaults to false)
35222      */
35223     selectOnFocus:false,
35224     /**
35225      * @cfg {String} queryParam Name of the query as it will be passed on the querystring (defaults to 'query')
35226      */
35227     queryParam: 'query',
35228     /**
35229      * @cfg {String} loadingText The text to display in the dropdown list while data is loading.  Only applies
35230      * when mode = 'remote' (defaults to 'Loading...')
35231      */
35232     loadingText: 'Loading...',
35233     /**
35234      * @cfg {Boolean} resizable True to add a resize handle to the bottom of the dropdown list (defaults to false)
35235      */
35236     resizable: false,
35237     /**
35238      * @cfg {Number} handleHeight The height in pixels of the dropdown list resize handle if resizable = true (defaults to 8)
35239      */
35240     handleHeight : 8,
35241     /**
35242      * @cfg {Boolean} editable False to prevent the user from typing text directly into the field, just like a
35243      * traditional select (defaults to true)
35244      */
35245     editable: true,
35246     /**
35247      * @cfg {String} allQuery The text query to send to the server to return all records for the list with no filtering (defaults to '')
35248      */
35249     allQuery: '',
35250     /**
35251      * @cfg {String} mode Set to 'local' if the ComboBox loads local data (defaults to 'remote' which loads from the server)
35252      */
35253     mode: 'remote',
35254     /**
35255      * @cfg {Number} minListWidth The minimum width of the dropdown list in pixels (defaults to 70, will be ignored if
35256      * listWidth has a higher value)
35257      */
35258     minListWidth : 70,
35259     /**
35260      * @cfg {Boolean} forceSelection True to restrict the selected value to one of the values in the list, false to
35261      * allow the user to set arbitrary text into the field (defaults to false)
35262      */
35263     forceSelection:false,
35264     /**
35265      * @cfg {Number} typeAheadDelay The length of time in milliseconds to wait until the typeahead text is displayed
35266      * if typeAhead = true (defaults to 250)
35267      */
35268     typeAheadDelay : 250,
35269     /**
35270      * @cfg {String} valueNotFoundText When using a name/value combo, if the value passed to setValue is not found in
35271      * the store, valueNotFoundText will be displayed as the field text if defined (defaults to undefined)
35272      */
35273     valueNotFoundText : undefined,
35274     
35275     /**
35276      * @cfg {String} defaultValue The value displayed after loading the store.
35277      */
35278     defaultValue: '',
35279     
35280     /**
35281      * @cfg {Boolean} blockFocus Prevents all focus calls, so it can work with things like HTML edtor bar
35282      */
35283     blockFocus : false,
35284     
35285     /**
35286      * @cfg {Boolean} disableClear Disable showing of clear button.
35287      */
35288     disableClear : false,
35289     /**
35290      * @cfg {Boolean} alwaysQuery  Disable caching of results, and always send query
35291      */
35292     alwaysQuery : false,
35293     
35294     //private
35295     addicon : false,
35296     editicon: false,
35297     
35298     // element that contains real text value.. (when hidden is used..)
35299      
35300     // private
35301     onRender : function(ct, position){
35302         Roo.form.Field.prototype.onRender.call(this, ct, position);
35303         
35304         if(this.store){
35305             this.store.on('beforeload', this.onBeforeLoad, this);
35306             this.store.on('load', this.onLoad, this);
35307             this.store.on('loadexception', this.onLoadException, this);
35308             this.store.load({});
35309         }
35310         
35311         
35312         
35313     },
35314
35315     // private
35316     initEvents : function(){
35317         //Roo.form.ComboBox.superclass.initEvents.call(this);
35318  
35319     },
35320
35321     onDestroy : function(){
35322        
35323         if(this.store){
35324             this.store.un('beforeload', this.onBeforeLoad, this);
35325             this.store.un('load', this.onLoad, this);
35326             this.store.un('loadexception', this.onLoadException, this);
35327         }
35328         //Roo.form.ComboBox.superclass.onDestroy.call(this);
35329     },
35330
35331     // private
35332     fireKey : function(e){
35333         if(e.isNavKeyPress() && !this.list.isVisible()){
35334             this.fireEvent("specialkey", this, e);
35335         }
35336     },
35337
35338     // private
35339     onResize: function(w, h){
35340         
35341         return; 
35342     
35343         
35344     },
35345
35346     /**
35347      * Allow or prevent the user from directly editing the field text.  If false is passed,
35348      * the user will only be able to select from the items defined in the dropdown list.  This method
35349      * is the runtime equivalent of setting the 'editable' config option at config time.
35350      * @param {Boolean} value True to allow the user to directly edit the field text
35351      */
35352     setEditable : function(value){
35353          
35354     },
35355
35356     // private
35357     onBeforeLoad : function(){
35358         
35359         Roo.log("Select before load");
35360         return;
35361     
35362         this.innerList.update(this.loadingText ?
35363                '<div class="loading-indicator">'+this.loadingText+'</div>' : '');
35364         //this.restrictHeight();
35365         this.selectedIndex = -1;
35366     },
35367
35368     // private
35369     onLoad : function(){
35370
35371     
35372         var dom = this.el.dom;
35373         dom.innerHTML = '';
35374          var od = dom.ownerDocument;
35375          
35376         if (this.emptyText) {
35377             var op = od.createElement('option');
35378             op.setAttribute('value', '');
35379             op.innerHTML = String.format('{0}', this.emptyText);
35380             dom.appendChild(op);
35381         }
35382         if(this.store.getCount() > 0){
35383            
35384             var vf = this.valueField;
35385             var df = this.displayField;
35386             this.store.data.each(function(r) {
35387                 // which colmsn to use... testing - cdoe / title..
35388                 var op = od.createElement('option');
35389                 op.setAttribute('value', r.data[vf]);
35390                 op.innerHTML = String.format('{0}', r.data[df]);
35391                 dom.appendChild(op);
35392             });
35393             if (typeof(this.defaultValue != 'undefined')) {
35394                 this.setValue(this.defaultValue);
35395             }
35396             
35397              
35398         }else{
35399             //this.onEmptyResults();
35400         }
35401         //this.el.focus();
35402     },
35403     // private
35404     onLoadException : function()
35405     {
35406         dom.innerHTML = '';
35407             
35408         Roo.log("Select on load exception");
35409         return;
35410     
35411         this.collapse();
35412         Roo.log(this.store.reader.jsonData);
35413         if (this.store && typeof(this.store.reader.jsonData.errorMsg) != 'undefined') {
35414             Roo.MessageBox.alert("Error loading",this.store.reader.jsonData.errorMsg);
35415         }
35416         
35417         
35418     },
35419     // private
35420     onTypeAhead : function(){
35421          
35422     },
35423
35424     // private
35425     onSelect : function(record, index){
35426         Roo.log('on select?');
35427         return;
35428         if(this.fireEvent('beforeselect', this, record, index) !== false){
35429             this.setFromData(index > -1 ? record.data : false);
35430             this.collapse();
35431             this.fireEvent('select', this, record, index);
35432         }
35433     },
35434
35435     /**
35436      * Returns the currently selected field value or empty string if no value is set.
35437      * @return {String} value The selected value
35438      */
35439     getValue : function(){
35440         var dom = this.el.dom;
35441         this.value = dom.options[dom.selectedIndex].value;
35442         return this.value;
35443         
35444     },
35445
35446     /**
35447      * Clears any text/value currently set in the field
35448      */
35449     clearValue : function(){
35450         this.value = '';
35451         this.el.dom.selectedIndex = this.emptyText ? 0 : -1;
35452         
35453     },
35454
35455     /**
35456      * Sets the specified value into the field.  If the value finds a match, the corresponding record text
35457      * will be displayed in the field.  If the value does not match the data value of an existing item,
35458      * and the valueNotFoundText config option is defined, it will be displayed as the default field text.
35459      * Otherwise the field will be blank (although the value will still be set).
35460      * @param {String} value The value to match
35461      */
35462     setValue : function(v){
35463         var d = this.el.dom;
35464         for (var i =0; i < d.options.length;i++) {
35465             if (v == d.options[i].value) {
35466                 d.selectedIndex = i;
35467                 this.value = v;
35468                 return;
35469             }
35470         }
35471         this.clearValue();
35472     },
35473     /**
35474      * @property {Object} the last set data for the element
35475      */
35476     
35477     lastData : false,
35478     /**
35479      * Sets the value of the field based on a object which is related to the record format for the store.
35480      * @param {Object} value the value to set as. or false on reset?
35481      */
35482     setFromData : function(o){
35483         Roo.log('setfrom data?');
35484          
35485         
35486         
35487     },
35488     // private
35489     reset : function(){
35490         this.clearValue();
35491     },
35492     // private
35493     findRecord : function(prop, value){
35494         
35495         return false;
35496     
35497         var record;
35498         if(this.store.getCount() > 0){
35499             this.store.each(function(r){
35500                 if(r.data[prop] == value){
35501                     record = r;
35502                     return false;
35503                 }
35504                 return true;
35505             });
35506         }
35507         return record;
35508     },
35509     
35510     getName: function()
35511     {
35512         // returns hidden if it's set..
35513         if (!this.rendered) {return ''};
35514         return !this.hiddenName && this.el.dom.name  ? this.el.dom.name : (this.hiddenName || '');
35515         
35516     },
35517      
35518
35519     
35520
35521     // private
35522     onEmptyResults : function(){
35523         Roo.log('empty results');
35524         //this.collapse();
35525     },
35526
35527     /**
35528      * Returns true if the dropdown list is expanded, else false.
35529      */
35530     isExpanded : function(){
35531         return false;
35532     },
35533
35534     /**
35535      * Select an item in the dropdown list by its data value. This function does NOT cause the select event to fire.
35536      * The store must be loaded and the list expanded for this function to work, otherwise use setValue.
35537      * @param {String} value The data value of the item to select
35538      * @param {Boolean} scrollIntoView False to prevent the dropdown list from autoscrolling to display the
35539      * selected item if it is not currently in view (defaults to true)
35540      * @return {Boolean} True if the value matched an item in the list, else false
35541      */
35542     selectByValue : function(v, scrollIntoView){
35543         Roo.log('select By Value');
35544         return false;
35545     
35546         if(v !== undefined && v !== null){
35547             var r = this.findRecord(this.valueField || this.displayField, v);
35548             if(r){
35549                 this.select(this.store.indexOf(r), scrollIntoView);
35550                 return true;
35551             }
35552         }
35553         return false;
35554     },
35555
35556     /**
35557      * Select an item in the dropdown list by its numeric index in the list. This function does NOT cause the select event to fire.
35558      * The store must be loaded and the list expanded for this function to work, otherwise use setValue.
35559      * @param {Number} index The zero-based index of the list item to select
35560      * @param {Boolean} scrollIntoView False to prevent the dropdown list from autoscrolling to display the
35561      * selected item if it is not currently in view (defaults to true)
35562      */
35563     select : function(index, scrollIntoView){
35564         Roo.log('select ');
35565         return  ;
35566         
35567         this.selectedIndex = index;
35568         this.view.select(index);
35569         if(scrollIntoView !== false){
35570             var el = this.view.getNode(index);
35571             if(el){
35572                 this.innerList.scrollChildIntoView(el, false);
35573             }
35574         }
35575     },
35576
35577       
35578
35579     // private
35580     validateBlur : function(){
35581         
35582         return;
35583         
35584     },
35585
35586     // private
35587     initQuery : function(){
35588         this.doQuery(this.getRawValue());
35589     },
35590
35591     // private
35592     doForce : function(){
35593         if(this.el.dom.value.length > 0){
35594             this.el.dom.value =
35595                 this.lastSelectionText === undefined ? '' : this.lastSelectionText;
35596              
35597         }
35598     },
35599
35600     /**
35601      * Execute a query to filter the dropdown list.  Fires the beforequery event prior to performing the
35602      * query allowing the query action to be canceled if needed.
35603      * @param {String} query The SQL query to execute
35604      * @param {Boolean} forceAll True to force the query to execute even if there are currently fewer characters
35605      * in the field than the minimum specified by the minChars config option.  It also clears any filter previously
35606      * saved in the current store (defaults to false)
35607      */
35608     doQuery : function(q, forceAll){
35609         
35610         Roo.log('doQuery?');
35611         if(q === undefined || q === null){
35612             q = '';
35613         }
35614         var qe = {
35615             query: q,
35616             forceAll: forceAll,
35617             combo: this,
35618             cancel:false
35619         };
35620         if(this.fireEvent('beforequery', qe)===false || qe.cancel){
35621             return false;
35622         }
35623         q = qe.query;
35624         forceAll = qe.forceAll;
35625         if(forceAll === true || (q.length >= this.minChars)){
35626             if(this.lastQuery != q || this.alwaysQuery){
35627                 this.lastQuery = q;
35628                 if(this.mode == 'local'){
35629                     this.selectedIndex = -1;
35630                     if(forceAll){
35631                         this.store.clearFilter();
35632                     }else{
35633                         this.store.filter(this.displayField, q);
35634                     }
35635                     this.onLoad();
35636                 }else{
35637                     this.store.baseParams[this.queryParam] = q;
35638                     this.store.load({
35639                         params: this.getParams(q)
35640                     });
35641                     this.expand();
35642                 }
35643             }else{
35644                 this.selectedIndex = -1;
35645                 this.onLoad();   
35646             }
35647         }
35648     },
35649
35650     // private
35651     getParams : function(q){
35652         var p = {};
35653         //p[this.queryParam] = q;
35654         if(this.pageSize){
35655             p.start = 0;
35656             p.limit = this.pageSize;
35657         }
35658         return p;
35659     },
35660
35661     /**
35662      * Hides the dropdown list if it is currently expanded. Fires the 'collapse' event on completion.
35663      */
35664     collapse : function(){
35665         
35666     },
35667
35668     // private
35669     collapseIf : function(e){
35670         
35671     },
35672
35673     /**
35674      * Expands the dropdown list if it is currently hidden. Fires the 'expand' event on completion.
35675      */
35676     expand : function(){
35677         
35678     } ,
35679
35680     // private
35681      
35682
35683     /** 
35684     * @cfg {Boolean} grow 
35685     * @hide 
35686     */
35687     /** 
35688     * @cfg {Number} growMin 
35689     * @hide 
35690     */
35691     /** 
35692     * @cfg {Number} growMax 
35693     * @hide 
35694     */
35695     /**
35696      * @hide
35697      * @method autoSize
35698      */
35699     
35700     setWidth : function()
35701     {
35702         
35703     },
35704     getResizeEl : function(){
35705         return this.el;
35706     }
35707 });//<script type="text/javasscript">
35708  
35709
35710 /**
35711  * @class Roo.DDView
35712  * A DnD enabled version of Roo.View.
35713  * @param {Element/String} container The Element in which to create the View.
35714  * @param {String} tpl The template string used to create the markup for each element of the View
35715  * @param {Object} config The configuration properties. These include all the config options of
35716  * {@link Roo.View} plus some specific to this class.<br>
35717  * <p>
35718  * Drag/drop is implemented by adding {@link Roo.data.Record}s to the target DDView. If copying is
35719  * not being performed, the original {@link Roo.data.Record} is removed from the source DDView.<br>
35720  * <p>
35721  * The following extra CSS rules are needed to provide insertion point highlighting:<pre><code>
35722 .x-view-drag-insert-above {
35723         border-top:1px dotted #3366cc;
35724 }
35725 .x-view-drag-insert-below {
35726         border-bottom:1px dotted #3366cc;
35727 }
35728 </code></pre>
35729  * 
35730  */
35731  
35732 Roo.DDView = function(container, tpl, config) {
35733     Roo.DDView.superclass.constructor.apply(this, arguments);
35734     this.getEl().setStyle("outline", "0px none");
35735     this.getEl().unselectable();
35736     if (this.dragGroup) {
35737         this.setDraggable(this.dragGroup.split(","));
35738     }
35739     if (this.dropGroup) {
35740         this.setDroppable(this.dropGroup.split(","));
35741     }
35742     if (this.deletable) {
35743         this.setDeletable();
35744     }
35745     this.isDirtyFlag = false;
35746         this.addEvents({
35747                 "drop" : true
35748         });
35749 };
35750
35751 Roo.extend(Roo.DDView, Roo.View, {
35752 /**     @cfg {String/Array} dragGroup The ddgroup name(s) for the View's DragZone. */
35753 /**     @cfg {String/Array} dropGroup The ddgroup name(s) for the View's DropZone. */
35754 /**     @cfg {Boolean} copy Causes drag operations to copy nodes rather than move. */
35755 /**     @cfg {Boolean} allowCopy Causes ctrl/drag operations to copy nodes rather than move. */
35756
35757         isFormField: true,
35758
35759         reset: Roo.emptyFn,
35760         
35761         clearInvalid: Roo.form.Field.prototype.clearInvalid,
35762
35763         validate: function() {
35764                 return true;
35765         },
35766         
35767         destroy: function() {
35768                 this.purgeListeners();
35769                 this.getEl.removeAllListeners();
35770                 this.getEl().remove();
35771                 if (this.dragZone) {
35772                         if (this.dragZone.destroy) {
35773                                 this.dragZone.destroy();
35774                         }
35775                 }
35776                 if (this.dropZone) {
35777                         if (this.dropZone.destroy) {
35778                                 this.dropZone.destroy();
35779                         }
35780                 }
35781         },
35782
35783 /**     Allows this class to be an Roo.form.Field so it can be found using {@link Roo.form.BasicForm#findField}. */
35784         getName: function() {
35785                 return this.name;
35786         },
35787
35788 /**     Loads the View from a JSON string representing the Records to put into the Store. */
35789         setValue: function(v) {
35790                 if (!this.store) {
35791                         throw "DDView.setValue(). DDView must be constructed with a valid Store";
35792                 }
35793                 var data = {};
35794                 data[this.store.reader.meta.root] = v ? [].concat(v) : [];
35795                 this.store.proxy = new Roo.data.MemoryProxy(data);
35796                 this.store.load();
35797         },
35798
35799 /**     @return {String} a parenthesised list of the ids of the Records in the View. */
35800         getValue: function() {
35801                 var result = '(';
35802                 this.store.each(function(rec) {
35803                         result += rec.id + ',';
35804                 });
35805                 return result.substr(0, result.length - 1) + ')';
35806         },
35807         
35808         getIds: function() {
35809                 var i = 0, result = new Array(this.store.getCount());
35810                 this.store.each(function(rec) {
35811                         result[i++] = rec.id;
35812                 });
35813                 return result;
35814         },
35815         
35816         isDirty: function() {
35817                 return this.isDirtyFlag;
35818         },
35819
35820 /**
35821  *      Part of the Roo.dd.DropZone interface. If no target node is found, the
35822  *      whole Element becomes the target, and this causes the drop gesture to append.
35823  */
35824     getTargetFromEvent : function(e) {
35825                 var target = e.getTarget();
35826                 while ((target !== null) && (target.parentNode != this.el.dom)) {
35827                 target = target.parentNode;
35828                 }
35829                 if (!target) {
35830                         target = this.el.dom.lastChild || this.el.dom;
35831                 }
35832                 return target;
35833     },
35834
35835 /**
35836  *      Create the drag data which consists of an object which has the property "ddel" as
35837  *      the drag proxy element. 
35838  */
35839     getDragData : function(e) {
35840         var target = this.findItemFromChild(e.getTarget());
35841                 if(target) {
35842                         this.handleSelection(e);
35843                         var selNodes = this.getSelectedNodes();
35844             var dragData = {
35845                 source: this,
35846                 copy: this.copy || (this.allowCopy && e.ctrlKey),
35847                 nodes: selNodes,
35848                 records: []
35849                         };
35850                         var selectedIndices = this.getSelectedIndexes();
35851                         for (var i = 0; i < selectedIndices.length; i++) {
35852                                 dragData.records.push(this.store.getAt(selectedIndices[i]));
35853                         }
35854                         if (selNodes.length == 1) {
35855                                 dragData.ddel = target.cloneNode(true); // the div element
35856                         } else {
35857                                 var div = document.createElement('div'); // create the multi element drag "ghost"
35858                                 div.className = 'multi-proxy';
35859                                 for (var i = 0, len = selNodes.length; i < len; i++) {
35860                                         div.appendChild(selNodes[i].cloneNode(true));
35861                                 }
35862                                 dragData.ddel = div;
35863                         }
35864             //console.log(dragData)
35865             //console.log(dragData.ddel.innerHTML)
35866                         return dragData;
35867                 }
35868         //console.log('nodragData')
35869                 return false;
35870     },
35871     
35872 /**     Specify to which ddGroup items in this DDView may be dragged. */
35873     setDraggable: function(ddGroup) {
35874         if (ddGroup instanceof Array) {
35875                 Roo.each(ddGroup, this.setDraggable, this);
35876                 return;
35877         }
35878         if (this.dragZone) {
35879                 this.dragZone.addToGroup(ddGroup);
35880         } else {
35881                         this.dragZone = new Roo.dd.DragZone(this.getEl(), {
35882                                 containerScroll: true,
35883                                 ddGroup: ddGroup 
35884
35885                         });
35886 //                      Draggability implies selection. DragZone's mousedown selects the element.
35887                         if (!this.multiSelect) { this.singleSelect = true; }
35888
35889 //                      Wire the DragZone's handlers up to methods in *this*
35890                         this.dragZone.getDragData = this.getDragData.createDelegate(this);
35891                 }
35892     },
35893
35894 /**     Specify from which ddGroup this DDView accepts drops. */
35895     setDroppable: function(ddGroup) {
35896         if (ddGroup instanceof Array) {
35897                 Roo.each(ddGroup, this.setDroppable, this);
35898                 return;
35899         }
35900         if (this.dropZone) {
35901                 this.dropZone.addToGroup(ddGroup);
35902         } else {
35903                         this.dropZone = new Roo.dd.DropZone(this.getEl(), {
35904                                 containerScroll: true,
35905                                 ddGroup: ddGroup
35906                         });
35907
35908 //                      Wire the DropZone's handlers up to methods in *this*
35909                         this.dropZone.getTargetFromEvent = this.getTargetFromEvent.createDelegate(this);
35910                         this.dropZone.onNodeEnter = this.onNodeEnter.createDelegate(this);
35911                         this.dropZone.onNodeOver = this.onNodeOver.createDelegate(this);
35912                         this.dropZone.onNodeOut = this.onNodeOut.createDelegate(this);
35913                         this.dropZone.onNodeDrop = this.onNodeDrop.createDelegate(this);
35914                 }
35915     },
35916
35917 /**     Decide whether to drop above or below a View node. */
35918     getDropPoint : function(e, n, dd){
35919         if (n == this.el.dom) { return "above"; }
35920                 var t = Roo.lib.Dom.getY(n), b = t + n.offsetHeight;
35921                 var c = t + (b - t) / 2;
35922                 var y = Roo.lib.Event.getPageY(e);
35923                 if(y <= c) {
35924                         return "above";
35925                 }else{
35926                         return "below";
35927                 }
35928     },
35929
35930     onNodeEnter : function(n, dd, e, data){
35931                 return false;
35932     },
35933     
35934     onNodeOver : function(n, dd, e, data){
35935                 var pt = this.getDropPoint(e, n, dd);
35936                 // set the insert point style on the target node
35937                 var dragElClass = this.dropNotAllowed;
35938                 if (pt) {
35939                         var targetElClass;
35940                         if (pt == "above"){
35941                                 dragElClass = n.previousSibling ? "x-tree-drop-ok-between" : "x-tree-drop-ok-above";
35942                                 targetElClass = "x-view-drag-insert-above";
35943                         } else {
35944                                 dragElClass = n.nextSibling ? "x-tree-drop-ok-between" : "x-tree-drop-ok-below";
35945                                 targetElClass = "x-view-drag-insert-below";
35946                         }
35947                         if (this.lastInsertClass != targetElClass){
35948                                 Roo.fly(n).replaceClass(this.lastInsertClass, targetElClass);
35949                                 this.lastInsertClass = targetElClass;
35950                         }
35951                 }
35952                 return dragElClass;
35953         },
35954
35955     onNodeOut : function(n, dd, e, data){
35956                 this.removeDropIndicators(n);
35957     },
35958
35959     onNodeDrop : function(n, dd, e, data){
35960         if (this.fireEvent("drop", this, n, dd, e, data) === false) {
35961                 return false;
35962         }
35963         var pt = this.getDropPoint(e, n, dd);
35964                 var insertAt = (n == this.el.dom) ? this.nodes.length : n.nodeIndex;
35965                 if (pt == "below") { insertAt++; }
35966                 for (var i = 0; i < data.records.length; i++) {
35967                         var r = data.records[i];
35968                         var dup = this.store.getById(r.id);
35969                         if (dup && (dd != this.dragZone)) {
35970                                 Roo.fly(this.getNode(this.store.indexOf(dup))).frame("red", 1);
35971                         } else {
35972                                 if (data.copy) {
35973                                         this.store.insert(insertAt++, r.copy());
35974                                 } else {
35975                                         data.source.isDirtyFlag = true;
35976                                         r.store.remove(r);
35977                                         this.store.insert(insertAt++, r);
35978                                 }
35979                                 this.isDirtyFlag = true;
35980                         }
35981                 }
35982                 this.dragZone.cachedTarget = null;
35983                 return true;
35984     },
35985
35986     removeDropIndicators : function(n){
35987                 if(n){
35988                         Roo.fly(n).removeClass([
35989                                 "x-view-drag-insert-above",
35990                                 "x-view-drag-insert-below"]);
35991                         this.lastInsertClass = "_noclass";
35992                 }
35993     },
35994
35995 /**
35996  *      Utility method. Add a delete option to the DDView's context menu.
35997  *      @param {String} imageUrl The URL of the "delete" icon image.
35998  */
35999         setDeletable: function(imageUrl) {
36000                 if (!this.singleSelect && !this.multiSelect) {
36001                         this.singleSelect = true;
36002                 }
36003                 var c = this.getContextMenu();
36004                 this.contextMenu.on("itemclick", function(item) {
36005                         switch (item.id) {
36006                                 case "delete":
36007                                         this.remove(this.getSelectedIndexes());
36008                                         break;
36009                         }
36010                 }, this);
36011                 this.contextMenu.add({
36012                         icon: imageUrl,
36013                         id: "delete",
36014                         text: 'Delete'
36015                 });
36016         },
36017         
36018 /**     Return the context menu for this DDView. */
36019         getContextMenu: function() {
36020                 if (!this.contextMenu) {
36021 //                      Create the View's context menu
36022                         this.contextMenu = new Roo.menu.Menu({
36023                                 id: this.id + "-contextmenu"
36024                         });
36025                         this.el.on("contextmenu", this.showContextMenu, this);
36026                 }
36027                 return this.contextMenu;
36028         },
36029         
36030         disableContextMenu: function() {
36031                 if (this.contextMenu) {
36032                         this.el.un("contextmenu", this.showContextMenu, this);
36033                 }
36034         },
36035
36036         showContextMenu: function(e, item) {
36037         item = this.findItemFromChild(e.getTarget());
36038                 if (item) {
36039                         e.stopEvent();
36040                         this.select(this.getNode(item), this.multiSelect && e.ctrlKey, true);
36041                         this.contextMenu.showAt(e.getXY());
36042             }
36043     },
36044
36045 /**
36046  *      Remove {@link Roo.data.Record}s at the specified indices.
36047  *      @param {Array/Number} selectedIndices The index (or Array of indices) of Records to remove.
36048  */
36049     remove: function(selectedIndices) {
36050                 selectedIndices = [].concat(selectedIndices);
36051                 for (var i = 0; i < selectedIndices.length; i++) {
36052                         var rec = this.store.getAt(selectedIndices[i]);
36053                         this.store.remove(rec);
36054                 }
36055     },
36056
36057 /**
36058  *      Double click fires the event, but also, if this is draggable, and there is only one other
36059  *      related DropZone, it transfers the selected node.
36060  */
36061     onDblClick : function(e){
36062         var item = this.findItemFromChild(e.getTarget());
36063         if(item){
36064             if (this.fireEvent("dblclick", this, this.indexOf(item), item, e) === false) {
36065                 return false;
36066             }
36067             if (this.dragGroup) {
36068                     var targets = Roo.dd.DragDropMgr.getRelated(this.dragZone, true);
36069                     while (targets.indexOf(this.dropZone) > -1) {
36070                             targets.remove(this.dropZone);
36071                                 }
36072                     if (targets.length == 1) {
36073                                         this.dragZone.cachedTarget = null;
36074                         var el = Roo.get(targets[0].getEl());
36075                         var box = el.getBox(true);
36076                         targets[0].onNodeDrop(el.dom, {
36077                                 target: el.dom,
36078                                 xy: [box.x, box.y + box.height - 1]
36079                         }, null, this.getDragData(e));
36080                     }
36081                 }
36082         }
36083     },
36084     
36085     handleSelection: function(e) {
36086                 this.dragZone.cachedTarget = null;
36087         var item = this.findItemFromChild(e.getTarget());
36088         if (!item) {
36089                 this.clearSelections(true);
36090                 return;
36091         }
36092                 if (item && (this.multiSelect || this.singleSelect)){
36093                         if(this.multiSelect && e.shiftKey && (!e.ctrlKey) && this.lastSelection){
36094                                 this.select(this.getNodes(this.indexOf(this.lastSelection), item.nodeIndex), false);
36095                         }else if (this.isSelected(this.getNode(item)) && e.ctrlKey){
36096                                 this.unselect(item);
36097                         } else {
36098                                 this.select(item, this.multiSelect && e.ctrlKey);
36099                                 this.lastSelection = item;
36100                         }
36101                 }
36102     },
36103
36104     onItemClick : function(item, index, e){
36105                 if(this.fireEvent("beforeclick", this, index, item, e) === false){
36106                         return false;
36107                 }
36108                 return true;
36109     },
36110
36111     unselect : function(nodeInfo, suppressEvent){
36112                 var node = this.getNode(nodeInfo);
36113                 if(node && this.isSelected(node)){
36114                         if(this.fireEvent("beforeselect", this, node, this.selections) !== false){
36115                                 Roo.fly(node).removeClass(this.selectedClass);
36116                                 this.selections.remove(node);
36117                                 if(!suppressEvent){
36118                                         this.fireEvent("selectionchange", this, this.selections);
36119                                 }
36120                         }
36121                 }
36122     }
36123 });
36124 Roo.layout = {};/*
36125  * Based on:
36126  * Ext JS Library 1.1.1
36127  * Copyright(c) 2006-2007, Ext JS, LLC.
36128  *
36129  * Originally Released Under LGPL - original licence link has changed is not relivant.
36130  *
36131  * Fork - LGPL
36132  * <script type="text/javascript">
36133  */
36134  
36135 /**
36136  * @class Roo.layout.Manager
36137  * @extends Roo.util.Observable
36138  * Base class for layout managers.
36139  */
36140 Roo.layout.Manager = function(container, config){
36141     Roo.layout.Manager.superclass.constructor.call(this);
36142     this.el = Roo.get(container);
36143     // ie scrollbar fix
36144     if(this.el.dom == document.body && Roo.isIE && !config.allowScroll){
36145         document.body.scroll = "no";
36146     }else if(this.el.dom != document.body && this.el.getStyle('position') == 'static'){
36147         this.el.position('relative');
36148     }
36149     this.id = this.el.id;
36150     this.el.addClass("x-layout-container");
36151     /** false to disable window resize monitoring @type Boolean */
36152     this.monitorWindowResize = true;
36153     this.regions = {};
36154     this.addEvents({
36155         /**
36156          * @event layout
36157          * Fires when a layout is performed. 
36158          * @param {Roo.layout.Manager} this
36159          */
36160         "layout" : true,
36161         /**
36162          * @event regionresized
36163          * Fires when the user resizes a region. 
36164          * @param {Roo.layout.Region} region The resized region
36165          * @param {Number} newSize The new size (width for east/west, height for north/south)
36166          */
36167         "regionresized" : true,
36168         /**
36169          * @event regioncollapsed
36170          * Fires when a region is collapsed. 
36171          * @param {Roo.layout.Region} region The collapsed region
36172          */
36173         "regioncollapsed" : true,
36174         /**
36175          * @event regionexpanded
36176          * Fires when a region is expanded.  
36177          * @param {Roo.layout.Region} region The expanded region
36178          */
36179         "regionexpanded" : true
36180     });
36181     this.updating = false;
36182     Roo.EventManager.onWindowResize(this.onWindowResize, this, true);
36183 };
36184
36185 Roo.extend(Roo.layout.Manager, Roo.util.Observable, {
36186     /**
36187      * Returns true if this layout is currently being updated
36188      * @return {Boolean}
36189      */
36190     isUpdating : function(){
36191         return this.updating; 
36192     },
36193     
36194     /**
36195      * Suspend the LayoutManager from doing auto-layouts while
36196      * making multiple add or remove calls
36197      */
36198     beginUpdate : function(){
36199         this.updating = true;    
36200     },
36201     
36202     /**
36203      * Restore auto-layouts and optionally disable the manager from performing a layout
36204      * @param {Boolean} noLayout true to disable a layout update 
36205      */
36206     endUpdate : function(noLayout){
36207         this.updating = false;
36208         if(!noLayout){
36209             this.layout();
36210         }    
36211     },
36212     
36213     layout: function(){
36214         
36215     },
36216     
36217     onRegionResized : function(region, newSize){
36218         this.fireEvent("regionresized", region, newSize);
36219         this.layout();
36220     },
36221     
36222     onRegionCollapsed : function(region){
36223         this.fireEvent("regioncollapsed", region);
36224     },
36225     
36226     onRegionExpanded : function(region){
36227         this.fireEvent("regionexpanded", region);
36228     },
36229         
36230     /**
36231      * Returns the size of the current view. This method normalizes document.body and element embedded layouts and
36232      * performs box-model adjustments.
36233      * @return {Object} The size as an object {width: (the width), height: (the height)}
36234      */
36235     getViewSize : function(){
36236         var size;
36237         if(this.el.dom != document.body){
36238             size = this.el.getSize();
36239         }else{
36240             size = {width: Roo.lib.Dom.getViewWidth(), height: Roo.lib.Dom.getViewHeight()};
36241         }
36242         size.width -= this.el.getBorderWidth("lr")-this.el.getPadding("lr");
36243         size.height -= this.el.getBorderWidth("tb")-this.el.getPadding("tb");
36244         return size;
36245     },
36246     
36247     /**
36248      * Returns the Element this layout is bound to.
36249      * @return {Roo.Element}
36250      */
36251     getEl : function(){
36252         return this.el;
36253     },
36254     
36255     /**
36256      * Returns the specified region.
36257      * @param {String} target The region key ('center', 'north', 'south', 'east' or 'west')
36258      * @return {Roo.layout.Region}
36259      */
36260     getRegion : function(target){
36261         return this.regions[target.toLowerCase()];
36262     },
36263     
36264     onWindowResize : function(){
36265         if(this.monitorWindowResize){
36266             this.layout();
36267         }
36268     }
36269 });/*
36270  * Based on:
36271  * Ext JS Library 1.1.1
36272  * Copyright(c) 2006-2007, Ext JS, LLC.
36273  *
36274  * Originally Released Under LGPL - original licence link has changed is not relivant.
36275  *
36276  * Fork - LGPL
36277  * <script type="text/javascript">
36278  */
36279 /**
36280  * @class Roo.layout.Border
36281  * @extends Roo.layout.Manager
36282  * @children Roo.panel.Content
36283  * This class represents a common layout manager used in desktop applications. For screenshots and more details,
36284  * please see: <br><br>
36285  * <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>
36286  * <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>
36287  * Example:
36288  <pre><code>
36289  var layout = new Roo.layout.Border(document.body, {
36290     north: {
36291         initialSize: 25,
36292         titlebar: false
36293     },
36294     west: {
36295         split:true,
36296         initialSize: 200,
36297         minSize: 175,
36298         maxSize: 400,
36299         titlebar: true,
36300         collapsible: true
36301     },
36302     east: {
36303         split:true,
36304         initialSize: 202,
36305         minSize: 175,
36306         maxSize: 400,
36307         titlebar: true,
36308         collapsible: true
36309     },
36310     south: {
36311         split:true,
36312         initialSize: 100,
36313         minSize: 100,
36314         maxSize: 200,
36315         titlebar: true,
36316         collapsible: true
36317     },
36318     center: {
36319         titlebar: true,
36320         autoScroll:true,
36321         resizeTabs: true,
36322         minTabWidth: 50,
36323         preferredTabWidth: 150
36324     }
36325 });
36326
36327 // shorthand
36328 var CP = Roo.panel.Content;
36329
36330 layout.beginUpdate();
36331 layout.add("north", new CP("north", "North"));
36332 layout.add("south", new CP("south", {title: "South", closable: true}));
36333 layout.add("west", new CP("west", {title: "West"}));
36334 layout.add("east", new CP("autoTabs", {title: "Auto Tabs", closable: true}));
36335 layout.add("center", new CP("center1", {title: "Close Me", closable: true}));
36336 layout.add("center", new CP("center2", {title: "Center Panel", closable: false}));
36337 layout.getRegion("center").showPanel("center1");
36338 layout.endUpdate();
36339 </code></pre>
36340
36341 <b>The container the layout is rendered into can be either the body element or any other element.
36342 If it is not the body element, the container needs to either be an absolute positioned element,
36343 or you will need to add "position:relative" to the css of the container.  You will also need to specify
36344 the container size if it is not the body element.</b>
36345
36346 * @constructor
36347 * Create a new BorderLayout
36348 * @param {String/HTMLElement/Element} container The container this layout is bound to
36349 * @param {Object} config Configuration options
36350  */
36351 Roo.layout.Border = function(container, config){
36352     config = config || {};
36353     Roo.layout.Border.superclass.constructor.call(this, container, config);
36354     this.factory = config.factory || Roo.layout.Border.RegionFactory;
36355     for(var i = 0, len = this.factory.validRegions.length; i < len; i++) {
36356         var target = this.factory.validRegions[i];
36357         if(config[target]){
36358             this.addRegion(target, config[target]);
36359         }
36360     }
36361 };
36362
36363 Roo.extend(Roo.layout.Border, Roo.layout.Manager, {
36364         
36365         /**
36366          * @cfg {Roo.layout.Region} east
36367          */
36368         /**
36369          * @cfg {Roo.layout.Region} west
36370          */
36371         /**
36372          * @cfg {Roo.layout.Region} north
36373          */
36374         /**
36375          * @cfg {Roo.layout.Region} south
36376          */
36377         /**
36378          * @cfg {Roo.layout.Region} center
36379          */
36380     /**
36381      * Creates and adds a new region if it doesn't already exist.
36382      * @param {String} target The target region key (north, south, east, west or center).
36383      * @param {Object} config The regions config object
36384      * @return {BorderLayoutRegion} The new region
36385      */
36386     addRegion : function(target, config){
36387         if(!this.regions[target]){
36388             var r = this.factory.create(target, this, config);
36389             this.bindRegion(target, r);
36390         }
36391         return this.regions[target];
36392     },
36393
36394     // private (kinda)
36395     bindRegion : function(name, r){
36396         this.regions[name] = r;
36397         r.on("visibilitychange", this.layout, this);
36398         r.on("paneladded", this.layout, this);
36399         r.on("panelremoved", this.layout, this);
36400         r.on("invalidated", this.layout, this);
36401         r.on("resized", this.onRegionResized, this);
36402         r.on("collapsed", this.onRegionCollapsed, this);
36403         r.on("expanded", this.onRegionExpanded, this);
36404     },
36405
36406     /**
36407      * Performs a layout update.
36408      */
36409     layout : function(){
36410         if(this.updating) {
36411             return;
36412         }
36413         var size = this.getViewSize();
36414         var w = size.width;
36415         var h = size.height;
36416         var centerW = w;
36417         var centerH = h;
36418         var centerY = 0;
36419         var centerX = 0;
36420         //var x = 0, y = 0;
36421
36422         var rs = this.regions;
36423         var north = rs["north"];
36424         var south = rs["south"]; 
36425         var west = rs["west"];
36426         var east = rs["east"];
36427         var center = rs["center"];
36428         //if(this.hideOnLayout){ // not supported anymore
36429             //c.el.setStyle("display", "none");
36430         //}
36431         if(north && north.isVisible()){
36432             var b = north.getBox();
36433             var m = north.getMargins();
36434             b.width = w - (m.left+m.right);
36435             b.x = m.left;
36436             b.y = m.top;
36437             centerY = b.height + b.y + m.bottom;
36438             centerH -= centerY;
36439             north.updateBox(this.safeBox(b));
36440         }
36441         if(south && south.isVisible()){
36442             var b = south.getBox();
36443             var m = south.getMargins();
36444             b.width = w - (m.left+m.right);
36445             b.x = m.left;
36446             var totalHeight = (b.height + m.top + m.bottom);
36447             b.y = h - totalHeight + m.top;
36448             centerH -= totalHeight;
36449             south.updateBox(this.safeBox(b));
36450         }
36451         if(west && west.isVisible()){
36452             var b = west.getBox();
36453             var m = west.getMargins();
36454             b.height = centerH - (m.top+m.bottom);
36455             b.x = m.left;
36456             b.y = centerY + m.top;
36457             var totalWidth = (b.width + m.left + m.right);
36458             centerX += totalWidth;
36459             centerW -= totalWidth;
36460             west.updateBox(this.safeBox(b));
36461         }
36462         if(east && east.isVisible()){
36463             var b = east.getBox();
36464             var m = east.getMargins();
36465             b.height = centerH - (m.top+m.bottom);
36466             var totalWidth = (b.width + m.left + m.right);
36467             b.x = w - totalWidth + m.left;
36468             b.y = centerY + m.top;
36469             centerW -= totalWidth;
36470             east.updateBox(this.safeBox(b));
36471         }
36472         if(center){
36473             var m = center.getMargins();
36474             var centerBox = {
36475                 x: centerX + m.left,
36476                 y: centerY + m.top,
36477                 width: centerW - (m.left+m.right),
36478                 height: centerH - (m.top+m.bottom)
36479             };
36480             //if(this.hideOnLayout){
36481                 //center.el.setStyle("display", "block");
36482             //}
36483             center.updateBox(this.safeBox(centerBox));
36484         }
36485         this.el.repaint();
36486         this.fireEvent("layout", this);
36487     },
36488
36489     // private
36490     safeBox : function(box){
36491         box.width = Math.max(0, box.width);
36492         box.height = Math.max(0, box.height);
36493         return box;
36494     },
36495
36496     /**
36497      * Adds a ContentPanel (or subclass) to this layout.
36498      * @param {String} target The target region key (north, south, east, west or center).
36499      * @param {Roo.panel.Content} panel The panel to add
36500      * @return {Roo.panel.Content} The added panel
36501      */
36502     add : function(target, panel){
36503          
36504         target = target.toLowerCase();
36505         return this.regions[target].add(panel);
36506     },
36507
36508     /**
36509      * Remove a ContentPanel (or subclass) to this layout.
36510      * @param {String} target The target region key (north, south, east, west or center).
36511      * @param {Number/String/Roo.panel.Content} panel The index, id or panel to remove
36512      * @return {Roo.panel.Content} The removed panel
36513      */
36514     remove : function(target, panel){
36515         target = target.toLowerCase();
36516         return this.regions[target].remove(panel);
36517     },
36518
36519     /**
36520      * Searches all regions for a panel with the specified id
36521      * @param {String} panelId
36522      * @return {Roo.panel.Content} The panel or null if it wasn't found
36523      */
36524     findPanel : function(panelId){
36525         var rs = this.regions;
36526         for(var target in rs){
36527             if(typeof rs[target] != "function"){
36528                 var p = rs[target].getPanel(panelId);
36529                 if(p){
36530                     return p;
36531                 }
36532             }
36533         }
36534         return null;
36535     },
36536
36537     /**
36538      * Searches all regions for a panel with the specified id and activates (shows) it.
36539      * @param {String/panel.Content} panelId The panels id or the panel itself
36540      * @return {Roo.panel.Content} The shown panel or null
36541      */
36542     showPanel : function(panelId) {
36543       var rs = this.regions;
36544       for(var target in rs){
36545          var r = rs[target];
36546          if(typeof r != "function"){
36547             if(r.hasPanel(panelId)){
36548                return r.showPanel(panelId);
36549             }
36550          }
36551       }
36552       return null;
36553    },
36554
36555    /**
36556      * Restores this layout's state using Roo.state.Manager or the state provided by the passed provider.
36557      * @param {Roo.state.Provider} provider (optional) An alternate state provider
36558      */
36559     restoreState : function(provider){
36560         if(!provider){
36561             provider = Roo.state.Manager;
36562         }
36563         var sm = new Roo.layout.StateManager();
36564         sm.init(this, provider);
36565     },
36566
36567     /**
36568      * Adds a batch of multiple ContentPanels dynamically by passing a special regions config object.  This config
36569      * object should contain properties for each region to add ContentPanels to, and each property's value should be
36570      * a valid ContentPanel config object.  Example:
36571      * <pre><code>
36572 // Create the main layout
36573 var layout = new Roo.layout.Border('main-ct', {
36574     west: {
36575         split:true,
36576         minSize: 175,
36577         titlebar: true
36578     },
36579     center: {
36580         title:'Components'
36581     }
36582 }, 'main-ct');
36583
36584 // Create and add multiple ContentPanels at once via configs
36585 layout.batchAdd({
36586    west: {
36587        id: 'source-files',
36588        autoCreate:true,
36589        title:'Ext Source Files',
36590        autoScroll:true,
36591        fitToFrame:true
36592    },
36593    center : {
36594        el: cview,
36595        autoScroll:true,
36596        fitToFrame:true,
36597        toolbar: tb,
36598        resizeEl:'cbody'
36599    }
36600 });
36601 </code></pre>
36602      * @param {Object} regions An object containing ContentPanel configs by region name
36603      */
36604     batchAdd : function(regions){
36605         this.beginUpdate();
36606         for(var rname in regions){
36607             var lr = this.regions[rname];
36608             if(lr){
36609                 this.addTypedPanels(lr, regions[rname]);
36610             }
36611         }
36612         this.endUpdate();
36613     },
36614
36615     // private
36616     addTypedPanels : function(lr, ps){
36617         if(typeof ps == 'string'){
36618             lr.add(new Roo.panel.Content(ps));
36619         }
36620         else if(ps instanceof Array){
36621             for(var i =0, len = ps.length; i < len; i++){
36622                 this.addTypedPanels(lr, ps[i]);
36623             }
36624         }
36625         else if(!ps.events){ // raw config?
36626             var el = ps.el;
36627             delete ps.el; // prevent conflict
36628             lr.add(new Roo.panel.Content(el || Roo.id(), ps));
36629         }
36630         else {  // panel object assumed!
36631             lr.add(ps);
36632         }
36633     },
36634     /**
36635      * Adds a xtype elements to the layout.
36636      * <pre><code>
36637
36638 layout.addxtype({
36639        xtype : 'ContentPanel',
36640        region: 'west',
36641        items: [ .... ]
36642    }
36643 );
36644
36645 layout.addxtype({
36646         xtype : 'NestedLayoutPanel',
36647         region: 'west',
36648         layout: {
36649            center: { },
36650            west: { }   
36651         },
36652         items : [ ... list of content panels or nested layout panels.. ]
36653    }
36654 );
36655 </code></pre>
36656      * @param {Object} cfg Xtype definition of item to add.
36657      */
36658     addxtype : function(cfg)
36659     {
36660         // basically accepts a pannel...
36661         // can accept a layout region..!?!?
36662         //Roo.log('Roo.layout.Border add ' + cfg.xtype)
36663         
36664         // if (!cfg.xtype.match(/Panel$/)) {
36665         //     return false;
36666         // }
36667         var ret = false;
36668
36669         if (typeof(cfg.region) == 'undefined') {
36670             Roo.log("Failed to add Panel, region was not set");
36671             Roo.log(cfg);
36672             return false;
36673         }
36674         var region = cfg.region;
36675         delete cfg.region;
36676         
36677           
36678         var xitems = [];
36679         if (cfg.items) {
36680             xitems = cfg.items;
36681             delete cfg.items;
36682         }
36683         var nb = false;
36684         
36685         switch(cfg.xtype) 
36686         {
36687             case 'Content':
36688                 if(cfg.autoCreate) {
36689                     ret = new Roo.panel[cfg.xtype](cfg); // new panel!!!!!
36690                 } else {
36691                     var el = this.el.createChild();
36692                     ret = new Roo.panel[cfg.xtype](el, cfg); // new panel!!!!!
36693                 }
36694                 
36695                 this.add(region, ret);
36696                 break;
36697             case 'Grid':
36698                 // needs grid and region
36699                 
36700                 //var el = this.getRegion(region).el.createChild();
36701                 var el = this.el.createChild();
36702                 // create the grid first...
36703                 
36704                 var grid = new Roo.grid[cfg.grid.xtype](el, cfg.grid);
36705                 delete cfg.grid;
36706                 if (region == 'center' && this.active ) {
36707                     cfg.background = false;
36708                 }
36709                 ret = new Roo.panel[cfg.xtype](grid, cfg); // new panel!!!!!
36710                 
36711                 this.add(region, ret);
36712                 if (cfg.background) {
36713                     ret.on('activate', function(gp) {
36714                         if (!gp.grid.rendered) {
36715                             gp.grid.render();
36716                         }
36717                     });
36718                 } else {
36719                     grid.render();
36720                 }
36721                 break;
36722             case 'NestedLayout': 
36723                 // create a new Layout (which is  a Border Layout...
36724                 var el = this.el.createChild();
36725                 var clayout = cfg.layout;
36726                 delete cfg.layout;
36727                 clayout.items   = clayout.items  || [];
36728                 // replace this exitems with the clayout ones..
36729                 xitems = clayout.items;
36730                  
36731                 
36732                 if (region == 'center' && this.active && this.getRegion('center').panels.length < 1) {
36733                     cfg.background = false;
36734                 }
36735                 var layout = new Roo.layout.Border(el, clayout);
36736                 
36737                 ret = new Roo.panel[cfg.xtype](layout, cfg); // new panel!!!!!
36738                 //console.log('adding nested layout panel '  + cfg.toSource());
36739                 this.add(region, ret);
36740                 nb = {}; /// find first...
36741                 break;
36742                 
36743             case 'Calendar':
36744                 ret = new Roo.panel[cfg.xtype](cfg); // new panel!!!!!
36745                 this.add(region, ret);
36746                 break;
36747             case 'Tree': // our new panel!
36748                 cfg.el = this.el.createChild();
36749                 ret = new Roo.panel[cfg.xtype](cfg); // new panel!!!!!
36750                 this.add(region, ret);
36751                 break;
36752             case 'ContentPanel':
36753             case 'ScrollPanel':  // ContentPanel (el, cfg)
36754             case 'ViewPanel': 
36755                 if(cfg.autoCreate) {
36756                     ret = new Roo[cfg.xtype](cfg); // new panel!!!!!
36757                 } else {
36758                     var el = this.el.createChild();
36759                     ret = new Roo[cfg.xtype](el, cfg); // new panel!!!!!
36760                 }
36761                 
36762                 this.add(region, ret);
36763                 break;
36764             
36765             
36766             case 'TreePanel': // our new panel!
36767                 cfg.el = this.el.createChild();
36768                 ret = new Roo[cfg.xtype](cfg); // new panel!!!!!
36769                 this.add(region, ret);
36770                 break;
36771             
36772             case 'NestedLayoutPanel': 
36773                 // create a new Layout (which is  a Border Layout...
36774                 var el = this.el.createChild();
36775                 var clayout = cfg.layout;
36776                 delete cfg.layout;
36777                 clayout.items   = clayout.items  || [];
36778                 // replace this exitems with the clayout ones..
36779                 xitems = clayout.items;
36780                  
36781                 
36782                 if (region == 'center' && this.active && this.getRegion('center').panels.length < 1) {
36783                     cfg.background = false;
36784                 }
36785                 var layout = new Roo.layout.Border(el, clayout);
36786                 
36787                 ret = new Roo[cfg.xtype](layout, cfg); // new panel!!!!!
36788                 //console.log('adding nested layout panel '  + cfg.toSource());
36789                 this.add(region, ret);
36790                 nb = {}; /// find first...
36791                 break;
36792                 
36793             case 'GridPanel': 
36794             
36795                 // needs grid and region
36796                 
36797                 //var el = this.getRegion(region).el.createChild();
36798                 var el = this.el.createChild();
36799                 // create the grid first...
36800                 
36801                 var grid = new Roo.grid[cfg.grid.xtype](el, cfg.grid);
36802                 delete cfg.grid;
36803                 if (region == 'center' && this.active ) {
36804                     cfg.background = false;
36805                 }
36806                 ret = new Roo[cfg.xtype](grid, cfg); // new panel!!!!!
36807                 
36808                 this.add(region, ret);
36809                 if (cfg.background) {
36810                     ret.on('activate', function(gp) {
36811                         if (!gp.grid.rendered) {
36812                             gp.grid.render();
36813                         }
36814                     });
36815                 } else {
36816                     grid.render();
36817                 }
36818                 break;
36819            
36820            
36821            
36822                 
36823                 
36824                 
36825             default:
36826                 if (typeof(Roo[cfg.xtype]) != 'undefined') {
36827                     
36828                     ret = new Roo[cfg.xtype](cfg); // new panel!!!!!
36829                     this.add(region, ret);
36830                 } else {
36831                 
36832                     alert("Can not add '" + cfg.xtype + "' to BorderLayout");
36833                     return null;
36834                 }
36835                 
36836              // GridPanel (grid, cfg)
36837             
36838         }
36839         this.beginUpdate();
36840         // add children..
36841         var region = '';
36842         var abn = {};
36843         Roo.each(xitems, function(i)  {
36844             region = nb && i.region ? i.region : false;
36845             
36846             var add = ret.addxtype(i);
36847            
36848             if (region) {
36849                 nb[region] = nb[region] == undefined ? 0 : nb[region]+1;
36850                 if (!i.background) {
36851                     abn[region] = nb[region] ;
36852                 }
36853             }
36854             
36855         });
36856         this.endUpdate();
36857
36858         // make the last non-background panel active..
36859         //if (nb) { Roo.log(abn); }
36860         if (nb) {
36861             
36862             for(var r in abn) {
36863                 region = this.getRegion(r);
36864                 if (region) {
36865                     // tried using nb[r], but it does not work..
36866                      
36867                     region.showPanel(abn[r]);
36868                    
36869                 }
36870             }
36871         }
36872         return ret;
36873         
36874     }
36875 });
36876
36877 /**
36878  * Shortcut for creating a new BorderLayout object and adding one or more ContentPanels to it in a single step, handling
36879  * the beginUpdate and endUpdate calls internally.  The key to this method is the <b>panels</b> property that can be
36880  * provided with each region config, which allows you to add ContentPanel configs in addition to the region configs
36881  * during creation.  The following code is equivalent to the constructor-based example at the beginning of this class:
36882  * <pre><code>
36883 // shorthand
36884 var CP = Roo.ContentPanel;
36885
36886 var layout = Roo.layout.Border.create({
36887     north: {
36888         initialSize: 25,
36889         titlebar: false,
36890         panels: [new CP("north", "North")]
36891     },
36892     west: {
36893         split:true,
36894         initialSize: 200,
36895         minSize: 175,
36896         maxSize: 400,
36897         titlebar: true,
36898         collapsible: true,
36899         panels: [new CP("west", {title: "West"})]
36900     },
36901     east: {
36902         split:true,
36903         initialSize: 202,
36904         minSize: 175,
36905         maxSize: 400,
36906         titlebar: true,
36907         collapsible: true,
36908         panels: [new CP("autoTabs", {title: "Auto Tabs", closable: true})]
36909     },
36910     south: {
36911         split:true,
36912         initialSize: 100,
36913         minSize: 100,
36914         maxSize: 200,
36915         titlebar: true,
36916         collapsible: true,
36917         panels: [new CP("south", {title: "South", closable: true})]
36918     },
36919     center: {
36920         titlebar: true,
36921         autoScroll:true,
36922         resizeTabs: true,
36923         minTabWidth: 50,
36924         preferredTabWidth: 150,
36925         panels: [
36926             new CP("center1", {title: "Close Me", closable: true}),
36927             new CP("center2", {title: "Center Panel", closable: false})
36928         ]
36929     }
36930 }, document.body);
36931
36932 layout.getRegion("center").showPanel("center1");
36933 </code></pre>
36934  * @param config
36935  * @param targetEl
36936  */
36937 Roo.layout.Border.create = function(config, targetEl){
36938     var layout = new Roo.layout.Border(targetEl || document.body, config);
36939     layout.beginUpdate();
36940     var regions = Roo.layout.Border.RegionFactory.validRegions;
36941     for(var j = 0, jlen = regions.length; j < jlen; j++){
36942         var lr = regions[j];
36943         if(layout.regions[lr] && config[lr].panels){
36944             var r = layout.regions[lr];
36945             var ps = config[lr].panels;
36946             layout.addTypedPanels(r, ps);
36947         }
36948     }
36949     layout.endUpdate();
36950     return layout;
36951 };
36952
36953 // private
36954 Roo.layout.Border.RegionFactory = {
36955     // private
36956     validRegions : ["north","south","east","west","center"],
36957
36958     // private
36959     create : function(target, mgr, config){
36960         target = target.toLowerCase();
36961         if(config.lightweight || config.basic){
36962             return new Roo.layout.BasicRegion(mgr, config, target);
36963         }
36964                 var cn = target.charAt(0).toUpperCase() + target.slice(1);
36965                 if (typeof (Roo.layout[cn]) == 'undefined') {
36966                         throw 'Layout region "'+target+'" not supported.';
36967                 }
36968                 return new Roo.layout[cn](mgr, config);
36969          
36970         
36971     }
36972 };/*
36973  * Based on:
36974  * Ext JS Library 1.1.1
36975  * Copyright(c) 2006-2007, Ext JS, LLC.
36976  *
36977  * Originally Released Under LGPL - original licence link has changed is not relivant.
36978  *
36979  * Fork - LGPL
36980  * <script type="text/javascript">
36981  */
36982  
36983 /**
36984  * @class Roo.layout.BasicRegion
36985  * @extends Roo.util.Observable
36986  * This class represents a lightweight region in a layout manager. This region does not move dom nodes
36987  * and does not have a titlebar, tabs or any other features. All it does is size and position 
36988  * panels. To create a BasicLayoutRegion, add lightweight:true or basic:true to your regions config.
36989  */
36990 Roo.layout.BasicRegion= function(mgr, config, pos, skipConfig){
36991     this.mgr = mgr;
36992     this.position  = pos;
36993     this.events = {
36994         /**
36995          * @scope Roo.layout.BasicRegion
36996          */
36997         
36998         /**
36999          * @event beforeremove
37000          * Fires before a panel is removed (or closed). To cancel the removal set "e.cancel = true" on the event argument.
37001          * @param {Roo.layout.Region} this
37002          * @param {Roo.panel.Content} panel The panel
37003          * @param {Object} e The cancel event object
37004          */
37005         "beforeremove" : true,
37006         /**
37007          * @event invalidated
37008          * Fires when the layout for this region is changed.
37009          * @param {Roo.layout.Region} this
37010          */
37011         "invalidated" : true,
37012         /**
37013          * @event visibilitychange
37014          * Fires when this region is shown or hidden 
37015          * @param {Roo.layout.Region} this
37016          * @param {Boolean} visibility true or false
37017          */
37018         "visibilitychange" : true,
37019         /**
37020          * @event paneladded
37021          * Fires when a panel is added. 
37022          * @param {Roo.layout.Region} this
37023          * @param {Roo.panel.Content} panel The panel
37024          */
37025         "paneladded" : true,
37026         /**
37027          * @event panelremoved
37028          * Fires when a panel is removed. 
37029          * @param {Roo.layout.Region} this
37030          * @param {Roo.panel.Content} panel The panel
37031          */
37032         "panelremoved" : true,
37033         /**
37034          * @event beforecollapse
37035          * Fires when this region before collapse.
37036          * @param {Roo.layout.Region} this
37037          */
37038         "beforecollapse" : true,
37039         /**
37040          * @event collapsed
37041          * Fires when this region is collapsed.
37042          * @param {Roo.layout.Region} this
37043          */
37044         "collapsed" : true,
37045         /**
37046          * @event expanded
37047          * Fires when this region is expanded.
37048          * @param {Roo.layout.Region} this
37049          */
37050         "expanded" : true,
37051         /**
37052          * @event slideshow
37053          * Fires when this region is slid into view.
37054          * @param {Roo.layout.Region} this
37055          */
37056         "slideshow" : true,
37057         /**
37058          * @event slidehide
37059          * Fires when this region slides out of view. 
37060          * @param {Roo.layout.Region} this
37061          */
37062         "slidehide" : true,
37063         /**
37064          * @event panelactivated
37065          * Fires when a panel is activated. 
37066          * @param {Roo.layout.Region} this
37067          * @param {Roo.panel.Content} panel The activated panel
37068          */
37069         "panelactivated" : true,
37070         /**
37071          * @event resized
37072          * Fires when the user resizes this region. 
37073          * @param {Roo.layout.Region} this
37074          * @param {Number} newSize The new size (width for east/west, height for north/south)
37075          */
37076         "resized" : true
37077     };
37078     /** A collection of panels in this region. @type Roo.util.MixedCollection */
37079     this.panels = new Roo.util.MixedCollection();
37080     this.panels.getKey = this.getPanelId.createDelegate(this);
37081     this.box = null;
37082     this.activePanel = null;
37083     // ensure listeners are added...
37084     
37085     if (config.listeners || config.events) {
37086         Roo.layout.BasicRegion.superclass.constructor.call(this, {
37087             listeners : config.listeners || {},
37088             events : config.events || {}
37089         });
37090     }
37091     
37092     if(skipConfig !== true){
37093         this.applyConfig(config);
37094     }
37095 };
37096
37097 Roo.extend(Roo.layout.BasicRegion, Roo.util.Observable, {
37098     getPanelId : function(p){
37099         return p.getId();
37100     },
37101     
37102     applyConfig : function(config){
37103         this.margins = config.margins || this.margins || {top: 0, left: 0, right:0, bottom: 0};
37104         this.config = config;
37105         
37106     },
37107     
37108     /**
37109      * Resizes the region to the specified size. For vertical regions (west, east) this adjusts 
37110      * the width, for horizontal (north, south) the height.
37111      * @param {Number} newSize The new width or height
37112      */
37113     resizeTo : function(newSize){
37114         var el = this.el ? this.el :
37115                  (this.activePanel ? this.activePanel.getEl() : null);
37116         if(el){
37117             switch(this.position){
37118                 case "east":
37119                 case "west":
37120                     el.setWidth(newSize);
37121                     this.fireEvent("resized", this, newSize);
37122                 break;
37123                 case "north":
37124                 case "south":
37125                     el.setHeight(newSize);
37126                     this.fireEvent("resized", this, newSize);
37127                 break;                
37128             }
37129         }
37130     },
37131     
37132     getBox : function(){
37133         return this.activePanel ? this.activePanel.getEl().getBox(false, true) : null;
37134     },
37135     
37136     getMargins : function(){
37137         return this.margins;
37138     },
37139     
37140     updateBox : function(box){
37141         this.box = box;
37142         var el = this.activePanel.getEl();
37143         el.dom.style.left = box.x + "px";
37144         el.dom.style.top = box.y + "px";
37145         this.activePanel.setSize(box.width, box.height);
37146     },
37147     
37148     /**
37149      * Returns the container element for this region.
37150      * @return {Roo.Element}
37151      */
37152     getEl : function(){
37153         return this.activePanel;
37154     },
37155     
37156     /**
37157      * Returns true if this region is currently visible.
37158      * @return {Boolean}
37159      */
37160     isVisible : function(){
37161         return this.activePanel ? true : false;
37162     },
37163     
37164     setActivePanel : function(panel){
37165         panel = this.getPanel(panel);
37166         if(this.activePanel && this.activePanel != panel){
37167             this.activePanel.setActiveState(false);
37168             this.activePanel.getEl().setLeftTop(-10000,-10000);
37169         }
37170         this.activePanel = panel;
37171         panel.setActiveState(true);
37172         if(this.box){
37173             panel.setSize(this.box.width, this.box.height);
37174         }
37175         this.fireEvent("panelactivated", this, panel);
37176         this.fireEvent("invalidated");
37177     },
37178     
37179     /**
37180      * Show the specified panel.
37181      * @param {Number/String/panel.Content} panelId The panels index, id or the panel itself
37182      * @return {Roo.panel.Content} The shown panel or null
37183      */
37184     showPanel : function(panel){
37185         if(panel = this.getPanel(panel)){
37186             this.setActivePanel(panel);
37187         }
37188         return panel;
37189     },
37190     
37191     /**
37192      * Get the active panel for this region.
37193      * @return {Roo.panel.Content} The active panel or null
37194      */
37195     getActivePanel : function(){
37196         return this.activePanel;
37197     },
37198     
37199     /**
37200      * Add the passed ContentPanel(s)
37201      * @param {panel.Content...} panel The ContentPanel(s) to add (you can pass more than one)
37202      * @return {Roo.panel.Content} The panel added (if only one was added)
37203      */
37204     add : function(panel){
37205         if(arguments.length > 1){
37206             for(var i = 0, len = arguments.length; i < len; i++) {
37207                 this.add(arguments[i]);
37208             }
37209             return null;
37210         }
37211         if(this.hasPanel(panel)){
37212             this.showPanel(panel);
37213             return panel;
37214         }
37215         var el = panel.getEl();
37216         if(el.dom.parentNode != this.mgr.el.dom){
37217             this.mgr.el.dom.appendChild(el.dom);
37218         }
37219         if(panel.setRegion){
37220             panel.setRegion(this);
37221         }
37222         this.panels.add(panel);
37223         el.setStyle("position", "absolute");
37224         if(!panel.background){
37225             this.setActivePanel(panel);
37226             if(this.config.initialSize && this.panels.getCount()==1){
37227                 this.resizeTo(this.config.initialSize);
37228             }
37229         }
37230         this.fireEvent("paneladded", this, panel);
37231         return panel;
37232     },
37233     
37234     /**
37235      * Returns true if the panel is in this region.
37236      * @param {Number/String/panel.Content} panel The panels index, id or the panel itself
37237      * @return {Boolean}
37238      */
37239     hasPanel : function(panel){
37240         if(typeof panel == "object"){ // must be panel obj
37241             panel = panel.getId();
37242         }
37243         return this.getPanel(panel) ? true : false;
37244     },
37245     
37246     /**
37247      * Removes the specified panel. If preservePanel is not true (either here or in the config), the panel is destroyed.
37248      * @param {Number/String/panel.Content} panel The panels index, id or the panel itself
37249      * @param {Boolean} preservePanel Overrides the config preservePanel option
37250      * @return {Roo.panel.Content} The panel that was removed
37251      */
37252     remove : function(panel, preservePanel){
37253         panel = this.getPanel(panel);
37254         if(!panel){
37255             return null;
37256         }
37257         var e = {};
37258         this.fireEvent("beforeremove", this, panel, e);
37259         if(e.cancel === true){
37260             return null;
37261         }
37262         var panelId = panel.getId();
37263         this.panels.removeKey(panelId);
37264         return panel;
37265     },
37266     
37267     /**
37268      * Returns the panel specified or null if it's not in this region.
37269      * @param {Number/String/panel.Content} panel The panels index, id or the panel itself
37270      * @return {Roo.panel.Content}
37271      */
37272     getPanel : function(id){
37273         if(typeof id == "object"){ // must be panel obj
37274             return id;
37275         }
37276         return this.panels.get(id);
37277     },
37278     
37279     /**
37280      * Returns this regions position (north/south/east/west/center).
37281      * @return {String} 
37282      */
37283     getPosition: function(){
37284         return this.position;    
37285     }
37286 });/*
37287  * Based on:
37288  * Ext JS Library 1.1.1
37289  * Copyright(c) 2006-2007, Ext JS, LLC.
37290  *
37291  * Originally Released Under LGPL - original licence link has changed is not relivant.
37292  *
37293  * Fork - LGPL
37294  * <script type="text/javascript">
37295  */
37296  
37297 /**
37298  * @class Roo.layout.Region
37299  * @extends Roo.layout.BasicRegion
37300  * This class represents a region in a layout manager.
37301  * @cfg {Boolean}   collapsible     False to disable collapsing (defaults to true)
37302  * @cfg {Boolean}   collapsed       True to set the initial display to collapsed (defaults to false)
37303  * @cfg {Boolean}   floatable       False to disable floating (defaults to true)
37304  * @cfg {Object}    margins         Margins for the element (defaults to {top: 0, left: 0, right:0, bottom: 0})
37305  * @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})
37306  * @cfg {String}    tabPosition     (top|bottom) "top" or "bottom" (defaults to "bottom")
37307  * @cfg {String}    collapsedTitle  Optional string message to display in the collapsed block of a north or south region
37308  * @cfg {Boolean}   alwaysShowTabs  True to always display tabs even when there is only 1 panel (defaults to false)
37309  * @cfg {Boolean}   autoScroll      True to enable overflow scrolling (defaults to false)
37310  * @cfg {Boolean}   titlebar        True to display a title bar (defaults to true)
37311  * @cfg {String}    title           The title for the region (overrides panel titles)
37312  * @cfg {Boolean}   animate         True to animate expand/collapse (defaults to false)
37313  * @cfg {Boolean}   autoHide        False to disable auto hiding when the mouse leaves the "floated" region (defaults to true)
37314  * @cfg {Boolean}   preservePanels  True to preserve removed panels so they can be readded later (defaults to false)
37315  * @cfg {Boolean}   closeOnTab      True to place the close icon on the tabs instead of the region titlebar (defaults to false)
37316  * @cfg {Boolean}   hideTabs        True to hide the tab strip (defaults to false)
37317  * @cfg {Boolean}   resizeTabs      True to enable automatic tab resizing. This will resize the tabs so they are all the same size and fit within
37318  *                      the space available, similar to FireFox 1.5 tabs (defaults to false)
37319  * @cfg {Number}    minTabWidth     The minimum tab width (defaults to 40)
37320  * @cfg {Number}    preferredTabWidth The preferred tab width (defaults to 150)
37321  * @cfg {Boolean}   showPin         True to show a pin button
37322  * @cfg {Boolean}   hidden          True to start the region hidden (defaults to false)
37323  * @cfg {Boolean}   hideWhenEmpty   True to hide the region when it has no panels
37324  * @cfg {Boolean}   disableTabTips  True to disable tab tooltips
37325  * @cfg {Number}    width           For East/West panels
37326  * @cfg {Number}    height          For North/South panels
37327  * @cfg {Boolean}   split           To show the splitter
37328  * @cfg {Boolean}   toolbar         xtype configuration for a toolbar - shows on right of tabbar
37329  */
37330 Roo.layout.Region = function(mgr, config, pos){
37331     Roo.layout.Region.superclass.constructor.call(this, mgr, config, pos, true);
37332     var dh = Roo.DomHelper;
37333     /** This region's container element 
37334     * @type Roo.Element */
37335     this.el = dh.append(mgr.el.dom, {tag: "div", cls: "x-layout-panel x-layout-panel-" + this.position}, true);
37336     /** This region's title element 
37337     * @type Roo.Element */
37338
37339     this.titleEl = dh.append(this.el.dom, {tag: "div", unselectable: "on", cls: "x-unselectable x-layout-panel-hd x-layout-title-"+this.position, children:[
37340         {tag: "span", cls: "x-unselectable x-layout-panel-hd-text", unselectable: "on", html: "&#160;"},
37341         {tag: "div", cls: "x-unselectable x-layout-panel-hd-tools", unselectable: "on"}
37342     ]}, true);
37343     this.titleEl.enableDisplayMode();
37344     /** This region's title text element 
37345     * @type HTMLElement */
37346     this.titleTextEl = this.titleEl.dom.firstChild;
37347     this.tools = Roo.get(this.titleEl.dom.childNodes[1], true);
37348     this.closeBtn = this.createTool(this.tools.dom, "x-layout-close");
37349     this.closeBtn.enableDisplayMode();
37350     this.closeBtn.on("click", this.closeClicked, this);
37351     this.closeBtn.hide();
37352
37353     this.createBody(config);
37354     this.visible = true;
37355     this.collapsed = false;
37356
37357     if(config.hideWhenEmpty){
37358         this.hide();
37359         this.on("paneladded", this.validateVisibility, this);
37360         this.on("panelremoved", this.validateVisibility, this);
37361     }
37362     this.applyConfig(config);
37363 };
37364
37365 Roo.extend(Roo.layout.Region, Roo.layout.BasicRegion, {
37366
37367     createBody : function(){
37368         /** This region's body element 
37369         * @type Roo.Element */
37370         this.bodyEl = this.el.createChild({tag: "div", cls: "x-layout-panel-body"});
37371     },
37372
37373     applyConfig : function(c){
37374         if(c.collapsible && this.position != "center" && !this.collapsedEl){
37375             var dh = Roo.DomHelper;
37376             if(c.titlebar !== false){
37377                 this.collapseBtn = this.createTool(this.tools.dom, "x-layout-collapse-"+this.position);
37378                 this.collapseBtn.on("click", this.collapse, this);
37379                 this.collapseBtn.enableDisplayMode();
37380
37381                 if(c.showPin === true || this.showPin){
37382                     this.stickBtn = this.createTool(this.tools.dom, "x-layout-stick");
37383                     this.stickBtn.enableDisplayMode();
37384                     this.stickBtn.on("click", this.expand, this);
37385                     this.stickBtn.hide();
37386                 }
37387             }
37388             /** This region's collapsed element
37389             * @type Roo.Element */
37390             this.collapsedEl = dh.append(this.mgr.el.dom, {cls: "x-layout-collapsed x-layout-collapsed-"+this.position, children:[
37391                 {cls: "x-layout-collapsed-tools", children:[{cls: "x-layout-ctools-inner"}]}
37392             ]}, true);
37393             if(c.floatable !== false){
37394                this.collapsedEl.addClassOnOver("x-layout-collapsed-over");
37395                this.collapsedEl.on("click", this.collapseClick, this);
37396             }
37397
37398             if(c.collapsedTitle && (this.position == "north" || this.position== "south")) {
37399                 this.collapsedTitleTextEl = dh.append(this.collapsedEl.dom, {tag: "div", cls: "x-unselectable x-layout-panel-hd-text",
37400                    id: "message", unselectable: "on", style:{"float":"left"}});
37401                this.collapsedTitleTextEl.innerHTML = c.collapsedTitle;
37402              }
37403             this.expandBtn = this.createTool(this.collapsedEl.dom.firstChild.firstChild, "x-layout-expand-"+this.position);
37404             this.expandBtn.on("click", this.expand, this);
37405         }
37406         if(this.collapseBtn){
37407             this.collapseBtn.setVisible(c.collapsible == true);
37408         }
37409         this.cmargins = c.cmargins || this.cmargins ||
37410                          (this.position == "west" || this.position == "east" ?
37411                              {top: 0, left: 2, right:2, bottom: 0} :
37412                              {top: 2, left: 0, right:0, bottom: 2});
37413         this.margins = c.margins || this.margins || {top: 0, left: 0, right:0, bottom: 0};
37414         this.bottomTabs = c.tabPosition != "top";
37415         this.autoScroll = c.autoScroll || false;
37416         if(this.autoScroll){
37417             this.bodyEl.setStyle("overflow", "auto");
37418         }else{
37419             this.bodyEl.setStyle("overflow", "hidden");
37420         }
37421         //if(c.titlebar !== false){
37422             if((!c.titlebar && !c.title) || c.titlebar === false){
37423                 this.titleEl.hide();
37424             }else{
37425                 this.titleEl.show();
37426                 if(c.title){
37427                     this.titleTextEl.innerHTML = c.title;
37428                 }
37429             }
37430         //}
37431         this.duration = c.duration || .30;
37432         this.slideDuration = c.slideDuration || .45;
37433         this.config = c;
37434         if(c.collapsed){
37435             this.collapse(true);
37436         }
37437         if(c.hidden){
37438             this.hide();
37439         }
37440     },
37441     /**
37442      * Returns true if this region is currently visible.
37443      * @return {Boolean}
37444      */
37445     isVisible : function(){
37446         return this.visible;
37447     },
37448
37449     /**
37450      * Updates the title for collapsed north/south regions (used with {@link #collapsedTitle} config option)
37451      * @param {String} title (optional) The title text (accepts HTML markup, defaults to the numeric character reference for a non-breaking space, "&amp;#160;")
37452      */
37453     setCollapsedTitle : function(title){
37454         title = title || "&#160;";
37455         if(this.collapsedTitleTextEl){
37456             this.collapsedTitleTextEl.innerHTML = title;
37457         }
37458     },
37459
37460     getBox : function(){
37461         var b;
37462         if(!this.collapsed){
37463             b = this.el.getBox(false, true);
37464         }else{
37465             b = this.collapsedEl.getBox(false, true);
37466         }
37467         return b;
37468     },
37469
37470     getMargins : function(){
37471         return this.collapsed ? this.cmargins : this.margins;
37472     },
37473
37474     highlight : function(){
37475         this.el.addClass("x-layout-panel-dragover");
37476     },
37477
37478     unhighlight : function(){
37479         this.el.removeClass("x-layout-panel-dragover");
37480     },
37481
37482     updateBox : function(box){
37483         this.box = box;
37484         if(!this.collapsed){
37485             this.el.dom.style.left = box.x + "px";
37486             this.el.dom.style.top = box.y + "px";
37487             this.updateBody(box.width, box.height);
37488         }else{
37489             this.collapsedEl.dom.style.left = box.x + "px";
37490             this.collapsedEl.dom.style.top = box.y + "px";
37491             this.collapsedEl.setSize(box.width, box.height);
37492         }
37493         if(this.tabs){
37494             this.tabs.autoSizeTabs();
37495         }
37496     },
37497
37498     updateBody : function(w, h){
37499         if(w !== null){
37500             this.el.setWidth(w);
37501             w -= this.el.getBorderWidth("rl");
37502             if(this.config.adjustments){
37503                 w += this.config.adjustments[0];
37504             }
37505         }
37506         if(h !== null){
37507             this.el.setHeight(h);
37508             h = this.titleEl && this.titleEl.isDisplayed() ? h - (this.titleEl.getHeight()||0) : h;
37509             h -= this.el.getBorderWidth("tb");
37510             if(this.config.adjustments){
37511                 h += this.config.adjustments[1];
37512             }
37513             this.bodyEl.setHeight(h);
37514             if(this.tabs){
37515                 h = this.tabs.syncHeight(h);
37516             }
37517         }
37518         if(this.panelSize){
37519             w = w !== null ? w : this.panelSize.width;
37520             h = h !== null ? h : this.panelSize.height;
37521         }
37522         if(this.activePanel){
37523             var el = this.activePanel.getEl();
37524             w = w !== null ? w : el.getWidth();
37525             h = h !== null ? h : el.getHeight();
37526             this.panelSize = {width: w, height: h};
37527             this.activePanel.setSize(w, h);
37528         }
37529         if(Roo.isIE && this.tabs){
37530             this.tabs.el.repaint();
37531         }
37532     },
37533
37534     /**
37535      * Returns the container element for this region.
37536      * @return {Roo.Element}
37537      */
37538     getEl : function(){
37539         return this.el;
37540     },
37541
37542     /**
37543      * Hides this region.
37544      */
37545     hide : function(){
37546         if(!this.collapsed){
37547             this.el.dom.style.left = "-2000px";
37548             this.el.hide();
37549         }else{
37550             this.collapsedEl.dom.style.left = "-2000px";
37551             this.collapsedEl.hide();
37552         }
37553         this.visible = false;
37554         this.fireEvent("visibilitychange", this, false);
37555     },
37556
37557     /**
37558      * Shows this region if it was previously hidden.
37559      */
37560     show : function(){
37561         if(!this.collapsed){
37562             this.el.show();
37563         }else{
37564             this.collapsedEl.show();
37565         }
37566         this.visible = true;
37567         this.fireEvent("visibilitychange", this, true);
37568     },
37569
37570     closeClicked : function(){
37571         if(this.activePanel){
37572             this.remove(this.activePanel);
37573         }
37574     },
37575
37576     collapseClick : function(e){
37577         if(this.isSlid){
37578            e.stopPropagation();
37579            this.slideIn();
37580         }else{
37581            e.stopPropagation();
37582            this.slideOut();
37583         }
37584     },
37585
37586     /**
37587      * Collapses this region.
37588      * @param {Boolean} skipAnim (optional) true to collapse the element without animation (if animate is true)
37589      */
37590     collapse : function(skipAnim, skipCheck){
37591         if(this.collapsed) {
37592             return;
37593         }
37594         
37595         if(skipCheck || this.fireEvent("beforecollapse", this) != false){
37596             
37597             this.collapsed = true;
37598             if(this.split){
37599                 this.split.el.hide();
37600             }
37601             if(this.config.animate && skipAnim !== true){
37602                 this.fireEvent("invalidated", this);
37603                 this.animateCollapse();
37604             }else{
37605                 this.el.setLocation(-20000,-20000);
37606                 this.el.hide();
37607                 this.collapsedEl.show();
37608                 this.fireEvent("collapsed", this);
37609                 this.fireEvent("invalidated", this);
37610             }
37611         }
37612         
37613     },
37614
37615     animateCollapse : function(){
37616         // overridden
37617     },
37618
37619     /**
37620      * Expands this region if it was previously collapsed.
37621      * @param {Roo.EventObject} e The event that triggered the expand (or null if calling manually)
37622      * @param {Boolean} skipAnim (optional) true to expand the element without animation (if animate is true)
37623      */
37624     expand : function(e, skipAnim){
37625         if(e) {
37626             e.stopPropagation();
37627         }
37628         if(!this.collapsed || this.el.hasActiveFx()) {
37629             return;
37630         }
37631         if(this.isSlid){
37632             this.afterSlideIn();
37633             skipAnim = true;
37634         }
37635         this.collapsed = false;
37636         if(this.config.animate && skipAnim !== true){
37637             this.animateExpand();
37638         }else{
37639             this.el.show();
37640             if(this.split){
37641                 this.split.el.show();
37642             }
37643             this.collapsedEl.setLocation(-2000,-2000);
37644             this.collapsedEl.hide();
37645             this.fireEvent("invalidated", this);
37646             this.fireEvent("expanded", this);
37647         }
37648     },
37649
37650     animateExpand : function(){
37651         // overridden
37652     },
37653
37654     initTabs : function()
37655     {
37656         this.bodyEl.setStyle("overflow", "hidden");
37657         var ts = new Roo.panel.Tab(
37658                 this.bodyEl.dom,
37659                 {
37660                     tabPosition: this.bottomTabs ? 'bottom' : 'top',
37661                     disableTooltips: this.config.disableTabTips,
37662                     toolbar : this.config.toolbar
37663                 }
37664         );
37665         if(this.config.hideTabs){
37666             ts.stripWrap.setDisplayed(false);
37667         }
37668         this.tabs = ts;
37669         ts.resizeTabs = this.config.resizeTabs === true;
37670         ts.minTabWidth = this.config.minTabWidth || 40;
37671         ts.maxTabWidth = this.config.maxTabWidth || 250;
37672         ts.preferredTabWidth = this.config.preferredTabWidth || 150;
37673         ts.monitorResize = false;
37674         ts.bodyEl.setStyle("overflow", this.config.autoScroll ? "auto" : "hidden");
37675         ts.bodyEl.addClass('x-layout-tabs-body');
37676         this.panels.each(this.initPanelAsTab, this);
37677     },
37678
37679     initPanelAsTab : function(panel){
37680         var ti = this.tabs.addTab(panel.getEl().id, panel.getTitle(), null,
37681                     this.config.closeOnTab && panel.isClosable());
37682         if(panel.tabTip !== undefined){
37683             ti.setTooltip(panel.tabTip);
37684         }
37685         ti.on("activate", function(){
37686               this.setActivePanel(panel);
37687         }, this);
37688         if(this.config.closeOnTab){
37689             ti.on("beforeclose", function(t, e){
37690                 e.cancel = true;
37691                 this.remove(panel);
37692             }, this);
37693         }
37694         return ti;
37695     },
37696
37697     updatePanelTitle : function(panel, title){
37698         if(this.activePanel == panel){
37699             this.updateTitle(title);
37700         }
37701         if(this.tabs){
37702             var ti = this.tabs.getTab(panel.getEl().id);
37703             ti.setText(title);
37704             if(panel.tabTip !== undefined){
37705                 ti.setTooltip(panel.tabTip);
37706             }
37707         }
37708     },
37709
37710     updateTitle : function(title){
37711         if(this.titleTextEl && !this.config.title){
37712             this.titleTextEl.innerHTML = (typeof title != "undefined" && title.length > 0 ? title : "&#160;");
37713         }
37714     },
37715
37716     setActivePanel : function(panel){
37717         panel = this.getPanel(panel);
37718         if(this.activePanel && this.activePanel != panel){
37719             this.activePanel.setActiveState(false);
37720         }
37721         this.activePanel = panel;
37722         panel.setActiveState(true);
37723         if(this.panelSize){
37724             panel.setSize(this.panelSize.width, this.panelSize.height);
37725         }
37726         if(this.closeBtn){
37727             this.closeBtn.setVisible(!this.config.closeOnTab && !this.isSlid && panel.isClosable());
37728         }
37729         this.updateTitle(panel.getTitle());
37730         if(this.tabs){
37731             this.fireEvent("invalidated", this);
37732         }
37733         this.fireEvent("panelactivated", this, panel);
37734     },
37735
37736     /**
37737      * Shows the specified panel.
37738      * @param {Number/String/panel.Content} panelId The panel's index, id or the panel itself
37739      * @return {Roo.panel.Content} The shown panel, or null if a panel could not be found from panelId
37740      */
37741     showPanel : function(panel)
37742     {
37743         panel = this.getPanel(panel);
37744         if(panel){
37745             if(this.tabs){
37746                 var tab = this.tabs.getTab(panel.getEl().id);
37747                 if(tab.isHidden()){
37748                     this.tabs.unhideTab(tab.id);
37749                 }
37750                 tab.activate();
37751             }else{
37752                 this.setActivePanel(panel);
37753             }
37754         }
37755         return panel;
37756     },
37757
37758     /**
37759      * Get the active panel for this region.
37760      * @return {Roo.panel.Content} The active panel or null
37761      */
37762     getActivePanel : function(){
37763         return this.activePanel;
37764     },
37765
37766     validateVisibility : function(){
37767         if(this.panels.getCount() < 1){
37768             this.updateTitle("&#160;");
37769             this.closeBtn.hide();
37770             this.hide();
37771         }else{
37772             if(!this.isVisible()){
37773                 this.show();
37774             }
37775         }
37776     },
37777
37778     /**
37779      * Adds the passed ContentPanel(s) to this region.
37780      * @param {panel.Content...} panel The ContentPanel(s) to add (you can pass more than one)
37781      * @return {Roo.panel.Content} The panel added (if only one was added; null otherwise)
37782      */
37783     add : function(panel){
37784         if(arguments.length > 1){
37785             for(var i = 0, len = arguments.length; i < len; i++) {
37786                 this.add(arguments[i]);
37787             }
37788             return null;
37789         }
37790         if(this.hasPanel(panel)){
37791             this.showPanel(panel);
37792             return panel;
37793         }
37794         panel.setRegion(this);
37795         this.panels.add(panel);
37796         if(this.panels.getCount() == 1 && !this.config.alwaysShowTabs){
37797             this.bodyEl.dom.appendChild(panel.getEl().dom);
37798             if(panel.background !== true){
37799                 this.setActivePanel(panel);
37800             }
37801             this.fireEvent("paneladded", this, panel);
37802             return panel;
37803         }
37804         if(!this.tabs){
37805             this.initTabs();
37806         }else{
37807             this.initPanelAsTab(panel);
37808         }
37809         if(panel.background !== true){
37810             this.tabs.activate(panel.getEl().id);
37811         }
37812         this.fireEvent("paneladded", this, panel);
37813         return panel;
37814     },
37815
37816     /**
37817      * Hides the tab for the specified panel.
37818      * @param {Number/String/panel.Content} panel The panel's index, id or the panel itself
37819      */
37820     hidePanel : function(panel){
37821         if(this.tabs && (panel = this.getPanel(panel))){
37822             this.tabs.hideTab(panel.getEl().id);
37823         }
37824     },
37825
37826     /**
37827      * Unhides the tab for a previously hidden panel.
37828      * @param {Number/String/panel.Content} panel The panel's index, id or the panel itself
37829      */
37830     unhidePanel : function(panel){
37831         if(this.tabs && (panel = this.getPanel(panel))){
37832             this.tabs.unhideTab(panel.getEl().id);
37833         }
37834     },
37835
37836     clearPanels : function(){
37837         while(this.panels.getCount() > 0){
37838              this.remove(this.panels.first());
37839         }
37840     },
37841
37842     /**
37843      * Removes the specified panel. If preservePanel is not true (either here or in the config), the panel is destroyed.
37844      * @param {Number/String/panel.Content} panel The panel's index, id or the panel itself
37845      * @param {Boolean} preservePanel Overrides the config preservePanel option
37846      * @return {Roo.panel.Content} The panel that was removed
37847      */
37848     remove : function(panel, preservePanel){
37849         panel = this.getPanel(panel);
37850         if(!panel){
37851             return null;
37852         }
37853         var e = {};
37854         this.fireEvent("beforeremove", this, panel, e);
37855         if(e.cancel === true){
37856             return null;
37857         }
37858         preservePanel = (typeof preservePanel != "undefined" ? preservePanel : (this.config.preservePanels === true || panel.preserve === true));
37859         var panelId = panel.getId();
37860         this.panels.removeKey(panelId);
37861         if(preservePanel){
37862             document.body.appendChild(panel.getEl().dom);
37863         }
37864         if(this.tabs){
37865             this.tabs.removeTab(panel.getEl().id);
37866         }else if (!preservePanel){
37867             this.bodyEl.dom.removeChild(panel.getEl().dom);
37868         }
37869         if(this.panels.getCount() == 1 && this.tabs && !this.config.alwaysShowTabs){
37870             var p = this.panels.first();
37871             var tempEl = document.createElement("div"); // temp holder to keep IE from deleting the node
37872             tempEl.appendChild(p.getEl().dom);
37873             this.bodyEl.update("");
37874             this.bodyEl.dom.appendChild(p.getEl().dom);
37875             tempEl = null;
37876             this.updateTitle(p.getTitle());
37877             this.tabs = null;
37878             this.bodyEl.setStyle("overflow", this.config.autoScroll ? "auto" : "hidden");
37879             this.setActivePanel(p);
37880         }
37881         panel.setRegion(null);
37882         if(this.activePanel == panel){
37883             this.activePanel = null;
37884         }
37885         if(this.config.autoDestroy !== false && preservePanel !== true){
37886             try{panel.destroy();}catch(e){}
37887         }
37888         this.fireEvent("panelremoved", this, panel);
37889         return panel;
37890     },
37891
37892     /**
37893      * Returns the TabPanel component used by this region
37894      * @return {Roo.panel.Tab}
37895      */
37896     getTabs : function(){
37897         return this.tabs;
37898     },
37899
37900     createTool : function(parentEl, className){
37901         var btn = Roo.DomHelper.append(parentEl, {tag: "div", cls: "x-layout-tools-button",
37902             children: [{tag: "div", cls: "x-layout-tools-button-inner " + className, html: "&#160;"}]}, true);
37903         btn.addClassOnOver("x-layout-tools-button-over");
37904         return btn;
37905     }
37906 });/*
37907  * Based on:
37908  * Ext JS Library 1.1.1
37909  * Copyright(c) 2006-2007, Ext JS, LLC.
37910  *
37911  * Originally Released Under LGPL - original licence link has changed is not relivant.
37912  *
37913  * Fork - LGPL
37914  * <script type="text/javascript">
37915  */
37916  
37917
37918
37919 /**
37920  * @class Roo.layout.SplitRegion
37921  * @extends Roo.layout.Region
37922  * Adds a splitbar and other (private) useful functionality to a {@link Roo.layout.Region}.
37923  */
37924 Roo.layout.SplitRegion = function(mgr, config, pos, cursor){
37925     this.cursor = cursor;
37926     Roo.layout.SplitRegion.superclass.constructor.call(this, mgr, config, pos);
37927 };
37928
37929 Roo.extend(Roo.layout.SplitRegion, Roo.layout.Region, {
37930     splitTip : "Drag to resize.",
37931     collapsibleSplitTip : "Drag to resize. Double click to hide.",
37932     useSplitTips : false,
37933
37934     applyConfig : function(config){
37935         Roo.layout.SplitRegion.superclass.applyConfig.call(this, config);
37936         if(config.split){
37937             if(!this.split){
37938                 var splitEl = Roo.DomHelper.append(this.mgr.el.dom, 
37939                         {tag: "div", id: this.el.id + "-split", cls: "x-layout-split x-layout-split-"+this.position, html: "&#160;"});
37940                 /** The SplitBar for this region 
37941                 * @type Roo.SplitBar */
37942                 this.split = new Roo.SplitBar(splitEl, this.el, this.orientation);
37943                 this.split.on("moved", this.onSplitMove, this);
37944                 this.split.useShim = config.useShim === true;
37945                 this.split.getMaximumSize = this[this.position == 'north' || this.position == 'south' ? 'getVMaxSize' : 'getHMaxSize'].createDelegate(this);
37946                 if(this.useSplitTips){
37947                     this.split.el.dom.title = config.collapsible ? this.collapsibleSplitTip : this.splitTip;
37948                 }
37949                 if(config.collapsible){
37950                     this.split.el.on("dblclick", this.collapse,  this);
37951                 }
37952             }
37953             if(typeof config.minSize != "undefined"){
37954                 this.split.minSize = config.minSize;
37955             }
37956             if(typeof config.maxSize != "undefined"){
37957                 this.split.maxSize = config.maxSize;
37958             }
37959             if(config.hideWhenEmpty || config.hidden || config.collapsed){
37960                 this.hideSplitter();
37961             }
37962         }
37963     },
37964
37965     getHMaxSize : function(){
37966          var cmax = this.config.maxSize || 10000;
37967          var center = this.mgr.getRegion("center");
37968          return Math.min(cmax, (this.el.getWidth()+center.getEl().getWidth())-center.getMinWidth());
37969     },
37970
37971     getVMaxSize : function(){
37972          var cmax = this.config.maxSize || 10000;
37973          var center = this.mgr.getRegion("center");
37974          return Math.min(cmax, (this.el.getHeight()+center.getEl().getHeight())-center.getMinHeight());
37975     },
37976
37977     onSplitMove : function(split, newSize){
37978         this.fireEvent("resized", this, newSize);
37979     },
37980     
37981     /** 
37982      * Returns the {@link Roo.SplitBar} for this region.
37983      * @return {Roo.SplitBar}
37984      */
37985     getSplitBar : function(){
37986         return this.split;
37987     },
37988     
37989     hide : function(){
37990         this.hideSplitter();
37991         Roo.layout.SplitRegion.superclass.hide.call(this);
37992     },
37993
37994     hideSplitter : function(){
37995         if(this.split){
37996             this.split.el.setLocation(-2000,-2000);
37997             this.split.el.hide();
37998         }
37999     },
38000
38001     show : function(){
38002         if(this.split){
38003             this.split.el.show();
38004         }
38005         Roo.layout.SplitRegion.superclass.show.call(this);
38006     },
38007     
38008     beforeSlide: function(){
38009         if(Roo.isGecko){// firefox overflow auto bug workaround
38010             this.bodyEl.clip();
38011             if(this.tabs) {
38012                 this.tabs.bodyEl.clip();
38013             }
38014             if(this.activePanel){
38015                 this.activePanel.getEl().clip();
38016                 
38017                 if(this.activePanel.beforeSlide){
38018                     this.activePanel.beforeSlide();
38019                 }
38020             }
38021         }
38022     },
38023     
38024     afterSlide : function(){
38025         if(Roo.isGecko){// firefox overflow auto bug workaround
38026             this.bodyEl.unclip();
38027             if(this.tabs) {
38028                 this.tabs.bodyEl.unclip();
38029             }
38030             if(this.activePanel){
38031                 this.activePanel.getEl().unclip();
38032                 if(this.activePanel.afterSlide){
38033                     this.activePanel.afterSlide();
38034                 }
38035             }
38036         }
38037     },
38038
38039     initAutoHide : function(){
38040         if(this.autoHide !== false){
38041             if(!this.autoHideHd){
38042                 var st = new Roo.util.DelayedTask(this.slideIn, this);
38043                 this.autoHideHd = {
38044                     "mouseout": function(e){
38045                         if(!e.within(this.el, true)){
38046                             st.delay(500);
38047                         }
38048                     },
38049                     "mouseover" : function(e){
38050                         st.cancel();
38051                     },
38052                     scope : this
38053                 };
38054             }
38055             this.el.on(this.autoHideHd);
38056         }
38057     },
38058
38059     clearAutoHide : function(){
38060         if(this.autoHide !== false){
38061             this.el.un("mouseout", this.autoHideHd.mouseout);
38062             this.el.un("mouseover", this.autoHideHd.mouseover);
38063         }
38064     },
38065
38066     clearMonitor : function(){
38067         Roo.get(document).un("click", this.slideInIf, this);
38068     },
38069
38070     // these names are backwards but not changed for compat
38071     slideOut : function(){
38072         if(this.isSlid || this.el.hasActiveFx()){
38073             return;
38074         }
38075         this.isSlid = true;
38076         if(this.collapseBtn){
38077             this.collapseBtn.hide();
38078         }
38079         this.closeBtnState = this.closeBtn.getStyle('display');
38080         this.closeBtn.hide();
38081         if(this.stickBtn){
38082             this.stickBtn.show();
38083         }
38084         this.el.show();
38085         this.el.alignTo(this.collapsedEl, this.getCollapseAnchor());
38086         this.beforeSlide();
38087         this.el.setStyle("z-index", 10001);
38088         this.el.slideIn(this.getSlideAnchor(), {
38089             callback: function(){
38090                 this.afterSlide();
38091                 this.initAutoHide();
38092                 Roo.get(document).on("click", this.slideInIf, this);
38093                 this.fireEvent("slideshow", this);
38094             },
38095             scope: this,
38096             block: true
38097         });
38098     },
38099
38100     afterSlideIn : function(){
38101         this.clearAutoHide();
38102         this.isSlid = false;
38103         this.clearMonitor();
38104         this.el.setStyle("z-index", "");
38105         if(this.collapseBtn){
38106             this.collapseBtn.show();
38107         }
38108         this.closeBtn.setStyle('display', this.closeBtnState);
38109         if(this.stickBtn){
38110             this.stickBtn.hide();
38111         }
38112         this.fireEvent("slidehide", this);
38113     },
38114
38115     slideIn : function(cb){
38116         if(!this.isSlid || this.el.hasActiveFx()){
38117             Roo.callback(cb);
38118             return;
38119         }
38120         this.isSlid = false;
38121         this.beforeSlide();
38122         this.el.slideOut(this.getSlideAnchor(), {
38123             callback: function(){
38124                 this.el.setLeftTop(-10000, -10000);
38125                 this.afterSlide();
38126                 this.afterSlideIn();
38127                 Roo.callback(cb);
38128             },
38129             scope: this,
38130             block: true
38131         });
38132     },
38133     
38134     slideInIf : function(e){
38135         if(!e.within(this.el)){
38136             this.slideIn();
38137         }
38138     },
38139
38140     animateCollapse : function(){
38141         this.beforeSlide();
38142         this.el.setStyle("z-index", 20000);
38143         var anchor = this.getSlideAnchor();
38144         this.el.slideOut(anchor, {
38145             callback : function(){
38146                 this.el.setStyle("z-index", "");
38147                 this.collapsedEl.slideIn(anchor, {duration:.3});
38148                 this.afterSlide();
38149                 this.el.setLocation(-10000,-10000);
38150                 this.el.hide();
38151                 this.fireEvent("collapsed", this);
38152             },
38153             scope: this,
38154             block: true
38155         });
38156     },
38157
38158     animateExpand : function(){
38159         this.beforeSlide();
38160         this.el.alignTo(this.collapsedEl, this.getCollapseAnchor(), this.getExpandAdj());
38161         this.el.setStyle("z-index", 20000);
38162         this.collapsedEl.hide({
38163             duration:.1
38164         });
38165         this.el.slideIn(this.getSlideAnchor(), {
38166             callback : function(){
38167                 this.el.setStyle("z-index", "");
38168                 this.afterSlide();
38169                 if(this.split){
38170                     this.split.el.show();
38171                 }
38172                 this.fireEvent("invalidated", this);
38173                 this.fireEvent("expanded", this);
38174             },
38175             scope: this,
38176             block: true
38177         });
38178     },
38179
38180     anchors : {
38181         "west" : "left",
38182         "east" : "right",
38183         "north" : "top",
38184         "south" : "bottom"
38185     },
38186
38187     sanchors : {
38188         "west" : "l",
38189         "east" : "r",
38190         "north" : "t",
38191         "south" : "b"
38192     },
38193
38194     canchors : {
38195         "west" : "tl-tr",
38196         "east" : "tr-tl",
38197         "north" : "tl-bl",
38198         "south" : "bl-tl"
38199     },
38200
38201     getAnchor : function(){
38202         return this.anchors[this.position];
38203     },
38204
38205     getCollapseAnchor : function(){
38206         return this.canchors[this.position];
38207     },
38208
38209     getSlideAnchor : function(){
38210         return this.sanchors[this.position];
38211     },
38212
38213     getAlignAdj : function(){
38214         var cm = this.cmargins;
38215         switch(this.position){
38216             case "west":
38217                 return [0, 0];
38218             break;
38219             case "east":
38220                 return [0, 0];
38221             break;
38222             case "north":
38223                 return [0, 0];
38224             break;
38225             case "south":
38226                 return [0, 0];
38227             break;
38228         }
38229     },
38230
38231     getExpandAdj : function(){
38232         var c = this.collapsedEl, cm = this.cmargins;
38233         switch(this.position){
38234             case "west":
38235                 return [-(cm.right+c.getWidth()+cm.left), 0];
38236             break;
38237             case "east":
38238                 return [cm.right+c.getWidth()+cm.left, 0];
38239             break;
38240             case "north":
38241                 return [0, -(cm.top+cm.bottom+c.getHeight())];
38242             break;
38243             case "south":
38244                 return [0, cm.top+cm.bottom+c.getHeight()];
38245             break;
38246         }
38247     }
38248 });/*
38249  * Based on:
38250  * Ext JS Library 1.1.1
38251  * Copyright(c) 2006-2007, Ext JS, LLC.
38252  *
38253  * Originally Released Under LGPL - original licence link has changed is not relivant.
38254  *
38255  * Fork - LGPL
38256  * <script type="text/javascript">
38257  */
38258 /*
38259  * These classes are private internal classes
38260  */
38261 Roo.layout.Center = function(mgr, config){
38262     Roo.layout.Region.call(this, mgr, config, "center");
38263     this.visible = true;
38264     this.minWidth = config.minWidth || 20;
38265     this.minHeight = config.minHeight || 20;
38266 };
38267
38268 Roo.extend(Roo.layout.Center, Roo.layout.Region, {
38269     hide : function(){
38270         // center panel can't be hidden
38271     },
38272     
38273     show : function(){
38274         // center panel can't be hidden
38275     },
38276     
38277     getMinWidth: function(){
38278         return this.minWidth;
38279     },
38280     
38281     getMinHeight: function(){
38282         return this.minHeight;
38283     }
38284 });
38285 Roo.layout.West = function(mgr, config){
38286     Roo.layout.SplitRegion.call(this, mgr, config, "west", "w-resize");
38287     if(this.split){
38288         this.split.placement = Roo.SplitBar.LEFT;
38289         this.split.orientation = Roo.SplitBar.HORIZONTAL;
38290         this.split.el.addClass("x-layout-split-h");
38291     }
38292     var size = config.initialSize || config.width;
38293     if(typeof size != "undefined"){
38294         this.el.setWidth(size);
38295     }
38296 };
38297 Roo.extend(Roo.layout.West, Roo.layout.SplitRegion, {
38298     orientation: Roo.SplitBar.HORIZONTAL,
38299     getBox : function(){
38300         if(this.collapsed){
38301             return this.collapsedEl.getBox();
38302         }
38303         var box = this.el.getBox();
38304         if(this.split){
38305             box.width += this.split.el.getWidth();
38306         }
38307         return box;
38308     },
38309     
38310     updateBox : function(box){
38311         if(this.split && !this.collapsed){
38312             var sw = this.split.el.getWidth();
38313             box.width -= sw;
38314             this.split.el.setLeft(box.x+box.width);
38315             this.split.el.setTop(box.y);
38316             this.split.el.setHeight(box.height);
38317         }
38318         if(this.collapsed){
38319             this.updateBody(null, box.height);
38320         }
38321         Roo.layout.Region.prototype.updateBox.call(this, box);
38322     }
38323 });
38324 Roo.layout.East = function(mgr, config){
38325     Roo.layout.SplitRegion.call(this, mgr, config, "east", "e-resize");
38326     if(this.split){
38327         this.split.placement = Roo.SplitBar.RIGHT;
38328         this.split.orientation = Roo.SplitBar.HORIZONTAL;
38329         this.split.el.addClass("x-layout-split-h");
38330     }
38331     var size = config.initialSize || config.width;
38332     if(typeof size != "undefined"){
38333         this.el.setWidth(size);
38334     }
38335 };
38336 Roo.extend(Roo.layout.East, Roo.layout.SplitRegion, {
38337     orientation: Roo.SplitBar.HORIZONTAL,
38338     getBox : function(){
38339         if(this.collapsed){
38340             return this.collapsedEl.getBox();
38341         }
38342         var box = this.el.getBox();
38343         if(this.split){
38344             var sw = this.split.el.getWidth();
38345             box.width += sw;
38346             box.x -= sw;
38347         }
38348         return box;
38349     },
38350
38351     updateBox : function(box){
38352         if(this.split && !this.collapsed){
38353             var sw = this.split.el.getWidth();
38354             box.width -= sw;
38355             this.split.el.setLeft(box.x);
38356             this.split.el.setTop(box.y);
38357             this.split.el.setHeight(box.height);
38358             box.x += sw;
38359         }
38360         if(this.collapsed){
38361             this.updateBody(null, box.height);
38362         }
38363         Roo.layout.Region.prototype.updateBox.call(this, box);
38364     }
38365 });Roo.layout.South = function(mgr, config){
38366     Roo.layout.SplitRegion.call(this, mgr, config, "south", "s-resize");
38367     if(this.split){
38368         this.split.placement = Roo.SplitBar.BOTTOM;
38369         this.split.orientation = Roo.SplitBar.VERTICAL;
38370         this.split.el.addClass("x-layout-split-v");
38371     }
38372     var size = config.initialSize || config.height;
38373     if(typeof size != "undefined"){
38374         this.el.setHeight(size);
38375     }
38376 };
38377 Roo.extend(Roo.layout.South, Roo.layout.SplitRegion, {
38378     orientation: Roo.SplitBar.VERTICAL,
38379     getBox : function(){
38380         if(this.collapsed){
38381             return this.collapsedEl.getBox();
38382         }
38383         var box = this.el.getBox();
38384         if(this.split){
38385             var sh = this.split.el.getHeight();
38386             box.height += sh;
38387             box.y -= sh;
38388         }
38389         return box;
38390     },
38391     
38392     updateBox : function(box){
38393         if(this.split && !this.collapsed){
38394             var sh = this.split.el.getHeight();
38395             box.height -= sh;
38396             box.y += sh;
38397             this.split.el.setLeft(box.x);
38398             this.split.el.setTop(box.y-sh);
38399             this.split.el.setWidth(box.width);
38400         }
38401         if(this.collapsed){
38402             this.updateBody(box.width, null);
38403         }
38404         Roo.layout.Region.prototype.updateBox.call(this, box);
38405     }
38406 });
38407
38408
38409 Roo.layout.North = function(mgr, config){
38410     Roo.layout.Region.call(this, mgr, config, "north", "n-resize");
38411     if(this.split){
38412         this.split.placement = Roo.SplitBar.TOP;
38413         this.split.orientation = Roo.SplitBar.VERTICAL;
38414         this.split.el.addClass("x-layout-split-v");
38415     }
38416     var size = config.initialSize || config.height;
38417     if(typeof size != "undefined"){
38418         this.el.setHeight(size);
38419     }
38420 };
38421 Roo.extend(Roo.layout.North, Roo.layout.SplitRegion, {
38422     orientation: Roo.SplitBar.VERTICAL,
38423     getBox : function(){
38424         if(this.collapsed){
38425             return this.collapsedEl.getBox();
38426         }
38427         var box = this.el.getBox();
38428         if(this.split){
38429             box.height += this.split.el.getHeight();
38430         }
38431         return box;
38432     },
38433     
38434     updateBox : function(box){
38435         if(this.split && !this.collapsed){
38436             box.height -= this.split.el.getHeight();
38437             this.split.el.setLeft(box.x);
38438             this.split.el.setTop(box.y+box.height);
38439             this.split.el.setWidth(box.width);
38440         }
38441         if(this.collapsed){
38442             this.updateBody(box.width, null);
38443         }
38444         Roo.layout.Region.prototype.updateBox.call(this, box);
38445     }
38446 });/*
38447  * Based on:
38448  * Ext JS Library 1.1.1
38449  * Copyright(c) 2006-2007, Ext JS, LLC.
38450  *
38451  * Originally Released Under LGPL - original licence link has changed is not relivant.
38452  *
38453  * Fork - LGPL
38454  * <script type="text/javascript">
38455  */
38456  
38457  
38458 /*
38459  * Private internal class for reading and applying state
38460  */
38461 Roo.layout.StateManager = function(layout){
38462      // default empty state
38463      this.state = {
38464         north: {},
38465         south: {},
38466         east: {},
38467         west: {}       
38468     };
38469 };
38470
38471 Roo.layout.StateManager.prototype = {
38472     init : function(layout, provider){
38473         this.provider = provider;
38474         var state = provider.get(layout.id+"-layout-state");
38475         if(state){
38476             var wasUpdating = layout.isUpdating();
38477             if(!wasUpdating){
38478                 layout.beginUpdate();
38479             }
38480             for(var key in state){
38481                 if(typeof state[key] != "function"){
38482                     var rstate = state[key];
38483                     var r = layout.getRegion(key);
38484                     if(r && rstate){
38485                         if(rstate.size){
38486                             r.resizeTo(rstate.size);
38487                         }
38488                         if(rstate.collapsed == true){
38489                             r.collapse(true);
38490                         }else{
38491                             r.expand(null, true);
38492                         }
38493                     }
38494                 }
38495             }
38496             if(!wasUpdating){
38497                 layout.endUpdate();
38498             }
38499             this.state = state; 
38500         }
38501         this.layout = layout;
38502         layout.on("regionresized", this.onRegionResized, this);
38503         layout.on("regioncollapsed", this.onRegionCollapsed, this);
38504         layout.on("regionexpanded", this.onRegionExpanded, this);
38505     },
38506     
38507     storeState : function(){
38508         this.provider.set(this.layout.id+"-layout-state", this.state);
38509     },
38510     
38511     onRegionResized : function(region, newSize){
38512         this.state[region.getPosition()].size = newSize;
38513         this.storeState();
38514     },
38515     
38516     onRegionCollapsed : function(region){
38517         this.state[region.getPosition()].collapsed = true;
38518         this.storeState();
38519     },
38520     
38521     onRegionExpanded : function(region){
38522         this.state[region.getPosition()].collapsed = false;
38523         this.storeState();
38524     }
38525 };/*
38526  * Based on:
38527  * Ext JS Library 1.1.1
38528  * Copyright(c) 2006-2007, Ext JS, LLC.
38529  *
38530  * Originally Released Under LGPL - original licence link has changed is not relivant.
38531  *
38532  * Fork - LGPL
38533  * <script type="text/javascript">
38534  */
38535 /**
38536  * @class Roo.panel.Content
38537  * @extends Roo.util.Observable
38538  * @children Roo.form.Form Roo.JsonView Roo.View
38539  * @parent Roo.layout.Border Roo.LayoutDialog builder
38540  * A basic Content Panel element.
38541  * @cfg {Boolean}   fitToFrame    True for this panel to adjust its size to fit when the region resizes  (defaults to false)
38542  * @cfg {Boolean}   fitContainer   When using {@link #fitToFrame} and {@link #resizeEl}, you can also fit the parent container  (defaults to false)
38543  * @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
38544  * @cfg {Boolean}   closable      True if the panel can be closed/removed
38545  * @cfg {Boolean}   background    True if the panel should not be activated when it is added (defaults to false)
38546  * @cfg {String|HTMLElement|Element} resizeEl An element to resize if {@link #fitToFrame} is true (instead of this panel's element)
38547  * @cfg {Roo.Toolbar}   toolbar       A toolbar for this panel
38548  * @cfg {Boolean} autoScroll    True to scroll overflow in this panel (use with {@link #fitToFrame})
38549  * @cfg {String} title          The title for this panel
38550  * @cfg {Array} adjustments     Values to <b>add</b> to the width/height when doing a {@link #fitToFrame} (default is [0, 0])
38551  * @cfg {String} url            Calls {@link #setUrl} with this value
38552  * @cfg {String} region (center|north|south|east|west) [required] which region to put this panel on (when used with xtype constructors)
38553  * @cfg {String|Object} params  When used with {@link #url}, calls {@link #setUrl} with this value
38554  * @cfg {Boolean} loadOnce      When used with {@link #url}, calls {@link #setUrl} with this value
38555  * @cfg {String}    content        Raw content to fill content panel with (uses setContent on construction.)
38556  * @cfg {String}    style  Extra style to add to the content panel
38557  * @cfg {Roo.menu.Menu} menu  popup menu
38558
38559  * @constructor
38560  * Create a new Content Panel.
38561  * @param {String/HTMLElement/Roo.Element} el The container element for this panel
38562  * @param {String/Object} config A string to set only the title or a config object
38563  * @param {String} content (optional) Set the HTML content for this panel
38564  * @param {String} region (optional) Used by xtype constructors to add to regions. (values center,east,west,south,north)
38565  */
38566 Roo.panel.Content = function(el, config, content){
38567     
38568     /*
38569     if(el.autoCreate || el.xtype){ // xtype is available if this is called from factory
38570         config = el;
38571         el = Roo.id();
38572     }
38573     if (config && config.parentLayout) { 
38574         el = config.parentLayout.el.createChild(); 
38575     }
38576     */
38577     if(el.autoCreate){ // xtype is available if this is called from factory
38578         config = el;
38579         el = Roo.id();
38580     }
38581     this.el = Roo.get(el);
38582     if(!this.el && config && config.autoCreate){
38583         if(typeof config.autoCreate == "object"){
38584             if(!config.autoCreate.id){
38585                 config.autoCreate.id = config.id||el;
38586             }
38587             this.el = Roo.DomHelper.append(document.body,
38588                         config.autoCreate, true);
38589         }else{
38590             this.el = Roo.DomHelper.append(document.body,
38591                         {tag: "div", cls: "x-layout-inactive-content", id: config.id||el}, true);
38592         }
38593     }
38594     
38595     
38596     this.closable = false;
38597     this.loaded = false;
38598     this.active = false;
38599     if(typeof config == "string"){
38600         this.title = config;
38601     }else{
38602         Roo.apply(this, config);
38603     }
38604     
38605     if (this.toolbar && !this.toolbar.el && this.toolbar.xtype) {
38606         this.wrapEl = this.el.wrap();
38607         this.toolbar.container = this.el.insertSibling(false, 'before');
38608         this.toolbar = new Roo.Toolbar(this.toolbar);
38609     }
38610     
38611     // xtype created footer. - not sure if will work as we normally have to render first..
38612     if (this.footer && !this.footer.el && this.footer.xtype) {
38613         if (!this.wrapEl) {
38614             this.wrapEl = this.el.wrap();
38615         }
38616     
38617         this.footer.container = this.wrapEl.createChild();
38618          
38619         this.footer = Roo.factory(this.footer, Roo);
38620         
38621     }
38622     
38623     if(this.resizeEl){
38624         this.resizeEl = Roo.get(this.resizeEl, true);
38625     }else{
38626         this.resizeEl = this.el;
38627     }
38628     // handle view.xtype
38629     
38630  
38631     
38632     
38633     this.addEvents({
38634         /**
38635          * @event activate
38636          * Fires when this panel is activated. 
38637          * @param {Roo.panel.Content} this
38638          */
38639         "activate" : true,
38640         /**
38641          * @event deactivate
38642          * Fires when this panel is activated. 
38643          * @param {Roo.panel.Content} this
38644          */
38645         "deactivate" : true,
38646
38647         /**
38648          * @event resize
38649          * Fires when this panel is resized if fitToFrame is true.
38650          * @param {Roo.panel.Content} this
38651          * @param {Number} width The width after any component adjustments
38652          * @param {Number} height The height after any component adjustments
38653          */
38654         "resize" : true,
38655         
38656          /**
38657          * @event render
38658          * Fires when this tab is created
38659          * @param {Roo.panel.Content} this
38660          */
38661         "render" : true
38662          
38663         
38664     });
38665     
38666
38667     
38668     
38669     if(this.autoScroll){
38670         this.resizeEl.setStyle("overflow", "auto");
38671     } else {
38672         // fix randome scrolling
38673         this.el.on('scroll', function() {
38674             Roo.log('fix random scolling');
38675             this.scrollTo('top',0); 
38676         });
38677     }
38678     content = content || this.content;
38679     if(content){
38680         this.setContent(content);
38681     }
38682     if(config && config.url){
38683         this.setUrl(this.url, this.params, this.loadOnce);
38684     }
38685     
38686     
38687     
38688     Roo.panel.Content.superclass.constructor.call(this);
38689     
38690     if (this.view && typeof(this.view.xtype) != 'undefined') {
38691         this.view.el = this.el.appendChild(document.createElement("div"));
38692         this.view = Roo.factory(this.view); 
38693         this.view.render  &&  this.view.render(false, '');  
38694     }
38695     
38696     
38697     this.fireEvent('render', this);
38698 };
38699
38700 Roo.extend(Roo.panel.Content, Roo.util.Observable, {
38701     tabTip:'',
38702     setRegion : function(region){
38703         this.region = region;
38704         if(region){
38705            this.el.replaceClass("x-layout-inactive-content", "x-layout-active-content");
38706         }else{
38707            this.el.replaceClass("x-layout-active-content", "x-layout-inactive-content");
38708         } 
38709     },
38710     
38711     /**
38712      * Returns the toolbar for this Panel if one was configured. 
38713      * @return {Roo.Toolbar} 
38714      */
38715     getToolbar : function(){
38716         return this.toolbar;
38717     },
38718     
38719     setActiveState : function(active){
38720         this.active = active;
38721         if(!active){
38722             this.fireEvent("deactivate", this);
38723         }else{
38724             this.fireEvent("activate", this);
38725         }
38726     },
38727     /**
38728      * Updates this panel's element
38729      * @param {String} content The new content
38730      * @param {Boolean} loadScripts (optional) true to look for and process scripts
38731     */
38732     setContent : function(content, loadScripts){
38733         this.el.update(content, loadScripts);
38734     },
38735
38736     ignoreResize : function(w, h){
38737         if(this.lastSize && this.lastSize.width == w && this.lastSize.height == h){
38738             return true;
38739         }else{
38740             this.lastSize = {width: w, height: h};
38741             return false;
38742         }
38743     },
38744     /**
38745      * Get the {@link Roo.UpdateManager} for this panel. Enables you to perform Ajax updates.
38746      * @return {Roo.UpdateManager} The UpdateManager
38747      */
38748     getUpdateManager : function(){
38749         return this.el.getUpdateManager();
38750     },
38751      /**
38752      * Loads this content panel immediately with content from XHR. Note: to delay loading until the panel is activated, use {@link #setUrl}.
38753      * @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:
38754 <pre><code>
38755 panel.load({
38756     url: "your-url.php",
38757     params: {param1: "foo", param2: "bar"}, // or a URL encoded string
38758     callback: yourFunction,
38759     scope: yourObject, //(optional scope)
38760     discardUrl: false,
38761     nocache: false,
38762     text: "Loading...",
38763     timeout: 30,
38764     scripts: false
38765 });
38766 </code></pre>
38767      * The only required property is <i>url</i>. The optional properties <i>nocache</i>, <i>text</i> and <i>scripts</i>
38768      * 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.
38769      * @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}
38770      * @param {Function} callback (optional) Callback when transaction is complete -- called with signature (oElement, bSuccess, oResponse)
38771      * @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.
38772      * @return {Roo.panel.Content} this
38773      */
38774     load : function(){
38775         var um = this.el.getUpdateManager();
38776         um.update.apply(um, arguments);
38777         return this;
38778     },
38779
38780
38781     /**
38782      * 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.
38783      * @param {String/Function} url The URL to load the content from or a function to call to get the URL
38784      * @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)
38785      * @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)
38786      * @return {Roo.UpdateManager} The UpdateManager
38787      */
38788     setUrl : function(url, params, loadOnce){
38789         if(this.refreshDelegate){
38790             this.removeListener("activate", this.refreshDelegate);
38791         }
38792         this.refreshDelegate = this._handleRefresh.createDelegate(this, [url, params, loadOnce]);
38793         this.on("activate", this.refreshDelegate);
38794         return this.el.getUpdateManager();
38795     },
38796     
38797     _handleRefresh : function(url, params, loadOnce){
38798         if(!loadOnce || !this.loaded){
38799             var updater = this.el.getUpdateManager();
38800             updater.update(url, params, this._setLoaded.createDelegate(this));
38801         }
38802     },
38803     
38804     _setLoaded : function(){
38805         this.loaded = true;
38806     }, 
38807     
38808     /**
38809      * Returns this panel's id
38810      * @return {String} 
38811      */
38812     getId : function(){
38813         return this.el.id;
38814     },
38815     
38816     /** 
38817      * Returns this panel's element - used by regiosn to add.
38818      * @return {Roo.Element} 
38819      */
38820     getEl : function(){
38821         return this.wrapEl || this.el;
38822     },
38823     
38824     adjustForComponents : function(width, height)
38825     {
38826         //Roo.log('adjustForComponents ');
38827         if(this.resizeEl != this.el){
38828             width -= this.el.getFrameWidth('lr');
38829             height -= this.el.getFrameWidth('tb');
38830         }
38831         if(this.toolbar){
38832             var te = this.toolbar.getEl();
38833             height -= te.getHeight();
38834             te.setWidth(width);
38835         }
38836         if(this.footer){
38837             var te = this.footer.getEl();
38838             //Roo.log("footer:" + te.getHeight());
38839             
38840             height -= te.getHeight();
38841             te.setWidth(width);
38842         }
38843         
38844         
38845         if(this.adjustments){
38846             width += this.adjustments[0];
38847             height += this.adjustments[1];
38848         }
38849         return {"width": width, "height": height};
38850     },
38851     
38852     setSize : function(width, height){
38853         if(this.fitToFrame && !this.ignoreResize(width, height)){
38854             if(this.fitContainer && this.resizeEl != this.el){
38855                 this.el.setSize(width, height);
38856             }
38857             var size = this.adjustForComponents(width, height);
38858             this.resizeEl.setSize(this.autoWidth ? "auto" : size.width, this.autoHeight ? "auto" : size.height);
38859             this.fireEvent('resize', this, size.width, size.height);
38860         }
38861     },
38862     
38863     /**
38864      * Returns this panel's title
38865      * @return {String} 
38866      */
38867     getTitle : function(){
38868         return this.title;
38869     },
38870     
38871     /**
38872      * Set this panel's title
38873      * @param {String} title
38874      */
38875     setTitle : function(title){
38876         this.title = title;
38877         if(this.region){
38878             this.region.updatePanelTitle(this, title);
38879         }
38880     },
38881     
38882     /**
38883      * Returns true is this panel was configured to be closable
38884      * @return {Boolean} 
38885      */
38886     isClosable : function(){
38887         return this.closable;
38888     },
38889     
38890     beforeSlide : function(){
38891         this.el.clip();
38892         this.resizeEl.clip();
38893     },
38894     
38895     afterSlide : function(){
38896         this.el.unclip();
38897         this.resizeEl.unclip();
38898     },
38899     
38900     /**
38901      *   Force a content refresh from the URL specified in the {@link #setUrl} method.
38902      *   Will fail silently if the {@link #setUrl} method has not been called.
38903      *   This does not activate the panel, just updates its content.
38904      */
38905     refresh : function(){
38906         if(this.refreshDelegate){
38907            this.loaded = false;
38908            this.refreshDelegate();
38909         }
38910     },
38911     
38912     /**
38913      * Destroys this panel
38914      */
38915     destroy : function(){
38916         this.el.removeAllListeners();
38917         var tempEl = document.createElement("span");
38918         tempEl.appendChild(this.el.dom);
38919         tempEl.innerHTML = "";
38920         this.el.remove();
38921         this.el = null;
38922     },
38923     
38924     /**
38925      * form - if the content panel contains a form - this is a reference to it.
38926      * @type {Roo.form.Form}
38927      */
38928     form : false,
38929     /**
38930      * view - if the content panel contains a view (Roo.DatePicker / Roo.View / Roo.JsonView)
38931      *    This contains a reference to it.
38932      * @type {Roo.View}
38933      */
38934     view : false,
38935     
38936       /**
38937      * Adds a xtype elements to the panel - currently only supports Forms, View, JsonView.
38938      * <pre><code>
38939
38940 layout.addxtype({
38941        xtype : 'Form',
38942        items: [ .... ]
38943    }
38944 );
38945
38946 </code></pre>
38947      * @param {Object} cfg Xtype definition of item to add.
38948      */
38949     
38950     addxtype : function(cfg) {
38951         if(cfg.xtype.match(/^Cropbox$/)) {
38952
38953             this.cropbox = new Roo.factory(cfg);
38954
38955             this.cropbox.render(this.el);
38956
38957             return this.cropbox;
38958         }
38959         // add form..
38960         if (cfg.xtype.match(/^Form$/)) {
38961             
38962             var el;
38963             //if (this.footer) {
38964             //    el = this.footer.container.insertSibling(false, 'before');
38965             //} else {
38966                 el = this.el.createChild();
38967             //}
38968
38969             this.form = new  Roo.form.Form(cfg);
38970             
38971             
38972             if ( this.form.allItems.length) {
38973                 this.form.render(el.dom);
38974             }
38975             return this.form;
38976         }
38977         // should only have one of theses..
38978         if ([ 'View', 'JsonView', 'DatePicker'].indexOf(cfg.xtype) > -1) {
38979             // views.. should not be just added - used named prop 'view''
38980             
38981             cfg.el = this.el.appendChild(document.createElement("div"));
38982             // factory?
38983             
38984             var ret = new Roo.factory(cfg);
38985              
38986              ret.render && ret.render(false, ''); // render blank..
38987             this.view = ret;
38988             return ret;
38989         }
38990         return false;
38991     }
38992 });
38993
38994
38995
38996
38997
38998
38999
39000
39001
39002
39003
39004
39005 /**
39006  * @class Roo.panel.Grid
39007  * @extends Roo.panel.Content
39008  * @parent Roo.layout.Border Roo.LayoutDialog builder
39009  * @constructor
39010  * Create a new GridPanel.
39011  * @cfg {Roo.grid.Grid} grid The grid for this panel
39012  */
39013 Roo.panel.Grid = function(grid, config){
39014     
39015     // universal ctor...
39016     if (typeof(grid.grid) != 'undefined') {
39017         config = grid;
39018         grid = config.grid;
39019     }
39020     this.wrapper = Roo.DomHelper.append(document.body, // wrapper for IE7 strict & safari scroll issue
39021         {tag: "div", cls: "x-layout-grid-wrapper x-layout-inactive-content"}, true);
39022         
39023     this.wrapper.dom.appendChild(grid.getGridEl().dom);
39024     
39025     Roo.panel.Grid.superclass.constructor.call(this, this.wrapper, config);
39026     
39027     if(this.toolbar){
39028         this.toolbar.el.insertBefore(this.wrapper.dom.firstChild);
39029     }
39030     // xtype created footer. - not sure if will work as we normally have to render first..
39031     if (this.footer && !this.footer.el && this.footer.xtype) {
39032         
39033         this.footer.container = this.grid.getView().getFooterPanel(true);
39034         this.footer.dataSource = this.grid.dataSource;
39035         this.footer = Roo.factory(this.footer, Roo);
39036         
39037     }
39038     
39039     grid.monitorWindowResize = false; // turn off autosizing
39040     grid.autoHeight = false;
39041     grid.autoWidth = false;
39042     this.grid = grid;
39043     this.grid.getGridEl().replaceClass("x-layout-inactive-content", "x-layout-component-panel");
39044 };
39045
39046 Roo.extend(Roo.panel.Grid, Roo.panel.Content, {
39047     getId : function(){
39048         return this.grid.id;
39049     },
39050     
39051     /**
39052      * Returns the grid for this panel
39053      * @return {Roo.grid.Grid} 
39054      */
39055     getGrid : function(){
39056         return this.grid;    
39057     },
39058     
39059     setSize : function(width, height){
39060         if(!this.ignoreResize(width, height)){
39061             var grid = this.grid;
39062             var size = this.adjustForComponents(width, height);
39063             grid.getGridEl().setSize(size.width, size.height);
39064             grid.autoSize();
39065         }
39066     },
39067     
39068     beforeSlide : function(){
39069         this.grid.getView().scroller.clip();
39070     },
39071     
39072     afterSlide : function(){
39073         this.grid.getView().scroller.unclip();
39074     },
39075     
39076     destroy : function(){
39077         this.grid.destroy();
39078         delete this.grid;
39079         Roo.panel.Grid.superclass.destroy.call(this); 
39080     }
39081 });
39082
39083
39084 /**
39085  * @class Roo.panel.NestedLayout
39086  * @extends Roo.panel.Content
39087  * @parent Roo.layout.Border Roo.LayoutDialog builder
39088  * @cfg {Roo.layout.Border} layout   [required] The layout for this panel
39089  *
39090  * 
39091  * @constructor
39092  * Create a new NestedLayoutPanel.
39093  * 
39094  * 
39095  * @param {Roo.layout.Border} layout [required] The layout for this panel
39096  * @param {String/Object} config A string to set only the title or a config object
39097  */
39098 Roo.panel.NestedLayout = function(layout, config)
39099 {
39100     // construct with only one argument..
39101     /* FIXME - implement nicer consturctors
39102     if (layout.layout) {
39103         config = layout;
39104         layout = config.layout;
39105         delete config.layout;
39106     }
39107     if (layout.xtype && !layout.getEl) {
39108         // then layout needs constructing..
39109         layout = Roo.factory(layout, Roo);
39110     }
39111     */
39112     
39113     
39114     Roo.panel.NestedLayout.superclass.constructor.call(this, layout.getEl(), config);
39115     
39116     layout.monitorWindowResize = false; // turn off autosizing
39117     this.layout = layout;
39118     this.layout.getEl().addClass("x-layout-nested-layout");
39119     
39120     
39121     
39122     
39123 };
39124
39125 Roo.extend(Roo.panel.NestedLayout, Roo.panel.Content, {
39126
39127     layout : false,
39128
39129     setSize : function(width, height){
39130         if(!this.ignoreResize(width, height)){
39131             var size = this.adjustForComponents(width, height);
39132             var el = this.layout.getEl();
39133             el.setSize(size.width, size.height);
39134             var touch = el.dom.offsetWidth;
39135             this.layout.layout();
39136             // ie requires a double layout on the first pass
39137             if(Roo.isIE && !this.initialized){
39138                 this.initialized = true;
39139                 this.layout.layout();
39140             }
39141         }
39142     },
39143     
39144     // activate all subpanels if not currently active..
39145     
39146     setActiveState : function(active){
39147         this.active = active;
39148         if(!active){
39149             this.fireEvent("deactivate", this);
39150             return;
39151         }
39152         
39153         this.fireEvent("activate", this);
39154         // not sure if this should happen before or after..
39155         if (!this.layout) {
39156             return; // should not happen..
39157         }
39158         var reg = false;
39159         for (var r in this.layout.regions) {
39160             reg = this.layout.getRegion(r);
39161             if (reg.getActivePanel()) {
39162                 //reg.showPanel(reg.getActivePanel()); // force it to activate.. 
39163                 reg.setActivePanel(reg.getActivePanel());
39164                 continue;
39165             }
39166             if (!reg.panels.length) {
39167                 continue;
39168             }
39169             reg.showPanel(reg.getPanel(0));
39170         }
39171         
39172         
39173         
39174         
39175     },
39176     
39177     /**
39178      * Returns the nested BorderLayout for this panel
39179      * @return {Roo.layout.Border}
39180      */
39181     getLayout : function(){
39182         return this.layout;
39183     },
39184     
39185      /**
39186      * Adds a xtype elements to the layout of the nested panel
39187      * <pre><code>
39188
39189 panel.addxtype({
39190        xtype : 'ContentPanel',
39191        region: 'west',
39192        items: [ .... ]
39193    }
39194 );
39195
39196 panel.addxtype({
39197         xtype : 'panel.NestedLayout',
39198         region: 'west',
39199         layout: {
39200            center: { },
39201            west: { }   
39202         },
39203         items : [ ... list of content panels or nested layout panels.. ]
39204    }
39205 );
39206 </code></pre>
39207      * @param {Object} cfg Xtype definition of item to add.
39208      */
39209     addxtype : function(cfg) {
39210         return this.layout.addxtype(cfg);
39211     
39212     }
39213 });
39214
39215 Roo.panel.Scroll = function(el, config, content){
39216     config = config || {};
39217     config.fitToFrame = true;
39218     Roo.panel.Scroll.superclass.constructor.call(this, el, config, content);
39219     
39220     this.el.dom.style.overflow = "hidden";
39221     var wrap = this.el.wrap({cls: "x-scroller x-layout-inactive-content"});
39222     this.el.removeClass("x-layout-inactive-content");
39223     this.el.on("mousewheel", this.onWheel, this);
39224
39225     var up = wrap.createChild({cls: "x-scroller-up", html: "&#160;"}, this.el.dom);
39226     var down = wrap.createChild({cls: "x-scroller-down", html: "&#160;"});
39227     up.unselectable(); down.unselectable();
39228     up.on("click", this.scrollUp, this);
39229     down.on("click", this.scrollDown, this);
39230     up.addClassOnOver("x-scroller-btn-over");
39231     down.addClassOnOver("x-scroller-btn-over");
39232     up.addClassOnClick("x-scroller-btn-click");
39233     down.addClassOnClick("x-scroller-btn-click");
39234     this.adjustments = [0, -(up.getHeight() + down.getHeight())];
39235
39236     this.resizeEl = this.el;
39237     this.el = wrap; this.up = up; this.down = down;
39238 };
39239
39240 Roo.extend(Roo.panel.Scroll, Roo.panel.Content, {
39241     increment : 100,
39242     wheelIncrement : 5,
39243     scrollUp : function(){
39244         this.resizeEl.scroll("up", this.increment, {callback: this.afterScroll, scope: this});
39245     },
39246
39247     scrollDown : function(){
39248         this.resizeEl.scroll("down", this.increment, {callback: this.afterScroll, scope: this});
39249     },
39250
39251     afterScroll : function(){
39252         var el = this.resizeEl;
39253         var t = el.dom.scrollTop, h = el.dom.scrollHeight, ch = el.dom.clientHeight;
39254         this.up[t == 0 ? "addClass" : "removeClass"]("x-scroller-btn-disabled");
39255         this.down[h - t <= ch ? "addClass" : "removeClass"]("x-scroller-btn-disabled");
39256     },
39257
39258     setSize : function(){
39259         Roo.panel.Scroll.superclass.setSize.apply(this, arguments);
39260         this.afterScroll();
39261     },
39262
39263     onWheel : function(e){
39264         var d = e.getWheelDelta();
39265         this.resizeEl.dom.scrollTop -= (d*this.wheelIncrement);
39266         this.afterScroll();
39267         e.stopEvent();
39268     },
39269
39270     setContent : function(content, loadScripts){
39271         this.resizeEl.update(content, loadScripts);
39272     }
39273
39274 });
39275
39276
39277
39278 /**
39279  * @class Roo.panel.Tree
39280  * @extends Roo.panel.Content
39281  * @parent Roo.layout.Border Roo.LayoutDialog builder
39282  * Treepanel component
39283  * 
39284  * @constructor
39285  * Create a new TreePanel. - defaults to fit/scoll contents.
39286  * @param {String/Object} config A string to set only the panel's title, or a config object
39287  */
39288 Roo.panel.Tree = function(config){
39289     var el = config.el;
39290     var tree = config.tree;
39291     delete config.tree; 
39292     delete config.el; // hopefull!
39293     
39294     // wrapper for IE7 strict & safari scroll issue
39295     
39296     var treeEl = el.createChild();
39297     config.resizeEl = treeEl;
39298     
39299     
39300     
39301     Roo.panel.Tree.superclass.constructor.call(this, el, config);
39302  
39303  
39304     this.tree = new Roo.tree.TreePanel(treeEl , tree);
39305     //console.log(tree);
39306     this.on('activate', function()
39307     {
39308         if (this.tree.rendered) {
39309             return;
39310         }
39311         //console.log('render tree');
39312         this.tree.render();
39313     });
39314     // this should not be needed.. - it's actually the 'el' that resizes?
39315     // actuall it breaks the containerScroll - dragging nodes auto scroll at top
39316     
39317     //this.on('resize',  function (cp, w, h) {
39318     //        this.tree.innerCt.setWidth(w);
39319     //        this.tree.innerCt.setHeight(h);
39320     //        //this.tree.innerCt.setStyle('overflow-y', 'auto');
39321     //});
39322
39323         
39324     
39325 };
39326
39327 Roo.extend(Roo.panel.Tree, Roo.panel.Content, {   
39328     fitToFrame : true,
39329     autoScroll : true,
39330     /*
39331      * @cfg {Roo.tree.panel.Tree} tree [required] The tree TreePanel, with config etc.
39332      */
39333     tree : false
39334
39335 });
39336 /*
39337  * Based on:
39338  * Ext JS Library 1.1.1
39339  * Copyright(c) 2006-2007, Ext JS, LLC.
39340  *
39341  * Originally Released Under LGPL - original licence link has changed is not relivant.
39342  *
39343  * Fork - LGPL
39344  * <script type="text/javascript">
39345  */
39346  
39347
39348 /**
39349  * @class Roo.layout.Reader
39350  * @extends Roo.layout.Border
39351  * This is a pre-built layout that represents a classic, 5-pane application.  It consists of a header, a primary
39352  * center region containing two nested regions (a top one for a list view and one for item preview below),
39353  * and regions on either side that can be used for navigation, application commands, informational displays, etc.
39354  * The setup and configuration work exactly the same as it does for a {@link Roo.layout.Border} - this class simply
39355  * expedites the setup of the overall layout and regions for this common application style.
39356  * Example:
39357  <pre><code>
39358 var reader = new Roo.layout.Reader();
39359 var CP = Roo.panel.Content;  // shortcut for adding
39360
39361 reader.beginUpdate();
39362 reader.add("north", new CP("north", "North"));
39363 reader.add("west", new CP("west", {title: "West"}));
39364 reader.add("east", new CP("east", {title: "East"}));
39365
39366 reader.regions.listView.add(new CP("listView", "List"));
39367 reader.regions.preview.add(new CP("preview", "Preview"));
39368 reader.endUpdate();
39369 </code></pre>
39370 * @constructor
39371 * Create a new ReaderLayout
39372 * @param {Object} config Configuration options
39373 * @param {String/HTMLElement/Element} container (optional) The container this layout is bound to (defaults to
39374 * document.body if omitted)
39375 */
39376 Roo.layout.Reader = function(config, renderTo){
39377     var c = config || {size:{}};
39378     Roo.layout.Reader.superclass.constructor.call(this, renderTo || document.body, {
39379         north: c.north !== false ? Roo.apply({
39380             split:false,
39381             initialSize: 32,
39382             titlebar: false
39383         }, c.north) : false,
39384         west: c.west !== false ? Roo.apply({
39385             split:true,
39386             initialSize: 200,
39387             minSize: 175,
39388             maxSize: 400,
39389             titlebar: true,
39390             collapsible: true,
39391             animate: true,
39392             margins:{left:5,right:0,bottom:5,top:5},
39393             cmargins:{left:5,right:5,bottom:5,top:5}
39394         }, c.west) : false,
39395         east: c.east !== false ? Roo.apply({
39396             split:true,
39397             initialSize: 200,
39398             minSize: 175,
39399             maxSize: 400,
39400             titlebar: true,
39401             collapsible: true,
39402             animate: true,
39403             margins:{left:0,right:5,bottom:5,top:5},
39404             cmargins:{left:5,right:5,bottom:5,top:5}
39405         }, c.east) : false,
39406         center: Roo.apply({
39407             tabPosition: 'top',
39408             autoScroll:false,
39409             closeOnTab: true,
39410             titlebar:false,
39411             margins:{left:c.west!==false ? 0 : 5,right:c.east!==false ? 0 : 5,bottom:5,top:2}
39412         }, c.center)
39413     });
39414
39415     this.el.addClass('x-reader');
39416
39417     this.beginUpdate();
39418
39419     var inner = new Roo.layout.Border(Roo.get(document.body).createChild(), {
39420         south: c.preview !== false ? Roo.apply({
39421             split:true,
39422             initialSize: 200,
39423             minSize: 100,
39424             autoScroll:true,
39425             collapsible:true,
39426             titlebar: true,
39427             cmargins:{top:5,left:0, right:0, bottom:0}
39428         }, c.preview) : false,
39429         center: Roo.apply({
39430             autoScroll:false,
39431             titlebar:false,
39432             minHeight:200
39433         }, c.listView)
39434     });
39435     this.add('center', new Roo.panel.NestedLayout(inner,
39436             Roo.apply({title: c.mainTitle || '',tabTip:''},c.innerPanelCfg)));
39437
39438     this.endUpdate();
39439
39440     this.regions.preview = inner.getRegion('south');
39441     this.regions.listView = inner.getRegion('center');
39442 };
39443
39444 Roo.extend(Roo.layout.Reader, Roo.layout.Border);/*
39445  * Based on:
39446  * Ext JS Library 1.1.1
39447  * Copyright(c) 2006-2007, Ext JS, LLC.
39448  *
39449  * Originally Released Under LGPL - original licence link has changed is not relivant.
39450  *
39451  * Fork - LGPL
39452  * <script type="text/javascript">
39453  */
39454  
39455 /**
39456  * @class Roo.grid.Grid
39457  * @extends Roo.util.Observable
39458  * This class represents the primary interface of a component based grid control.
39459  * <br><br>Usage:<pre><code>
39460  var grid = new Roo.grid.Grid("my-container-id", {
39461      ds: myDataStore,
39462      cm: myColModel,
39463      selModel: mySelectionModel,
39464      autoSizeColumns: true,
39465      monitorWindowResize: false,
39466      trackMouseOver: true
39467  });
39468  // set any options
39469  grid.render();
39470  * </code></pre>
39471  * <b>Common Problems:</b><br/>
39472  * - Grid does not resize properly when going smaller: Setting overflow hidden on the container
39473  * element will correct this<br/>
39474  * - If you get el.style[camel]= NaNpx or -2px or something related, be certain you have given your container element
39475  * dimensions. The grid adapts to your container's size, if your container has no size defined then the results
39476  * are unpredictable.<br/>
39477  * - Do not render the grid into an element with display:none. Try using visibility:hidden. Otherwise there is no way for the
39478  * grid to calculate dimensions/offsets.<br/>
39479   * @constructor
39480  * @param {String/HTMLElement/Roo.Element} container The element into which this grid will be rendered -
39481  * The container MUST have some type of size defined for the grid to fill. The container will be
39482  * automatically set to position relative if it isn't already.
39483  * @param {Object} config A config object that sets properties on this grid.
39484  */
39485 Roo.grid.Grid = function(container, config){
39486         // initialize the container
39487         this.container = Roo.get(container);
39488         this.container.update("");
39489         this.container.setStyle("overflow", "hidden");
39490     this.container.addClass('x-grid-container');
39491
39492     this.id = this.container.id;
39493
39494     Roo.apply(this, config);
39495     // check and correct shorthanded configs
39496     if(this.ds){
39497         this.dataSource = this.ds;
39498         delete this.ds;
39499     }
39500     if(this.cm){
39501         this.colModel = this.cm;
39502         delete this.cm;
39503     }
39504     if(this.sm){
39505         this.selModel = this.sm;
39506         delete this.sm;
39507     }
39508
39509     if (this.selModel) {
39510         this.selModel = Roo.factory(this.selModel, Roo.grid);
39511         this.sm = this.selModel;
39512         this.sm.xmodule = this.xmodule || false;
39513     }
39514     if (typeof(this.colModel.config) == 'undefined') {
39515         this.colModel = new Roo.grid.ColumnModel(this.colModel);
39516         this.cm = this.colModel;
39517         this.cm.xmodule = this.xmodule || false;
39518     }
39519     if (this.dataSource) {
39520         this.dataSource= Roo.factory(this.dataSource, Roo.data);
39521         this.ds = this.dataSource;
39522         this.ds.xmodule = this.xmodule || false;
39523          
39524     }
39525     
39526     
39527     
39528     if(this.width){
39529         this.container.setWidth(this.width);
39530     }
39531
39532     if(this.height){
39533         this.container.setHeight(this.height);
39534     }
39535     /** @private */
39536         this.addEvents({
39537         // raw events
39538         /**
39539          * @event click
39540          * The raw click event for the entire grid.
39541          * @param {Roo.EventObject} e
39542          */
39543         "click" : true,
39544         /**
39545          * @event dblclick
39546          * The raw dblclick event for the entire grid.
39547          * @param {Roo.EventObject} e
39548          */
39549         "dblclick" : true,
39550         /**
39551          * @event contextmenu
39552          * The raw contextmenu event for the entire grid.
39553          * @param {Roo.EventObject} e
39554          */
39555         "contextmenu" : true,
39556         /**
39557          * @event mousedown
39558          * The raw mousedown event for the entire grid.
39559          * @param {Roo.EventObject} e
39560          */
39561         "mousedown" : true,
39562         /**
39563          * @event mouseup
39564          * The raw mouseup event for the entire grid.
39565          * @param {Roo.EventObject} e
39566          */
39567         "mouseup" : true,
39568         /**
39569          * @event mouseover
39570          * The raw mouseover event for the entire grid.
39571          * @param {Roo.EventObject} e
39572          */
39573         "mouseover" : true,
39574         /**
39575          * @event mouseout
39576          * The raw mouseout event for the entire grid.
39577          * @param {Roo.EventObject} e
39578          */
39579         "mouseout" : true,
39580         /**
39581          * @event keypress
39582          * The raw keypress event for the entire grid.
39583          * @param {Roo.EventObject} e
39584          */
39585         "keypress" : true,
39586         /**
39587          * @event keydown
39588          * The raw keydown event for the entire grid.
39589          * @param {Roo.EventObject} e
39590          */
39591         "keydown" : true,
39592
39593         // custom events
39594
39595         /**
39596          * @event cellclick
39597          * Fires when a cell is clicked
39598          * @param {Grid} this
39599          * @param {Number} rowIndex
39600          * @param {Number} columnIndex
39601          * @param {Roo.EventObject} e
39602          */
39603         "cellclick" : true,
39604         /**
39605          * @event celldblclick
39606          * Fires when a cell is double clicked
39607          * @param {Grid} this
39608          * @param {Number} rowIndex
39609          * @param {Number} columnIndex
39610          * @param {Roo.EventObject} e
39611          */
39612         "celldblclick" : true,
39613         /**
39614          * @event rowclick
39615          * Fires when a row is clicked
39616          * @param {Grid} this
39617          * @param {Number} rowIndex
39618          * @param {Roo.EventObject} e
39619          */
39620         "rowclick" : true,
39621         /**
39622          * @event rowdblclick
39623          * Fires when a row is double clicked
39624          * @param {Grid} this
39625          * @param {Number} rowIndex
39626          * @param {Roo.EventObject} e
39627          */
39628         "rowdblclick" : true,
39629         /**
39630          * @event headerclick
39631          * Fires when a header is clicked
39632          * @param {Grid} this
39633          * @param {Number} columnIndex
39634          * @param {Roo.EventObject} e
39635          */
39636         "headerclick" : true,
39637         /**
39638          * @event headerdblclick
39639          * Fires when a header cell is double clicked
39640          * @param {Grid} this
39641          * @param {Number} columnIndex
39642          * @param {Roo.EventObject} e
39643          */
39644         "headerdblclick" : true,
39645         /**
39646          * @event rowcontextmenu
39647          * Fires when a row is right clicked
39648          * @param {Grid} this
39649          * @param {Number} rowIndex
39650          * @param {Roo.EventObject} e
39651          */
39652         "rowcontextmenu" : true,
39653         /**
39654          * @event cellcontextmenu
39655          * Fires when a cell is right clicked
39656          * @param {Grid} this
39657          * @param {Number} rowIndex
39658          * @param {Number} cellIndex
39659          * @param {Roo.EventObject} e
39660          */
39661          "cellcontextmenu" : true,
39662         /**
39663          * @event headercontextmenu
39664          * Fires when a header is right clicked
39665          * @param {Grid} this
39666          * @param {Number} columnIndex
39667          * @param {Roo.EventObject} e
39668          */
39669         "headercontextmenu" : true,
39670         /**
39671          * @event bodyscroll
39672          * Fires when the body element is scrolled
39673          * @param {Number} scrollLeft
39674          * @param {Number} scrollTop
39675          */
39676         "bodyscroll" : true,
39677         /**
39678          * @event columnresize
39679          * Fires when the user resizes a column
39680          * @param {Number} columnIndex
39681          * @param {Number} newSize
39682          */
39683         "columnresize" : true,
39684         /**
39685          * @event columnmove
39686          * Fires when the user moves a column
39687          * @param {Number} oldIndex
39688          * @param {Number} newIndex
39689          */
39690         "columnmove" : true,
39691         /**
39692          * @event startdrag
39693          * Fires when row(s) start being dragged
39694          * @param {Grid} this
39695          * @param {Roo.GridDD} dd The drag drop object
39696          * @param {event} e The raw browser event
39697          */
39698         "startdrag" : true,
39699         /**
39700          * @event enddrag
39701          * Fires when a drag operation is complete
39702          * @param {Grid} this
39703          * @param {Roo.GridDD} dd The drag drop object
39704          * @param {event} e The raw browser event
39705          */
39706         "enddrag" : true,
39707         /**
39708          * @event dragdrop
39709          * Fires when dragged row(s) are dropped on a valid DD target
39710          * @param {Grid} this
39711          * @param {Roo.GridDD} dd The drag drop object
39712          * @param {String} targetId The target drag drop object
39713          * @param {event} e The raw browser event
39714          */
39715         "dragdrop" : true,
39716         /**
39717          * @event dragover
39718          * Fires while row(s) are being dragged. "targetId" is the id of the Yahoo.util.DD object the selected rows are being dragged over.
39719          * @param {Grid} this
39720          * @param {Roo.GridDD} dd The drag drop object
39721          * @param {String} targetId The target drag drop object
39722          * @param {event} e The raw browser event
39723          */
39724         "dragover" : true,
39725         /**
39726          * @event dragenter
39727          *  Fires when the dragged row(s) first cross another DD target while being dragged
39728          * @param {Grid} this
39729          * @param {Roo.GridDD} dd The drag drop object
39730          * @param {String} targetId The target drag drop object
39731          * @param {event} e The raw browser event
39732          */
39733         "dragenter" : true,
39734         /**
39735          * @event dragout
39736          * Fires when the dragged row(s) leave another DD target while being dragged
39737          * @param {Grid} this
39738          * @param {Roo.GridDD} dd The drag drop object
39739          * @param {String} targetId The target drag drop object
39740          * @param {event} e The raw browser event
39741          */
39742         "dragout" : true,
39743         /**
39744          * @event rowclass
39745          * Fires when a row is rendered, so you can change add a style to it.
39746          * @param {GridView} gridview   The grid view
39747          * @param {Object} rowcfg   contains record  rowIndex and rowClass - set rowClass to add a style.
39748          */
39749         'rowclass' : true,
39750
39751         /**
39752          * @event render
39753          * Fires when the grid is rendered
39754          * @param {Grid} grid
39755          */
39756         'render' : true
39757     });
39758
39759     Roo.grid.Grid.superclass.constructor.call(this);
39760 };
39761 Roo.extend(Roo.grid.Grid, Roo.util.Observable, {
39762     
39763     /**
39764          * @cfg {Roo.grid.AbstractSelectionModel} sm The selection Model (default = Roo.grid.RowSelectionModel)
39765          */
39766         /**
39767          * @cfg {Roo.grid.GridView} view  The view that renders the grid (default = Roo.grid.GridView)
39768          */
39769         /**
39770          * @cfg {Roo.grid.ColumnModel} cm[] The columns of the grid
39771          */
39772         /**
39773          * @cfg {Roo.data.Store} ds The data store for the grid
39774          */
39775         /**
39776          * @cfg {Roo.Toolbar} toolbar a toolbar for buttons etc.
39777          */
39778          
39779          /**
39780          * @cfg {Roo.PagingToolbar} footer the paging toolbar
39781          */
39782         
39783         /**
39784      * @cfg {String} ddGroup - drag drop group.
39785      */
39786       /**
39787      * @cfg {String} dragGroup - drag group (?? not sure if needed.)
39788      */
39789
39790     /**
39791      * @cfg {Number} minColumnWidth The minimum width a column can be resized to. Default is 25.
39792      */
39793     minColumnWidth : 25,
39794
39795     /**
39796      * @cfg {Boolean} autoSizeColumns True to automatically resize the columns to fit their content
39797      * <b>on initial render.</b> It is more efficient to explicitly size the columns
39798      * through the ColumnModel's {@link Roo.grid.ColumnModel#width} config option.  Default is false.
39799      */
39800     autoSizeColumns : false,
39801
39802     /**
39803      * @cfg {Boolean} autoSizeHeaders True to measure headers with column data when auto sizing columns. Default is true.
39804      */
39805     autoSizeHeaders : true,
39806
39807     /**
39808      * @cfg {Boolean} monitorWindowResize True to autoSize the grid when the window resizes. Default is true.
39809      */
39810     monitorWindowResize : true,
39811
39812     /**
39813      * @cfg {Boolean} maxRowsToMeasure If autoSizeColumns is on, maxRowsToMeasure can be used to limit the number of
39814      * rows measured to get a columns size. Default is 0 (all rows).
39815      */
39816     maxRowsToMeasure : 0,
39817
39818     /**
39819      * @cfg {Boolean} trackMouseOver True to highlight rows when the mouse is over. Default is true.
39820      */
39821     trackMouseOver : true,
39822
39823     /**
39824     * @cfg {Boolean} enableDrag  True to enable drag of rows. Default is false. (double check if this is needed?)
39825     */
39826       /**
39827     * @cfg {Boolean} enableDrop  True to enable drop of elements. Default is false. (double check if this is needed?)
39828     */
39829     
39830     /**
39831     * @cfg {Boolean} enableDragDrop True to enable drag and drop of rows. Default is false.
39832     */
39833     enableDragDrop : false,
39834     
39835     /**
39836     * @cfg {Boolean} enableColumnMove True to enable drag and drop reorder of columns. Default is true.
39837     */
39838     enableColumnMove : true,
39839     
39840     /**
39841     * @cfg {Boolean} enableColumnHide True to enable hiding of columns with the header context menu. Default is true.
39842     */
39843     enableColumnHide : true,
39844     
39845     /**
39846     * @cfg {Boolean} enableRowHeightSync True to manually sync row heights across locked and not locked rows. Default is false.
39847     */
39848     enableRowHeightSync : false,
39849     
39850     /**
39851     * @cfg {Boolean} stripeRows True to stripe the rows.  Default is true.
39852     */
39853     stripeRows : true,
39854     
39855     /**
39856     * @cfg {Boolean} autoHeight True to fit the height of the grid container to the height of the data. Default is false.
39857     */
39858     autoHeight : false,
39859
39860     /**
39861      * @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.
39862      */
39863     autoExpandColumn : false,
39864
39865     /**
39866     * @cfg {Number} autoExpandMin The minimum width the autoExpandColumn can have (if enabled).
39867     * Default is 50.
39868     */
39869     autoExpandMin : 50,
39870
39871     /**
39872     * @cfg {Number} autoExpandMax The maximum width the autoExpandColumn can have (if enabled). Default is 1000.
39873     */
39874     autoExpandMax : 1000,
39875
39876     /**
39877     * @cfg {Object} view The {@link Roo.grid.GridView} used by the grid. This can be set before a call to render().
39878     */
39879     view : null,
39880
39881     /**
39882     * @cfg {Object} loadMask An {@link Roo.LoadMask} config or true to mask the grid while loading. Default is false.
39883     */
39884     loadMask : false,
39885     /**
39886     * @cfg {Roo.dd.DropTarget} dropTarget An {@link Roo.dd.DropTarget} config
39887     */
39888     dropTarget: false,
39889      /**
39890     * @cfg {boolean} sortColMenu Sort the column order menu when it shows (usefull for long lists..) default false
39891     */ 
39892     sortColMenu : false,
39893     
39894     // private
39895     rendered : false,
39896
39897     /**
39898     * @cfg {Boolean} autoWidth True to set the grid's width to the default total width of the grid's columns instead
39899     * of a fixed width. Default is false.
39900     */
39901     /**
39902     * @cfg {Number} maxHeight Sets the maximum height of the grid - ignored if autoHeight is not on.
39903     */
39904     
39905     
39906     /**
39907     * @cfg {String} ddText Configures the text is the drag proxy (defaults to "%0 selected row(s)").
39908     * %0 is replaced with the number of selected rows.
39909     */
39910     ddText : "{0} selected row{1}",
39911     
39912     
39913     /**
39914      * Called once after all setup has been completed and the grid is ready to be rendered.
39915      * @return {Roo.grid.Grid} this
39916      */
39917     render : function()
39918     {
39919         var c = this.container;
39920         // try to detect autoHeight/width mode
39921         if((!c.dom.offsetHeight || c.dom.offsetHeight < 20) || c.getStyle("height") == "auto"){
39922             this.autoHeight = true;
39923         }
39924         var view = this.getView();
39925         view.init(this);
39926
39927         c.on("click", this.onClick, this);
39928         c.on("dblclick", this.onDblClick, this);
39929         c.on("contextmenu", this.onContextMenu, this);
39930         c.on("keydown", this.onKeyDown, this);
39931         if (Roo.isTouch) {
39932             c.on("touchstart", this.onTouchStart, this);
39933         }
39934
39935         this.relayEvents(c, ["mousedown","mouseup","mouseover","mouseout","keypress"]);
39936
39937         this.getSelectionModel().init(this);
39938
39939         view.render();
39940
39941         if(this.loadMask){
39942             this.loadMask = new Roo.LoadMask(this.container,
39943                     Roo.apply({store:this.dataSource}, this.loadMask));
39944         }
39945         
39946         
39947         if (this.toolbar && this.toolbar.xtype) {
39948             this.toolbar.container = this.getView().getHeaderPanel(true);
39949             this.toolbar = new Roo.Toolbar(this.toolbar);
39950         }
39951         if (this.footer && this.footer.xtype) {
39952             this.footer.dataSource = this.getDataSource();
39953             this.footer.container = this.getView().getFooterPanel(true);
39954             this.footer = Roo.factory(this.footer, Roo);
39955         }
39956         if (this.dropTarget && this.dropTarget.xtype) {
39957             delete this.dropTarget.xtype;
39958             this.dropTarget =  new Roo.dd.DropTarget(this.getView().mainBody, this.dropTarget);
39959         }
39960         
39961         
39962         this.rendered = true;
39963         this.fireEvent('render', this);
39964         return this;
39965     },
39966
39967     /**
39968      * Reconfigures the grid to use a different Store and Column Model.
39969      * The View will be bound to the new objects and refreshed.
39970      * @param {Roo.data.Store} dataSource The new {@link Roo.data.Store} object
39971      * @param {Roo.grid.ColumnModel} The new {@link Roo.grid.ColumnModel} object
39972      */
39973     reconfigure : function(dataSource, colModel){
39974         if(this.loadMask){
39975             this.loadMask.destroy();
39976             this.loadMask = new Roo.LoadMask(this.container,
39977                     Roo.apply({store:dataSource}, this.loadMask));
39978         }
39979         this.view.bind(dataSource, colModel);
39980         this.dataSource = dataSource;
39981         this.colModel = colModel;
39982         this.view.refresh(true);
39983     },
39984     /**
39985      * addColumns
39986      * Add's a column, default at the end..
39987      
39988      * @param {int} position to add (default end)
39989      * @param {Array} of objects of column configuration see {@link Roo.grid.ColumnModel} 
39990      */
39991     addColumns : function(pos, ar)
39992     {
39993         
39994         for (var i =0;i< ar.length;i++) {
39995             var cfg = ar[i];
39996             cfg.id = typeof(cfg.id) == 'undefined' ? Roo.id() : cfg.id; // don't normally use this..
39997             this.cm.lookup[cfg.id] = cfg;
39998         }
39999         
40000         
40001         if (typeof(pos) == 'undefined' || pos >= this.cm.config.length) {
40002             pos = this.cm.config.length; //this.cm.config.push(cfg);
40003         } 
40004         pos = Math.max(0,pos);
40005         ar.unshift(0);
40006         ar.unshift(pos);
40007         this.cm.config.splice.apply(this.cm.config, ar);
40008         
40009         
40010         
40011         this.view.generateRules(this.cm);
40012         this.view.refresh(true);
40013         
40014     },
40015     
40016     
40017     
40018     
40019     // private
40020     onKeyDown : function(e){
40021         this.fireEvent("keydown", e);
40022     },
40023
40024     /**
40025      * Destroy this grid.
40026      * @param {Boolean} removeEl True to remove the element
40027      */
40028     destroy : function(removeEl, keepListeners){
40029         if(this.loadMask){
40030             this.loadMask.destroy();
40031         }
40032         var c = this.container;
40033         c.removeAllListeners();
40034         this.view.destroy();
40035         this.colModel.purgeListeners();
40036         if(!keepListeners){
40037             this.purgeListeners();
40038         }
40039         c.update("");
40040         if(removeEl === true){
40041             c.remove();
40042         }
40043     },
40044
40045     // private
40046     processEvent : function(name, e){
40047         // does this fire select???
40048         //Roo.log('grid:processEvent '  + name);
40049         
40050         if (name != 'touchstart' ) {
40051             this.fireEvent(name, e);    
40052         }
40053         
40054         var t = e.getTarget();
40055         var v = this.view;
40056         var header = v.findHeaderIndex(t);
40057         if(header !== false){
40058             var ename = name == 'touchstart' ? 'click' : name;
40059              
40060             this.fireEvent("header" + ename, this, header, e);
40061         }else{
40062             var row = v.findRowIndex(t);
40063             var cell = v.findCellIndex(t);
40064             if (name == 'touchstart') {
40065                 // first touch is always a click.
40066                 // hopefull this happens after selection is updated.?
40067                 name = false;
40068                 
40069                 if (typeof(this.selModel.getSelectedCell) != 'undefined') {
40070                     var cs = this.selModel.getSelectedCell();
40071                     if (row == cs[0] && cell == cs[1]){
40072                         name = 'dblclick';
40073                     }
40074                 }
40075                 if (typeof(this.selModel.getSelections) != 'undefined') {
40076                     var cs = this.selModel.getSelections();
40077                     var ds = this.dataSource;
40078                     if (cs.length == 1 && ds.getAt(row) == cs[0]){
40079                         name = 'dblclick';
40080                     }
40081                 }
40082                 if (!name) {
40083                     return;
40084                 }
40085             }
40086             
40087             
40088             if(row !== false){
40089                 this.fireEvent("row" + name, this, row, e);
40090                 if(cell !== false){
40091                     this.fireEvent("cell" + name, this, row, cell, e);
40092                 }
40093             }
40094         }
40095     },
40096
40097     // private
40098     onClick : function(e){
40099         this.processEvent("click", e);
40100     },
40101    // private
40102     onTouchStart : function(e){
40103         this.processEvent("touchstart", e);
40104     },
40105
40106     // private
40107     onContextMenu : function(e, t){
40108         this.processEvent("contextmenu", e);
40109     },
40110
40111     // private
40112     onDblClick : function(e){
40113         this.processEvent("dblclick", e);
40114     },
40115
40116     // private
40117     walkCells : function(row, col, step, fn, scope){
40118         var cm = this.colModel, clen = cm.getColumnCount();
40119         var ds = this.dataSource, rlen = ds.getCount(), first = true;
40120         if(step < 0){
40121             if(col < 0){
40122                 row--;
40123                 first = false;
40124             }
40125             while(row >= 0){
40126                 if(!first){
40127                     col = clen-1;
40128                 }
40129                 first = false;
40130                 while(col >= 0){
40131                     if(fn.call(scope || this, row, col, cm) === true){
40132                         return [row, col];
40133                     }
40134                     col--;
40135                 }
40136                 row--;
40137             }
40138         } else {
40139             if(col >= clen){
40140                 row++;
40141                 first = false;
40142             }
40143             while(row < rlen){
40144                 if(!first){
40145                     col = 0;
40146                 }
40147                 first = false;
40148                 while(col < clen){
40149                     if(fn.call(scope || this, row, col, cm) === true){
40150                         return [row, col];
40151                     }
40152                     col++;
40153                 }
40154                 row++;
40155             }
40156         }
40157         return null;
40158     },
40159
40160     // private
40161     getSelections : function(){
40162         return this.selModel.getSelections();
40163     },
40164
40165     /**
40166      * Causes the grid to manually recalculate its dimensions. Generally this is done automatically,
40167      * but if manual update is required this method will initiate it.
40168      */
40169     autoSize : function(){
40170         if(this.rendered){
40171             this.view.layout();
40172             if(this.view.adjustForScroll){
40173                 this.view.adjustForScroll();
40174             }
40175         }
40176     },
40177
40178     /**
40179      * Returns the grid's underlying element.
40180      * @return {Element} The element
40181      */
40182     getGridEl : function(){
40183         return this.container;
40184     },
40185
40186     // private for compatibility, overridden by editor grid
40187     stopEditing : function(){},
40188
40189     /**
40190      * Returns the grid's SelectionModel.
40191      * @return {SelectionModel}
40192      */
40193     getSelectionModel : function(){
40194         if(!this.selModel){
40195             this.selModel = new Roo.grid.RowSelectionModel();
40196         }
40197         return this.selModel;
40198     },
40199
40200     /**
40201      * Returns the grid's DataSource.
40202      * @return {DataSource}
40203      */
40204     getDataSource : function(){
40205         return this.dataSource;
40206     },
40207
40208     /**
40209      * Returns the grid's ColumnModel.
40210      * @return {ColumnModel}
40211      */
40212     getColumnModel : function(){
40213         return this.colModel;
40214     },
40215
40216     /**
40217      * Returns the grid's GridView object.
40218      * @return {GridView}
40219      */
40220     getView : function(){
40221         if(!this.view){
40222             this.view = new Roo.grid.GridView(this.viewConfig);
40223             this.relayEvents(this.view, [
40224                 "beforerowremoved", "beforerowsinserted",
40225                 "beforerefresh", "rowremoved",
40226                 "rowsinserted", "rowupdated" ,"refresh"
40227             ]);
40228         }
40229         return this.view;
40230     },
40231     /**
40232      * Called to get grid's drag proxy text, by default returns this.ddText.
40233      * Override this to put something different in the dragged text.
40234      * @return {String}
40235      */
40236     getDragDropText : function(){
40237         var count = this.selModel.getCount();
40238         return String.format(this.ddText, count, count == 1 ? '' : 's');
40239     }
40240 });
40241 /*
40242  * Based on:
40243  * Ext JS Library 1.1.1
40244  * Copyright(c) 2006-2007, Ext JS, LLC.
40245  *
40246  * Originally Released Under LGPL - original licence link has changed is not relivant.
40247  *
40248  * Fork - LGPL
40249  * <script type="text/javascript">
40250  */
40251  /**
40252  * @class Roo.grid.AbstractGridView
40253  * @extends Roo.util.Observable
40254  * @abstract
40255  * Abstract base class for grid Views
40256  * @constructor
40257  */
40258 Roo.grid.AbstractGridView = function(){
40259         this.grid = null;
40260         
40261         this.events = {
40262             "beforerowremoved" : true,
40263             "beforerowsinserted" : true,
40264             "beforerefresh" : true,
40265             "rowremoved" : true,
40266             "rowsinserted" : true,
40267             "rowupdated" : true,
40268             "refresh" : true
40269         };
40270     Roo.grid.AbstractGridView.superclass.constructor.call(this);
40271 };
40272
40273 Roo.extend(Roo.grid.AbstractGridView, Roo.util.Observable, {
40274     rowClass : "x-grid-row",
40275     cellClass : "x-grid-cell",
40276     tdClass : "x-grid-td",
40277     hdClass : "x-grid-hd",
40278     splitClass : "x-grid-hd-split",
40279     
40280     init: function(grid){
40281         this.grid = grid;
40282                 var cid = this.grid.getGridEl().id;
40283         this.colSelector = "#" + cid + " ." + this.cellClass + "-";
40284         this.tdSelector = "#" + cid + " ." + this.tdClass + "-";
40285         this.hdSelector = "#" + cid + " ." + this.hdClass + "-";
40286         this.splitSelector = "#" + cid + " ." + this.splitClass + "-";
40287         },
40288         
40289     getColumnRenderers : function(){
40290         var renderers = [];
40291         var cm = this.grid.colModel;
40292         var colCount = cm.getColumnCount();
40293         for(var i = 0; i < colCount; i++){
40294             renderers[i] = cm.getRenderer(i);
40295         }
40296         return renderers;
40297     },
40298     
40299     getColumnIds : function(){
40300         var ids = [];
40301         var cm = this.grid.colModel;
40302         var colCount = cm.getColumnCount();
40303         for(var i = 0; i < colCount; i++){
40304             ids[i] = cm.getColumnId(i);
40305         }
40306         return ids;
40307     },
40308     
40309     getDataIndexes : function(){
40310         if(!this.indexMap){
40311             this.indexMap = this.buildIndexMap();
40312         }
40313         return this.indexMap.colToData;
40314     },
40315     
40316     getColumnIndexByDataIndex : function(dataIndex){
40317         if(!this.indexMap){
40318             this.indexMap = this.buildIndexMap();
40319         }
40320         return this.indexMap.dataToCol[dataIndex];
40321     },
40322     
40323     /**
40324      * Set a css style for a column dynamically. 
40325      * @param {Number} colIndex The index of the column
40326      * @param {String} name The css property name
40327      * @param {String} value The css value
40328      */
40329     setCSSStyle : function(colIndex, name, value){
40330         var selector = "#" + this.grid.id + " .x-grid-col-" + colIndex;
40331         Roo.util.CSS.updateRule(selector, name, value);
40332     },
40333     
40334     generateRules : function(cm){
40335         var ruleBuf = [], rulesId = this.grid.id + '-cssrules';
40336         Roo.util.CSS.removeStyleSheet(rulesId);
40337         for(var i = 0, len = cm.getColumnCount(); i < len; i++){
40338             var cid = cm.getColumnId(i);
40339             ruleBuf.push(this.colSelector, cid, " {\n", cm.config[i].css, "}\n",
40340                          this.tdSelector, cid, " {\n}\n",
40341                          this.hdSelector, cid, " {\n}\n",
40342                          this.splitSelector, cid, " {\n}\n");
40343         }
40344         return Roo.util.CSS.createStyleSheet(ruleBuf.join(""), rulesId);
40345     }
40346 });/*
40347  * Based on:
40348  * Ext JS Library 1.1.1
40349  * Copyright(c) 2006-2007, Ext JS, LLC.
40350  *
40351  * Originally Released Under LGPL - original licence link has changed is not relivant.
40352  *
40353  * Fork - LGPL
40354  * <script type="text/javascript">
40355  */
40356
40357 // private
40358 // This is a support class used internally by the Grid components
40359 Roo.grid.HeaderDragZone = function(grid, hd, hd2){
40360     this.grid = grid;
40361     this.view = grid.getView();
40362     this.ddGroup = "gridHeader" + this.grid.getGridEl().id;
40363     Roo.grid.HeaderDragZone.superclass.constructor.call(this, hd);
40364     if(hd2){
40365         this.setHandleElId(Roo.id(hd));
40366         this.setOuterHandleElId(Roo.id(hd2));
40367     }
40368     this.scroll = false;
40369 };
40370 Roo.extend(Roo.grid.HeaderDragZone, Roo.dd.DragZone, {
40371     maxDragWidth: 120,
40372     getDragData : function(e){
40373         var t = Roo.lib.Event.getTarget(e);
40374         var h = this.view.findHeaderCell(t);
40375         if(h){
40376             return {ddel: h.firstChild, header:h};
40377         }
40378         return false;
40379     },
40380
40381     onInitDrag : function(e){
40382         this.view.headersDisabled = true;
40383         var clone = this.dragData.ddel.cloneNode(true);
40384         clone.id = Roo.id();
40385         clone.style.width = Math.min(this.dragData.header.offsetWidth,this.maxDragWidth) + "px";
40386         this.proxy.update(clone);
40387         return true;
40388     },
40389
40390     afterValidDrop : function(){
40391         var v = this.view;
40392         setTimeout(function(){
40393             v.headersDisabled = false;
40394         }, 50);
40395     },
40396
40397     afterInvalidDrop : function(){
40398         var v = this.view;
40399         setTimeout(function(){
40400             v.headersDisabled = false;
40401         }, 50);
40402     }
40403 });
40404 /*
40405  * Based on:
40406  * Ext JS Library 1.1.1
40407  * Copyright(c) 2006-2007, Ext JS, LLC.
40408  *
40409  * Originally Released Under LGPL - original licence link has changed is not relivant.
40410  *
40411  * Fork - LGPL
40412  * <script type="text/javascript">
40413  */
40414 // private
40415 // This is a support class used internally by the Grid components
40416 Roo.grid.HeaderDropZone = function(grid, hd, hd2){
40417     this.grid = grid;
40418     this.view = grid.getView();
40419     // split the proxies so they don't interfere with mouse events
40420     this.proxyTop = Roo.DomHelper.append(document.body, {
40421         cls:"col-move-top", html:"&#160;"
40422     }, true);
40423     this.proxyBottom = Roo.DomHelper.append(document.body, {
40424         cls:"col-move-bottom", html:"&#160;"
40425     }, true);
40426     this.proxyTop.hide = this.proxyBottom.hide = function(){
40427         this.setLeftTop(-100,-100);
40428         this.setStyle("visibility", "hidden");
40429     };
40430     this.ddGroup = "gridHeader" + this.grid.getGridEl().id;
40431     // temporarily disabled
40432     //Roo.dd.ScrollManager.register(this.view.scroller.dom);
40433     Roo.grid.HeaderDropZone.superclass.constructor.call(this, grid.getGridEl().dom);
40434 };
40435 Roo.extend(Roo.grid.HeaderDropZone, Roo.dd.DropZone, {
40436     proxyOffsets : [-4, -9],
40437     fly: Roo.Element.fly,
40438
40439     getTargetFromEvent : function(e){
40440         var t = Roo.lib.Event.getTarget(e);
40441         var cindex = this.view.findCellIndex(t);
40442         if(cindex !== false){
40443             return this.view.getHeaderCell(cindex);
40444         }
40445         return null;
40446     },
40447
40448     nextVisible : function(h){
40449         var v = this.view, cm = this.grid.colModel;
40450         h = h.nextSibling;
40451         while(h){
40452             if(!cm.isHidden(v.getCellIndex(h))){
40453                 return h;
40454             }
40455             h = h.nextSibling;
40456         }
40457         return null;
40458     },
40459
40460     prevVisible : function(h){
40461         var v = this.view, cm = this.grid.colModel;
40462         h = h.prevSibling;
40463         while(h){
40464             if(!cm.isHidden(v.getCellIndex(h))){
40465                 return h;
40466             }
40467             h = h.prevSibling;
40468         }
40469         return null;
40470     },
40471
40472     positionIndicator : function(h, n, e){
40473         var x = Roo.lib.Event.getPageX(e);
40474         var r = Roo.lib.Dom.getRegion(n.firstChild);
40475         var px, pt, py = r.top + this.proxyOffsets[1];
40476         if((r.right - x) <= (r.right-r.left)/2){
40477             px = r.right+this.view.borderWidth;
40478             pt = "after";
40479         }else{
40480             px = r.left;
40481             pt = "before";
40482         }
40483         var oldIndex = this.view.getCellIndex(h);
40484         var newIndex = this.view.getCellIndex(n);
40485
40486         if(this.grid.colModel.isFixed(newIndex)){
40487             return false;
40488         }
40489
40490         var locked = this.grid.colModel.isLocked(newIndex);
40491
40492         if(pt == "after"){
40493             newIndex++;
40494         }
40495         if(oldIndex < newIndex){
40496             newIndex--;
40497         }
40498         if(oldIndex == newIndex && (locked == this.grid.colModel.isLocked(oldIndex))){
40499             return false;
40500         }
40501         px +=  this.proxyOffsets[0];
40502         this.proxyTop.setLeftTop(px, py);
40503         this.proxyTop.show();
40504         if(!this.bottomOffset){
40505             this.bottomOffset = this.view.mainHd.getHeight();
40506         }
40507         this.proxyBottom.setLeftTop(px, py+this.proxyTop.dom.offsetHeight+this.bottomOffset);
40508         this.proxyBottom.show();
40509         return pt;
40510     },
40511
40512     onNodeEnter : function(n, dd, e, data){
40513         if(data.header != n){
40514             this.positionIndicator(data.header, n, e);
40515         }
40516     },
40517
40518     onNodeOver : function(n, dd, e, data){
40519         var result = false;
40520         if(data.header != n){
40521             result = this.positionIndicator(data.header, n, e);
40522         }
40523         if(!result){
40524             this.proxyTop.hide();
40525             this.proxyBottom.hide();
40526         }
40527         return result ? this.dropAllowed : this.dropNotAllowed;
40528     },
40529
40530     onNodeOut : function(n, dd, e, data){
40531         this.proxyTop.hide();
40532         this.proxyBottom.hide();
40533     },
40534
40535     onNodeDrop : function(n, dd, e, data){
40536         var h = data.header;
40537         if(h != n){
40538             var cm = this.grid.colModel;
40539             var x = Roo.lib.Event.getPageX(e);
40540             var r = Roo.lib.Dom.getRegion(n.firstChild);
40541             var pt = (r.right - x) <= ((r.right-r.left)/2) ? "after" : "before";
40542             var oldIndex = this.view.getCellIndex(h);
40543             var newIndex = this.view.getCellIndex(n);
40544             var locked = cm.isLocked(newIndex);
40545             if(pt == "after"){
40546                 newIndex++;
40547             }
40548             if(oldIndex < newIndex){
40549                 newIndex--;
40550             }
40551             if(oldIndex == newIndex && (locked == cm.isLocked(oldIndex))){
40552                 return false;
40553             }
40554             cm.setLocked(oldIndex, locked, true);
40555             cm.moveColumn(oldIndex, newIndex);
40556             this.grid.fireEvent("columnmove", oldIndex, newIndex);
40557             return true;
40558         }
40559         return false;
40560     }
40561 });
40562 /*
40563  * Based on:
40564  * Ext JS Library 1.1.1
40565  * Copyright(c) 2006-2007, Ext JS, LLC.
40566  *
40567  * Originally Released Under LGPL - original licence link has changed is not relivant.
40568  *
40569  * Fork - LGPL
40570  * <script type="text/javascript">
40571  */
40572   
40573 /**
40574  * @class Roo.grid.GridView
40575  * @extends Roo.util.Observable
40576  *
40577  * @constructor
40578  * @param {Object} config
40579  */
40580 Roo.grid.GridView = function(config){
40581     Roo.grid.GridView.superclass.constructor.call(this);
40582     this.el = null;
40583
40584     Roo.apply(this, config);
40585 };
40586
40587 Roo.extend(Roo.grid.GridView, Roo.grid.AbstractGridView, {
40588
40589     unselectable :  'unselectable="on"',
40590     unselectableCls :  'x-unselectable',
40591     
40592     
40593     rowClass : "x-grid-row",
40594
40595     cellClass : "x-grid-col",
40596
40597     tdClass : "x-grid-td",
40598
40599     hdClass : "x-grid-hd",
40600
40601     splitClass : "x-grid-split",
40602
40603     sortClasses : ["sort-asc", "sort-desc"],
40604
40605     enableMoveAnim : false,
40606
40607     hlColor: "C3DAF9",
40608
40609     dh : Roo.DomHelper,
40610
40611     fly : Roo.Element.fly,
40612
40613     css : Roo.util.CSS,
40614
40615     borderWidth: 1,
40616
40617     splitOffset: 3,
40618
40619     scrollIncrement : 22,
40620
40621     cellRE: /(?:.*?)x-grid-(?:hd|cell|csplit)-(?:[\d]+)-([\d]+)(?:.*?)/,
40622
40623     findRE: /\s?(?:x-grid-hd|x-grid-col|x-grid-csplit)\s/,
40624
40625     bind : function(ds, cm){
40626         if(this.ds){
40627             this.ds.un("load", this.onLoad, this);
40628             this.ds.un("datachanged", this.onDataChange, this);
40629             this.ds.un("add", this.onAdd, this);
40630             this.ds.un("remove", this.onRemove, this);
40631             this.ds.un("update", this.onUpdate, this);
40632             this.ds.un("clear", this.onClear, this);
40633         }
40634         if(ds){
40635             ds.on("load", this.onLoad, this);
40636             ds.on("datachanged", this.onDataChange, this);
40637             ds.on("add", this.onAdd, this);
40638             ds.on("remove", this.onRemove, this);
40639             ds.on("update", this.onUpdate, this);
40640             ds.on("clear", this.onClear, this);
40641         }
40642         this.ds = ds;
40643
40644         if(this.cm){
40645             this.cm.un("widthchange", this.onColWidthChange, this);
40646             this.cm.un("headerchange", this.onHeaderChange, this);
40647             this.cm.un("hiddenchange", this.onHiddenChange, this);
40648             this.cm.un("columnmoved", this.onColumnMove, this);
40649             this.cm.un("columnlockchange", this.onColumnLock, this);
40650         }
40651         if(cm){
40652             this.generateRules(cm);
40653             cm.on("widthchange", this.onColWidthChange, this);
40654             cm.on("headerchange", this.onHeaderChange, this);
40655             cm.on("hiddenchange", this.onHiddenChange, this);
40656             cm.on("columnmoved", this.onColumnMove, this);
40657             cm.on("columnlockchange", this.onColumnLock, this);
40658         }
40659         this.cm = cm;
40660     },
40661
40662     init: function(grid){
40663         Roo.grid.GridView.superclass.init.call(this, grid);
40664
40665         this.bind(grid.dataSource, grid.colModel);
40666
40667         grid.on("headerclick", this.handleHeaderClick, this);
40668
40669         if(grid.trackMouseOver){
40670             grid.on("mouseover", this.onRowOver, this);
40671             grid.on("mouseout", this.onRowOut, this);
40672         }
40673         grid.cancelTextSelection = function(){};
40674         this.gridId = grid.id;
40675
40676         var tpls = this.templates || {};
40677
40678         if(!tpls.master){
40679             tpls.master = new Roo.Template(
40680                '<div class="x-grid" hidefocus="true">',
40681                 '<a href="#" class="x-grid-focus" tabIndex="-1"></a>',
40682                   '<div class="x-grid-topbar"></div>',
40683                   '<div class="x-grid-scroller"><div></div></div>',
40684                   '<div class="x-grid-locked">',
40685                       '<div class="x-grid-header">{lockedHeader}</div>',
40686                       '<div class="x-grid-body">{lockedBody}</div>',
40687                   "</div>",
40688                   '<div class="x-grid-viewport">',
40689                       '<div class="x-grid-header">{header}</div>',
40690                       '<div class="x-grid-body">{body}</div>',
40691                   "</div>",
40692                   '<div class="x-grid-bottombar"></div>',
40693                  
40694                   '<div class="x-grid-resize-proxy">&#160;</div>',
40695                "</div>"
40696             );
40697             tpls.master.disableformats = true;
40698         }
40699
40700         if(!tpls.header){
40701             tpls.header = new Roo.Template(
40702                '<table border="0" cellspacing="0" cellpadding="0">',
40703                '<tbody><tr class="x-grid-hd-row">{cells}</tr></tbody>',
40704                "</table>{splits}"
40705             );
40706             tpls.header.disableformats = true;
40707         }
40708         tpls.header.compile();
40709
40710         if(!tpls.hcell){
40711             tpls.hcell = new Roo.Template(
40712                 '<td class="x-grid-hd x-grid-td-{id} {cellId}"><div title="{title}" class="x-grid-hd-inner x-grid-hd-{id}">',
40713                 '<div class="x-grid-hd-text ' + this.unselectableCls +  '" ' + this.unselectable +'>{value}<img class="x-grid-sort-icon" src="', Roo.BLANK_IMAGE_URL, '" /></div>',
40714                 "</div></td>"
40715              );
40716              tpls.hcell.disableFormats = true;
40717         }
40718         tpls.hcell.compile();
40719
40720         if(!tpls.hsplit){
40721             tpls.hsplit = new Roo.Template('<div class="x-grid-split {splitId} x-grid-split-{id}" style="{style} ' +
40722                                             this.unselectableCls +  '" ' + this.unselectable +'>&#160;</div>');
40723             tpls.hsplit.disableFormats = true;
40724         }
40725         tpls.hsplit.compile();
40726
40727         if(!tpls.body){
40728             tpls.body = new Roo.Template(
40729                '<table border="0" cellspacing="0" cellpadding="0">',
40730                "<tbody>{rows}</tbody>",
40731                "</table>"
40732             );
40733             tpls.body.disableFormats = true;
40734         }
40735         tpls.body.compile();
40736
40737         if(!tpls.row){
40738             tpls.row = new Roo.Template('<tr class="x-grid-row {alt}">{cells}</tr>');
40739             tpls.row.disableFormats = true;
40740         }
40741         tpls.row.compile();
40742
40743         if(!tpls.cell){
40744             tpls.cell = new Roo.Template(
40745                 '<td class="x-grid-col x-grid-td-{id} {cellId} {css}" tabIndex="0">',
40746                 '<div class="x-grid-col-{id} x-grid-cell-inner"><div class="x-grid-cell-text ' +
40747                     this.unselectableCls +  '" ' + this.unselectable +'" {attr}>{value}</div></div>',
40748                 "</td>"
40749             );
40750             tpls.cell.disableFormats = true;
40751         }
40752         tpls.cell.compile();
40753
40754         this.templates = tpls;
40755     },
40756
40757     // remap these for backwards compat
40758     onColWidthChange : function(){
40759         this.updateColumns.apply(this, arguments);
40760     },
40761     onHeaderChange : function(){
40762         this.updateHeaders.apply(this, arguments);
40763     }, 
40764     onHiddenChange : function(){
40765         this.handleHiddenChange.apply(this, arguments);
40766     },
40767     onColumnMove : function(){
40768         this.handleColumnMove.apply(this, arguments);
40769     },
40770     onColumnLock : function(){
40771         this.handleLockChange.apply(this, arguments);
40772     },
40773
40774     onDataChange : function(){
40775         this.refresh();
40776         this.updateHeaderSortState();
40777     },
40778
40779     onClear : function(){
40780         this.refresh();
40781     },
40782
40783     onUpdate : function(ds, record){
40784         this.refreshRow(record);
40785     },
40786
40787     refreshRow : function(record){
40788         var ds = this.ds, index;
40789         if(typeof record == 'number'){
40790             index = record;
40791             record = ds.getAt(index);
40792         }else{
40793             index = ds.indexOf(record);
40794         }
40795         this.insertRows(ds, index, index, true);
40796         this.onRemove(ds, record, index+1, true);
40797         this.syncRowHeights(index, index);
40798         this.layout();
40799         this.fireEvent("rowupdated", this, index, record);
40800     },
40801
40802     onAdd : function(ds, records, index){
40803         this.insertRows(ds, index, index + (records.length-1));
40804     },
40805
40806     onRemove : function(ds, record, index, isUpdate){
40807         if(isUpdate !== true){
40808             this.fireEvent("beforerowremoved", this, index, record);
40809         }
40810         var bt = this.getBodyTable(), lt = this.getLockedTable();
40811         if(bt.rows[index]){
40812             bt.firstChild.removeChild(bt.rows[index]);
40813         }
40814         if(lt.rows[index]){
40815             lt.firstChild.removeChild(lt.rows[index]);
40816         }
40817         if(isUpdate !== true){
40818             this.stripeRows(index);
40819             this.syncRowHeights(index, index);
40820             this.layout();
40821             this.fireEvent("rowremoved", this, index, record);
40822         }
40823     },
40824
40825     onLoad : function(){
40826         this.scrollToTop();
40827     },
40828
40829     /**
40830      * Scrolls the grid to the top
40831      */
40832     scrollToTop : function(){
40833         if(this.scroller){
40834             this.scroller.dom.scrollTop = 0;
40835             this.syncScroll();
40836         }
40837     },
40838
40839     /**
40840      * Gets a panel in the header of the grid that can be used for toolbars etc.
40841      * After modifying the contents of this panel a call to grid.autoSize() may be
40842      * required to register any changes in size.
40843      * @param {Boolean} doShow By default the header is hidden. Pass true to show the panel
40844      * @return Roo.Element
40845      */
40846     getHeaderPanel : function(doShow){
40847         if(doShow){
40848             this.headerPanel.show();
40849         }
40850         return this.headerPanel;
40851     },
40852
40853     /**
40854      * Gets a panel in the footer of the grid that can be used for toolbars etc.
40855      * After modifying the contents of this panel a call to grid.autoSize() may be
40856      * required to register any changes in size.
40857      * @param {Boolean} doShow By default the footer is hidden. Pass true to show the panel
40858      * @return Roo.Element
40859      */
40860     getFooterPanel : function(doShow){
40861         if(doShow){
40862             this.footerPanel.show();
40863         }
40864         return this.footerPanel;
40865     },
40866
40867     initElements : function(){
40868         var E = Roo.Element;
40869         var el = this.grid.getGridEl().dom.firstChild;
40870         var cs = el.childNodes;
40871
40872         this.el = new E(el);
40873         
40874          this.focusEl = new E(el.firstChild);
40875         this.focusEl.swallowEvent("click", true);
40876         
40877         this.headerPanel = new E(cs[1]);
40878         this.headerPanel.enableDisplayMode("block");
40879
40880         this.scroller = new E(cs[2]);
40881         this.scrollSizer = new E(this.scroller.dom.firstChild);
40882
40883         this.lockedWrap = new E(cs[3]);
40884         this.lockedHd = new E(this.lockedWrap.dom.firstChild);
40885         this.lockedBody = new E(this.lockedWrap.dom.childNodes[1]);
40886
40887         this.mainWrap = new E(cs[4]);
40888         this.mainHd = new E(this.mainWrap.dom.firstChild);
40889         this.mainBody = new E(this.mainWrap.dom.childNodes[1]);
40890
40891         this.footerPanel = new E(cs[5]);
40892         this.footerPanel.enableDisplayMode("block");
40893
40894         this.resizeProxy = new E(cs[6]);
40895
40896         this.headerSelector = String.format(
40897            '#{0} td.x-grid-hd, #{1} td.x-grid-hd',
40898            this.lockedHd.id, this.mainHd.id
40899         );
40900
40901         this.splitterSelector = String.format(
40902            '#{0} div.x-grid-split, #{1} div.x-grid-split',
40903            this.idToCssName(this.lockedHd.id), this.idToCssName(this.mainHd.id)
40904         );
40905     },
40906     idToCssName : function(s)
40907     {
40908         return s.replace(/[^a-z0-9]+/ig, '-');
40909     },
40910
40911     getHeaderCell : function(index){
40912         return Roo.DomQuery.select(this.headerSelector)[index];
40913     },
40914
40915     getHeaderCellMeasure : function(index){
40916         return this.getHeaderCell(index).firstChild;
40917     },
40918
40919     getHeaderCellText : function(index){
40920         return this.getHeaderCell(index).firstChild.firstChild;
40921     },
40922
40923     getLockedTable : function(){
40924         return this.lockedBody.dom.firstChild;
40925     },
40926
40927     getBodyTable : function(){
40928         return this.mainBody.dom.firstChild;
40929     },
40930
40931     getLockedRow : function(index){
40932         return this.getLockedTable().rows[index];
40933     },
40934
40935     getRow : function(index){
40936         return this.getBodyTable().rows[index];
40937     },
40938
40939     getRowComposite : function(index){
40940         if(!this.rowEl){
40941             this.rowEl = new Roo.CompositeElementLite();
40942         }
40943         var els = [], lrow, mrow;
40944         if(lrow = this.getLockedRow(index)){
40945             els.push(lrow);
40946         }
40947         if(mrow = this.getRow(index)){
40948             els.push(mrow);
40949         }
40950         this.rowEl.elements = els;
40951         return this.rowEl;
40952     },
40953     /**
40954      * Gets the 'td' of the cell
40955      * 
40956      * @param {Integer} rowIndex row to select
40957      * @param {Integer} colIndex column to select
40958      * 
40959      * @return {Object} 
40960      */
40961     getCell : function(rowIndex, colIndex){
40962         var locked = this.cm.getLockedCount();
40963         var source;
40964         if(colIndex < locked){
40965             source = this.lockedBody.dom.firstChild;
40966         }else{
40967             source = this.mainBody.dom.firstChild;
40968             colIndex -= locked;
40969         }
40970         return source.rows[rowIndex].childNodes[colIndex];
40971     },
40972
40973     getCellText : function(rowIndex, colIndex){
40974         return this.getCell(rowIndex, colIndex).firstChild.firstChild;
40975     },
40976
40977     getCellBox : function(cell){
40978         var b = this.fly(cell).getBox();
40979         if(Roo.isOpera){ // opera fails to report the Y
40980             b.y = cell.offsetTop + this.mainBody.getY();
40981         }
40982         return b;
40983     },
40984
40985     getCellIndex : function(cell){
40986         var id = String(cell.className).match(this.cellRE);
40987         if(id){
40988             return parseInt(id[1], 10);
40989         }
40990         return 0;
40991     },
40992
40993     findHeaderIndex : function(n){
40994         var r = Roo.fly(n).findParent("td." + this.hdClass, 6);
40995         return r ? this.getCellIndex(r) : false;
40996     },
40997
40998     findHeaderCell : function(n){
40999         var r = Roo.fly(n).findParent("td." + this.hdClass, 6);
41000         return r ? r : false;
41001     },
41002
41003     findRowIndex : function(n){
41004         if(!n){
41005             return false;
41006         }
41007         var r = Roo.fly(n).findParent("tr." + this.rowClass, 6);
41008         return r ? r.rowIndex : false;
41009     },
41010
41011     findCellIndex : function(node){
41012         var stop = this.el.dom;
41013         while(node && node != stop){
41014             if(this.findRE.test(node.className)){
41015                 return this.getCellIndex(node);
41016             }
41017             node = node.parentNode;
41018         }
41019         return false;
41020     },
41021
41022     getColumnId : function(index){
41023         return this.cm.getColumnId(index);
41024     },
41025
41026     getSplitters : function()
41027     {
41028         if(this.splitterSelector){
41029            return Roo.DomQuery.select(this.splitterSelector);
41030         }else{
41031             return null;
41032       }
41033     },
41034
41035     getSplitter : function(index){
41036         return this.getSplitters()[index];
41037     },
41038
41039     onRowOver : function(e, t){
41040         var row;
41041         if((row = this.findRowIndex(t)) !== false){
41042             this.getRowComposite(row).addClass("x-grid-row-over");
41043         }
41044     },
41045
41046     onRowOut : function(e, t){
41047         var row;
41048         if((row = this.findRowIndex(t)) !== false && row !== this.findRowIndex(e.getRelatedTarget())){
41049             this.getRowComposite(row).removeClass("x-grid-row-over");
41050         }
41051     },
41052
41053     renderHeaders : function(){
41054         var cm = this.cm;
41055         var ct = this.templates.hcell, ht = this.templates.header, st = this.templates.hsplit;
41056         var cb = [], lb = [], sb = [], lsb = [], p = {};
41057         for(var i = 0, len = cm.getColumnCount(); i < len; i++){
41058             p.cellId = "x-grid-hd-0-" + i;
41059             p.splitId = "x-grid-csplit-0-" + i;
41060             p.id = cm.getColumnId(i);
41061             p.value = cm.getColumnHeader(i) || "";
41062             p.title = cm.getColumnTooltip(i) || (''+p.value).match(/\</)  ? '' :  p.value  || "";
41063             p.style = (this.grid.enableColumnResize === false || !cm.isResizable(i) || cm.isFixed(i)) ? 'cursor:default' : '';
41064             if(!cm.isLocked(i)){
41065                 cb[cb.length] = ct.apply(p);
41066                 sb[sb.length] = st.apply(p);
41067             }else{
41068                 lb[lb.length] = ct.apply(p);
41069                 lsb[lsb.length] = st.apply(p);
41070             }
41071         }
41072         return [ht.apply({cells: lb.join(""), splits:lsb.join("")}),
41073                 ht.apply({cells: cb.join(""), splits:sb.join("")})];
41074     },
41075
41076     updateHeaders : function(){
41077         var html = this.renderHeaders();
41078         this.lockedHd.update(html[0]);
41079         this.mainHd.update(html[1]);
41080     },
41081
41082     /**
41083      * Focuses the specified row.
41084      * @param {Number} row The row index
41085      */
41086     focusRow : function(row)
41087     {
41088         //Roo.log('GridView.focusRow');
41089         var x = this.scroller.dom.scrollLeft;
41090         this.focusCell(row, 0, false);
41091         this.scroller.dom.scrollLeft = x;
41092     },
41093
41094     /**
41095      * Focuses the specified cell.
41096      * @param {Number} row The row index
41097      * @param {Number} col The column index
41098      * @param {Boolean} hscroll false to disable horizontal scrolling
41099      */
41100     focusCell : function(row, col, hscroll)
41101     {
41102         //Roo.log('GridView.focusCell');
41103         var el = this.ensureVisible(row, col, hscroll);
41104         this.focusEl.alignTo(el, "tl-tl");
41105         if(Roo.isGecko){
41106             this.focusEl.focus();
41107         }else{
41108             this.focusEl.focus.defer(1, this.focusEl);
41109         }
41110     },
41111
41112     /**
41113      * Scrolls the specified cell into view
41114      * @param {Number} row The row index
41115      * @param {Number} col The column index
41116      * @param {Boolean} hscroll false to disable horizontal scrolling
41117      */
41118     ensureVisible : function(row, col, hscroll)
41119     {
41120         //Roo.log('GridView.ensureVisible,' + row + ',' + col);
41121         //return null; //disable for testing.
41122         if(typeof row != "number"){
41123             row = row.rowIndex;
41124         }
41125         if(row < 0 && row >= this.ds.getCount()){
41126             return  null;
41127         }
41128         col = (col !== undefined ? col : 0);
41129         var cm = this.grid.colModel;
41130         while(cm.isHidden(col)){
41131             col++;
41132         }
41133
41134         var el = this.getCell(row, col);
41135         if(!el){
41136             return null;
41137         }
41138         var c = this.scroller.dom;
41139
41140         var ctop = parseInt(el.offsetTop, 10);
41141         var cleft = parseInt(el.offsetLeft, 10);
41142         var cbot = ctop + el.offsetHeight;
41143         var cright = cleft + el.offsetWidth;
41144         
41145         var ch = c.clientHeight - this.mainHd.dom.offsetHeight;
41146         var stop = parseInt(c.scrollTop, 10);
41147         var sleft = parseInt(c.scrollLeft, 10);
41148         var sbot = stop + ch;
41149         var sright = sleft + c.clientWidth;
41150         /*
41151         Roo.log('GridView.ensureVisible:' +
41152                 ' ctop:' + ctop +
41153                 ' c.clientHeight:' + c.clientHeight +
41154                 ' this.mainHd.dom.offsetHeight:' + this.mainHd.dom.offsetHeight +
41155                 ' stop:' + stop +
41156                 ' cbot:' + cbot +
41157                 ' sbot:' + sbot +
41158                 ' ch:' + ch  
41159                 );
41160         */
41161         if(ctop < stop){
41162             c.scrollTop = ctop;
41163             //Roo.log("set scrolltop to ctop DISABLE?");
41164         }else if(cbot > sbot){
41165             //Roo.log("set scrolltop to cbot-ch");
41166             c.scrollTop = cbot-ch;
41167         }
41168         
41169         if(hscroll !== false){
41170             if(cleft < sleft){
41171                 c.scrollLeft = cleft;
41172             }else if(cright > sright){
41173                 c.scrollLeft = cright-c.clientWidth;
41174             }
41175         }
41176          
41177         return el;
41178     },
41179
41180     updateColumns : function(){
41181         this.grid.stopEditing();
41182         var cm = this.grid.colModel, colIds = this.getColumnIds();
41183         //var totalWidth = cm.getTotalWidth();
41184         var pos = 0;
41185         for(var i = 0, len = cm.getColumnCount(); i < len; i++){
41186             //if(cm.isHidden(i)) continue;
41187             var w = cm.getColumnWidth(i);
41188             this.css.updateRule(this.colSelector+this.idToCssName(colIds[i]), "width", (w - this.borderWidth) + "px");
41189             this.css.updateRule(this.hdSelector+this.idToCssName(colIds[i]), "width", (w - this.borderWidth) + "px");
41190         }
41191         this.updateSplitters();
41192     },
41193
41194     generateRules : function(cm){
41195         var ruleBuf = [], rulesId = this.idToCssName(this.grid.id)+ '-cssrules';
41196         Roo.util.CSS.removeStyleSheet(rulesId);
41197         for(var i = 0, len = cm.getColumnCount(); i < len; i++){
41198             var cid = cm.getColumnId(i);
41199             var align = '';
41200             if(cm.config[i].align){
41201                 align = 'text-align:'+cm.config[i].align+';';
41202             }
41203             var hidden = '';
41204             if(cm.isHidden(i)){
41205                 hidden = 'display:none;';
41206             }
41207             var width = "width:" + (cm.getColumnWidth(i) - this.borderWidth) + "px;";
41208             ruleBuf.push(
41209                     this.colSelector, cid, " {\n", cm.config[i].css, align, width, "\n}\n",
41210                     this.hdSelector, cid, " {\n", align, width, "}\n",
41211                     this.tdSelector, cid, " {\n",hidden,"\n}\n",
41212                     this.splitSelector, cid, " {\n", hidden , "\n}\n");
41213         }
41214         return Roo.util.CSS.createStyleSheet(ruleBuf.join(""), rulesId);
41215     },
41216
41217     updateSplitters : function(){
41218         var cm = this.cm, s = this.getSplitters();
41219         if(s){ // splitters not created yet
41220             var pos = 0, locked = true;
41221             for(var i = 0, len = cm.getColumnCount(); i < len; i++){
41222                 if(cm.isHidden(i)) {
41223                     continue;
41224                 }
41225                 var w = cm.getColumnWidth(i); // make sure it's a number
41226                 if(!cm.isLocked(i) && locked){
41227                     pos = 0;
41228                     locked = false;
41229                 }
41230                 pos += w;
41231                 s[i].style.left = (pos-this.splitOffset) + "px";
41232             }
41233         }
41234     },
41235
41236     handleHiddenChange : function(colModel, colIndex, hidden){
41237         if(hidden){
41238             this.hideColumn(colIndex);
41239         }else{
41240             this.unhideColumn(colIndex);
41241         }
41242     },
41243
41244     hideColumn : function(colIndex){
41245         var cid = this.getColumnId(colIndex);
41246         this.css.updateRule(this.tdSelector+this.idToCssName(cid), "display", "none");
41247         this.css.updateRule(this.splitSelector+this.idToCssName(cid), "display", "none");
41248         if(Roo.isSafari){
41249             this.updateHeaders();
41250         }
41251         this.updateSplitters();
41252         this.layout();
41253     },
41254
41255     unhideColumn : function(colIndex){
41256         var cid = this.getColumnId(colIndex);
41257         this.css.updateRule(this.tdSelector+this.idToCssName(cid), "display", "");
41258         this.css.updateRule(this.splitSelector+this.idToCssName(cid), "display", "");
41259
41260         if(Roo.isSafari){
41261             this.updateHeaders();
41262         }
41263         this.updateSplitters();
41264         this.layout();
41265     },
41266
41267     insertRows : function(dm, firstRow, lastRow, isUpdate){
41268         if(firstRow == 0 && lastRow == dm.getCount()-1){
41269             this.refresh();
41270         }else{
41271             if(!isUpdate){
41272                 this.fireEvent("beforerowsinserted", this, firstRow, lastRow);
41273             }
41274             var s = this.getScrollState();
41275             var markup = this.renderRows(firstRow, lastRow);
41276             this.bufferRows(markup[0], this.getLockedTable(), firstRow);
41277             this.bufferRows(markup[1], this.getBodyTable(), firstRow);
41278             this.restoreScroll(s);
41279             if(!isUpdate){
41280                 this.fireEvent("rowsinserted", this, firstRow, lastRow);
41281                 this.syncRowHeights(firstRow, lastRow);
41282                 this.stripeRows(firstRow);
41283                 this.layout();
41284             }
41285         }
41286     },
41287
41288     bufferRows : function(markup, target, index){
41289         var before = null, trows = target.rows, tbody = target.tBodies[0];
41290         if(index < trows.length){
41291             before = trows[index];
41292         }
41293         var b = document.createElement("div");
41294         b.innerHTML = "<table><tbody>"+markup+"</tbody></table>";
41295         var rows = b.firstChild.rows;
41296         for(var i = 0, len = rows.length; i < len; i++){
41297             if(before){
41298                 tbody.insertBefore(rows[0], before);
41299             }else{
41300                 tbody.appendChild(rows[0]);
41301             }
41302         }
41303         b.innerHTML = "";
41304         b = null;
41305     },
41306
41307     deleteRows : function(dm, firstRow, lastRow){
41308         if(dm.getRowCount()<1){
41309             this.fireEvent("beforerefresh", this);
41310             this.mainBody.update("");
41311             this.lockedBody.update("");
41312             this.fireEvent("refresh", this);
41313         }else{
41314             this.fireEvent("beforerowsdeleted", this, firstRow, lastRow);
41315             var bt = this.getBodyTable();
41316             var tbody = bt.firstChild;
41317             var rows = bt.rows;
41318             for(var rowIndex = firstRow; rowIndex <= lastRow; rowIndex++){
41319                 tbody.removeChild(rows[firstRow]);
41320             }
41321             this.stripeRows(firstRow);
41322             this.fireEvent("rowsdeleted", this, firstRow, lastRow);
41323         }
41324     },
41325
41326     updateRows : function(dataSource, firstRow, lastRow){
41327         var s = this.getScrollState();
41328         this.refresh();
41329         this.restoreScroll(s);
41330     },
41331
41332     handleSort : function(dataSource, sortColumnIndex, sortDir, noRefresh){
41333         if(!noRefresh){
41334            this.refresh();
41335         }
41336         this.updateHeaderSortState();
41337     },
41338
41339     getScrollState : function(){
41340         
41341         var sb = this.scroller.dom;
41342         return {left: sb.scrollLeft, top: sb.scrollTop};
41343     },
41344
41345     stripeRows : function(startRow){
41346         if(!this.grid.stripeRows || this.ds.getCount() < 1){
41347             return;
41348         }
41349         startRow = startRow || 0;
41350         var rows = this.getBodyTable().rows;
41351         var lrows = this.getLockedTable().rows;
41352         var cls = ' x-grid-row-alt ';
41353         for(var i = startRow, len = rows.length; i < len; i++){
41354             var row = rows[i], lrow = lrows[i];
41355             var isAlt = ((i+1) % 2 == 0);
41356             var hasAlt = (' '+row.className + ' ').indexOf(cls) != -1;
41357             if(isAlt == hasAlt){
41358                 continue;
41359             }
41360             if(isAlt){
41361                 row.className += " x-grid-row-alt";
41362             }else{
41363                 row.className = row.className.replace("x-grid-row-alt", "");
41364             }
41365             if(lrow){
41366                 lrow.className = row.className;
41367             }
41368         }
41369     },
41370
41371     restoreScroll : function(state){
41372         //Roo.log('GridView.restoreScroll');
41373         var sb = this.scroller.dom;
41374         sb.scrollLeft = state.left;
41375         sb.scrollTop = state.top;
41376         this.syncScroll();
41377     },
41378
41379     syncScroll : function(){
41380         //Roo.log('GridView.syncScroll');
41381         var sb = this.scroller.dom;
41382         var sh = this.mainHd.dom;
41383         var bs = this.mainBody.dom;
41384         var lv = this.lockedBody.dom;
41385         sh.scrollLeft = bs.scrollLeft = sb.scrollLeft;
41386         lv.scrollTop = bs.scrollTop = sb.scrollTop;
41387     },
41388
41389     handleScroll : function(e){
41390         this.syncScroll();
41391         var sb = this.scroller.dom;
41392         this.grid.fireEvent("bodyscroll", sb.scrollLeft, sb.scrollTop);
41393         e.stopEvent();
41394     },
41395
41396     handleWheel : function(e){
41397         var d = e.getWheelDelta();
41398         this.scroller.dom.scrollTop -= d*22;
41399         // set this here to prevent jumpy scrolling on large tables
41400         this.lockedBody.dom.scrollTop = this.mainBody.dom.scrollTop = this.scroller.dom.scrollTop;
41401         e.stopEvent();
41402     },
41403
41404     renderRows : function(startRow, endRow){
41405         // pull in all the crap needed to render rows
41406         var g = this.grid, cm = g.colModel, ds = g.dataSource, stripe = g.stripeRows;
41407         var colCount = cm.getColumnCount();
41408
41409         if(ds.getCount() < 1){
41410             return ["", ""];
41411         }
41412
41413         // build a map for all the columns
41414         var cs = [];
41415         for(var i = 0; i < colCount; i++){
41416             var name = cm.getDataIndex(i);
41417             cs[i] = {
41418                 name : typeof name == 'undefined' ? ds.fields.get(i).name : name,
41419                 renderer : cm.getRenderer(i),
41420                 id : cm.getColumnId(i),
41421                 locked : cm.isLocked(i),
41422                 has_editor : cm.isCellEditable(i)
41423             };
41424         }
41425
41426         startRow = startRow || 0;
41427         endRow = typeof endRow == "undefined"? ds.getCount()-1 : endRow;
41428
41429         // records to render
41430         var rs = ds.getRange(startRow, endRow);
41431
41432         return this.doRender(cs, rs, ds, startRow, colCount, stripe);
41433     },
41434
41435     // As much as I hate to duplicate code, this was branched because FireFox really hates
41436     // [].join("") on strings. The performance difference was substantial enough to
41437     // branch this function
41438     doRender : Roo.isGecko ?
41439             function(cs, rs, ds, startRow, colCount, stripe){
41440                 var ts = this.templates, ct = ts.cell, rt = ts.row;
41441                 // buffers
41442                 var buf = "", lbuf = "", cb, lcb, c, p = {}, rp = {}, r, rowIndex;
41443                 
41444                 var hasListener = this.grid.hasListener('rowclass');
41445                 var rowcfg = {};
41446                 for(var j = 0, len = rs.length; j < len; j++){
41447                     r = rs[j]; cb = ""; lcb = ""; rowIndex = (j+startRow);
41448                     for(var i = 0; i < colCount; i++){
41449                         c = cs[i];
41450                         p.cellId = "x-grid-cell-" + rowIndex + "-" + i;
41451                         p.id = c.id;
41452                         p.css = p.attr = "";
41453                         p.value = c.renderer(r.data[c.name], p, r, rowIndex, i, ds);
41454                         if(p.value == undefined || p.value === "") {
41455                             p.value = "&#160;";
41456                         }
41457                         if(c.has_editor){
41458                             p.css += ' x-grid-editable-cell';
41459                         }
41460                         if(c.dirty && typeof r.modified[c.name] !== 'undefined'){
41461                             p.css +=  ' x-grid-dirty-cell';
41462                         }
41463                         var markup = ct.apply(p);
41464                         if(!c.locked){
41465                             cb+= markup;
41466                         }else{
41467                             lcb+= markup;
41468                         }
41469                     }
41470                     var alt = [];
41471                     if(stripe && ((rowIndex+1) % 2 == 0)){
41472                         alt.push("x-grid-row-alt")
41473                     }
41474                     if(r.dirty){
41475                         alt.push(  " x-grid-dirty-row");
41476                     }
41477                     rp.cells = lcb;
41478                     if(this.getRowClass){
41479                         alt.push(this.getRowClass(r, rowIndex));
41480                     }
41481                     if (hasListener) {
41482                         rowcfg = {
41483                              
41484                             record: r,
41485                             rowIndex : rowIndex,
41486                             rowClass : ''
41487                         };
41488                         this.grid.fireEvent('rowclass', this, rowcfg);
41489                         alt.push(rowcfg.rowClass);
41490                     }
41491                     rp.alt = alt.join(" ");
41492                     lbuf+= rt.apply(rp);
41493                     rp.cells = cb;
41494                     buf+=  rt.apply(rp);
41495                 }
41496                 return [lbuf, buf];
41497             } :
41498             function(cs, rs, ds, startRow, colCount, stripe){
41499                 var ts = this.templates, ct = ts.cell, rt = ts.row;
41500                 // buffers
41501                 var buf = [], lbuf = [], cb, lcb, c, p = {}, rp = {}, r, rowIndex;
41502                 var hasListener = this.grid.hasListener('rowclass');
41503  
41504                 var rowcfg = {};
41505                 for(var j = 0, len = rs.length; j < len; j++){
41506                     r = rs[j]; cb = []; lcb = []; rowIndex = (j+startRow);
41507                     for(var i = 0; i < colCount; i++){
41508                         c = cs[i];
41509                         p.cellId = "x-grid-cell-" + rowIndex + "-" + i;
41510                         p.id = c.id;
41511                         p.css = p.attr = "";
41512                         p.value = c.renderer(r.data[c.name], p, r, rowIndex, i, ds);
41513                         if(p.value == undefined || p.value === "") {
41514                             p.value = "&#160;";
41515                         }
41516                         //Roo.log(c);
41517                          if(c.has_editor){
41518                             p.css += ' x-grid-editable-cell';
41519                         }
41520                         if(r.dirty && typeof r.modified[c.name] !== 'undefined'){
41521                             p.css += ' x-grid-dirty-cell' 
41522                         }
41523                         
41524                         var markup = ct.apply(p);
41525                         if(!c.locked){
41526                             cb[cb.length] = markup;
41527                         }else{
41528                             lcb[lcb.length] = markup;
41529                         }
41530                     }
41531                     var alt = [];
41532                     if(stripe && ((rowIndex+1) % 2 == 0)){
41533                         alt.push( "x-grid-row-alt");
41534                     }
41535                     if(r.dirty){
41536                         alt.push(" x-grid-dirty-row");
41537                     }
41538                     rp.cells = lcb;
41539                     if(this.getRowClass){
41540                         alt.push( this.getRowClass(r, rowIndex));
41541                     }
41542                     if (hasListener) {
41543                         rowcfg = {
41544                              
41545                             record: r,
41546                             rowIndex : rowIndex,
41547                             rowClass : ''
41548                         };
41549                         this.grid.fireEvent('rowclass', this, rowcfg);
41550                         alt.push(rowcfg.rowClass);
41551                     }
41552                     
41553                     rp.alt = alt.join(" ");
41554                     rp.cells = lcb.join("");
41555                     lbuf[lbuf.length] = rt.apply(rp);
41556                     rp.cells = cb.join("");
41557                     buf[buf.length] =  rt.apply(rp);
41558                 }
41559                 return [lbuf.join(""), buf.join("")];
41560             },
41561
41562     renderBody : function(){
41563         var markup = this.renderRows();
41564         var bt = this.templates.body;
41565         return [bt.apply({rows: markup[0]}), bt.apply({rows: markup[1]})];
41566     },
41567
41568     /**
41569      * Refreshes the grid
41570      * @param {Boolean} headersToo
41571      */
41572     refresh : function(headersToo){
41573         this.fireEvent("beforerefresh", this);
41574         this.grid.stopEditing();
41575         var result = this.renderBody();
41576         this.lockedBody.update(result[0]);
41577         this.mainBody.update(result[1]);
41578         if(headersToo === true){
41579             this.updateHeaders();
41580             this.updateColumns();
41581             this.updateSplitters();
41582             this.updateHeaderSortState();
41583         }
41584         this.syncRowHeights();
41585         this.layout();
41586         this.fireEvent("refresh", this);
41587     },
41588
41589     handleColumnMove : function(cm, oldIndex, newIndex){
41590         this.indexMap = null;
41591         var s = this.getScrollState();
41592         this.refresh(true);
41593         this.restoreScroll(s);
41594         this.afterMove(newIndex);
41595     },
41596
41597     afterMove : function(colIndex){
41598         if(this.enableMoveAnim && Roo.enableFx){
41599             this.fly(this.getHeaderCell(colIndex).firstChild).highlight(this.hlColor);
41600         }
41601         // if multisort - fix sortOrder, and reload..
41602         if (this.grid.dataSource.multiSort) {
41603             // the we can call sort again..
41604             var dm = this.grid.dataSource;
41605             var cm = this.grid.colModel;
41606             var so = [];
41607             for(var i = 0; i < cm.config.length; i++ ) {
41608                 
41609                 if ((typeof(dm.sortToggle[cm.config[i].dataIndex]) == 'undefined')) {
41610                     continue; // dont' bother, it's not in sort list or being set.
41611                 }
41612                 
41613                 so.push(cm.config[i].dataIndex);
41614             };
41615             dm.sortOrder = so;
41616             dm.load(dm.lastOptions);
41617             
41618             
41619         }
41620         
41621     },
41622
41623     updateCell : function(dm, rowIndex, dataIndex){
41624         var colIndex = this.getColumnIndexByDataIndex(dataIndex);
41625         if(typeof colIndex == "undefined"){ // not present in grid
41626             return;
41627         }
41628         var cm = this.grid.colModel;
41629         var cell = this.getCell(rowIndex, colIndex);
41630         var cellText = this.getCellText(rowIndex, colIndex);
41631
41632         var p = {
41633             cellId : "x-grid-cell-" + rowIndex + "-" + colIndex,
41634             id : cm.getColumnId(colIndex),
41635             css: colIndex == cm.getColumnCount()-1 ? "x-grid-col-last" : ""
41636         };
41637         var renderer = cm.getRenderer(colIndex);
41638         var val = renderer(dm.getValueAt(rowIndex, dataIndex), p, rowIndex, colIndex, dm);
41639         if(typeof val == "undefined" || val === "") {
41640             val = "&#160;";
41641         }
41642         cellText.innerHTML = val;
41643         cell.className = this.cellClass + " " + this.idToCssName(p.cellId) + " " + p.css;
41644         this.syncRowHeights(rowIndex, rowIndex);
41645     },
41646
41647     calcColumnWidth : function(colIndex, maxRowsToMeasure){
41648         var maxWidth = 0;
41649         if(this.grid.autoSizeHeaders){
41650             var h = this.getHeaderCellMeasure(colIndex);
41651             maxWidth = Math.max(maxWidth, h.scrollWidth);
41652         }
41653         var tb, index;
41654         if(this.cm.isLocked(colIndex)){
41655             tb = this.getLockedTable();
41656             index = colIndex;
41657         }else{
41658             tb = this.getBodyTable();
41659             index = colIndex - this.cm.getLockedCount();
41660         }
41661         if(tb && tb.rows){
41662             var rows = tb.rows;
41663             var stopIndex = Math.min(maxRowsToMeasure || rows.length, rows.length);
41664             for(var i = 0; i < stopIndex; i++){
41665                 var cell = rows[i].childNodes[index].firstChild;
41666                 maxWidth = Math.max(maxWidth, cell.scrollWidth);
41667             }
41668         }
41669         return maxWidth + /*margin for error in IE*/ 5;
41670     },
41671     /**
41672      * Autofit a column to its content.
41673      * @param {Number} colIndex
41674      * @param {Boolean} forceMinSize true to force the column to go smaller if possible
41675      */
41676      autoSizeColumn : function(colIndex, forceMinSize, suppressEvent){
41677          if(this.cm.isHidden(colIndex)){
41678              return; // can't calc a hidden column
41679          }
41680         if(forceMinSize){
41681             var cid = this.cm.getColumnId(colIndex);
41682             this.css.updateRule(this.colSelector +this.idToCssName( cid), "width", this.grid.minColumnWidth + "px");
41683            if(this.grid.autoSizeHeaders){
41684                this.css.updateRule(this.hdSelector + this.idToCssName(cid), "width", this.grid.minColumnWidth + "px");
41685            }
41686         }
41687         var newWidth = this.calcColumnWidth(colIndex);
41688         this.cm.setColumnWidth(colIndex,
41689             Math.max(this.grid.minColumnWidth, newWidth), suppressEvent);
41690         if(!suppressEvent){
41691             this.grid.fireEvent("columnresize", colIndex, newWidth);
41692         }
41693     },
41694
41695     /**
41696      * Autofits all columns to their content and then expands to fit any extra space in the grid
41697      */
41698      autoSizeColumns : function(){
41699         var cm = this.grid.colModel;
41700         var colCount = cm.getColumnCount();
41701         for(var i = 0; i < colCount; i++){
41702             this.autoSizeColumn(i, true, true);
41703         }
41704         if(cm.getTotalWidth() < this.scroller.dom.clientWidth){
41705             this.fitColumns();
41706         }else{
41707             this.updateColumns();
41708             this.layout();
41709         }
41710     },
41711
41712     /**
41713      * Autofits all columns to the grid's width proportionate with their current size
41714      * @param {Boolean} reserveScrollSpace Reserve space for a scrollbar
41715      */
41716     fitColumns : function(reserveScrollSpace){
41717         var cm = this.grid.colModel;
41718         var colCount = cm.getColumnCount();
41719         var cols = [];
41720         var width = 0;
41721         var i, w;
41722         for (i = 0; i < colCount; i++){
41723             if(!cm.isHidden(i) && !cm.isFixed(i)){
41724                 w = cm.getColumnWidth(i);
41725                 cols.push(i);
41726                 cols.push(w);
41727                 width += w;
41728             }
41729         }
41730         var avail = Math.min(this.scroller.dom.clientWidth, this.el.getWidth());
41731         if(reserveScrollSpace){
41732             avail -= 17;
41733         }
41734         var frac = (avail - cm.getTotalWidth())/width;
41735         while (cols.length){
41736             w = cols.pop();
41737             i = cols.pop();
41738             cm.setColumnWidth(i, Math.floor(w + w*frac), true);
41739         }
41740         this.updateColumns();
41741         this.layout();
41742     },
41743
41744     onRowSelect : function(rowIndex){
41745         var row = this.getRowComposite(rowIndex);
41746         row.addClass("x-grid-row-selected");
41747     },
41748
41749     onRowDeselect : function(rowIndex){
41750         var row = this.getRowComposite(rowIndex);
41751         row.removeClass("x-grid-row-selected");
41752     },
41753
41754     onCellSelect : function(row, col){
41755         var cell = this.getCell(row, col);
41756         if(cell){
41757             Roo.fly(cell).addClass("x-grid-cell-selected");
41758         }
41759     },
41760
41761     onCellDeselect : function(row, col){
41762         var cell = this.getCell(row, col);
41763         if(cell){
41764             Roo.fly(cell).removeClass("x-grid-cell-selected");
41765         }
41766     },
41767
41768     updateHeaderSortState : function(){
41769         
41770         // sort state can be single { field: xxx, direction : yyy}
41771         // or   { xxx=>ASC , yyy : DESC ..... }
41772         
41773         var mstate = {};
41774         if (!this.ds.multiSort) { 
41775             var state = this.ds.getSortState();
41776             if(!state){
41777                 return;
41778             }
41779             mstate[state.field] = state.direction;
41780             // FIXME... - this is not used here.. but might be elsewhere..
41781             this.sortState = state;
41782             
41783         } else {
41784             mstate = this.ds.sortToggle;
41785         }
41786         //remove existing sort classes..
41787         
41788         var sc = this.sortClasses;
41789         var hds = this.el.select(this.headerSelector).removeClass(sc);
41790         
41791         for(var f in mstate) {
41792         
41793             var sortColumn = this.cm.findColumnIndex(f);
41794             
41795             if(sortColumn != -1){
41796                 var sortDir = mstate[f];        
41797                 hds.item(sortColumn).addClass(sc[sortDir == "DESC" ? 1 : 0]);
41798             }
41799         }
41800         
41801          
41802         
41803     },
41804
41805
41806     handleHeaderClick : function(g, index,e){
41807         
41808         Roo.log("header click");
41809         
41810         if (Roo.isTouch) {
41811             // touch events on header are handled by context
41812             this.handleHdCtx(g,index,e);
41813             return;
41814         }
41815         
41816         
41817         if(this.headersDisabled){
41818             return;
41819         }
41820         var dm = g.dataSource, cm = g.colModel;
41821         if(!cm.isSortable(index)){
41822             return;
41823         }
41824         g.stopEditing();
41825         
41826         if (dm.multiSort) {
41827             // update the sortOrder
41828             var so = [];
41829             for(var i = 0; i < cm.config.length; i++ ) {
41830                 
41831                 if ((typeof(dm.sortToggle[cm.config[i].dataIndex]) == 'undefined') && (index != i)) {
41832                     continue; // dont' bother, it's not in sort list or being set.
41833                 }
41834                 
41835                 so.push(cm.config[i].dataIndex);
41836             };
41837             dm.sortOrder = so;
41838         }
41839         
41840         
41841         dm.sort(cm.getDataIndex(index));
41842     },
41843
41844
41845     destroy : function(){
41846         if(this.colMenu){
41847             this.colMenu.removeAll();
41848             Roo.menu.MenuMgr.unregister(this.colMenu);
41849             this.colMenu.getEl().remove();
41850             delete this.colMenu;
41851         }
41852         if(this.hmenu){
41853             this.hmenu.removeAll();
41854             Roo.menu.MenuMgr.unregister(this.hmenu);
41855             this.hmenu.getEl().remove();
41856             delete this.hmenu;
41857         }
41858         if(this.grid.enableColumnMove){
41859             var dds = Roo.dd.DDM.ids['gridHeader' + this.grid.getGridEl().id];
41860             if(dds){
41861                 for(var dd in dds){
41862                     if(!dds[dd].config.isTarget && dds[dd].dragElId){
41863                         var elid = dds[dd].dragElId;
41864                         dds[dd].unreg();
41865                         Roo.get(elid).remove();
41866                     } else if(dds[dd].config.isTarget){
41867                         dds[dd].proxyTop.remove();
41868                         dds[dd].proxyBottom.remove();
41869                         dds[dd].unreg();
41870                     }
41871                     if(Roo.dd.DDM.locationCache[dd]){
41872                         delete Roo.dd.DDM.locationCache[dd];
41873                     }
41874                 }
41875                 delete Roo.dd.DDM.ids['gridHeader' + this.grid.getGridEl().id];
41876             }
41877         }
41878         Roo.util.CSS.removeStyleSheet(this.idToCssName(this.grid.id) + '-cssrules');
41879         this.bind(null, null);
41880         Roo.EventManager.removeResizeListener(this.onWindowResize, this);
41881     },
41882
41883     handleLockChange : function(){
41884         this.refresh(true);
41885     },
41886
41887     onDenyColumnLock : function(){
41888
41889     },
41890
41891     onDenyColumnHide : function(){
41892
41893     },
41894
41895     handleHdMenuClick : function(item){
41896         var index = this.hdCtxIndex;
41897         var cm = this.cm, ds = this.ds;
41898         switch(item.id){
41899             case "asc":
41900                 ds.sort(cm.getDataIndex(index), "ASC");
41901                 break;
41902             case "desc":
41903                 ds.sort(cm.getDataIndex(index), "DESC");
41904                 break;
41905             case "lock":
41906                 var lc = cm.getLockedCount();
41907                 if(cm.getColumnCount(true) <= lc+1){
41908                     this.onDenyColumnLock();
41909                     return;
41910                 }
41911                 if(lc != index){
41912                     cm.setLocked(index, true, true);
41913                     cm.moveColumn(index, lc);
41914                     this.grid.fireEvent("columnmove", index, lc);
41915                 }else{
41916                     cm.setLocked(index, true);
41917                 }
41918             break;
41919             case "unlock":
41920                 var lc = cm.getLockedCount();
41921                 if((lc-1) != index){
41922                     cm.setLocked(index, false, true);
41923                     cm.moveColumn(index, lc-1);
41924                     this.grid.fireEvent("columnmove", index, lc-1);
41925                 }else{
41926                     cm.setLocked(index, false);
41927                 }
41928             break;
41929             case 'wider': // used to expand cols on touch..
41930             case 'narrow':
41931                 var cw = cm.getColumnWidth(index);
41932                 cw += (item.id == 'wider' ? 1 : -1) * 50;
41933                 cw = Math.max(0, cw);
41934                 cw = Math.min(cw,4000);
41935                 cm.setColumnWidth(index, cw);
41936                 break;
41937                 
41938             default:
41939                 index = cm.getIndexById(item.id.substr(4));
41940                 if(index != -1){
41941                     if(item.checked && cm.getColumnCount(true) <= 1){
41942                         this.onDenyColumnHide();
41943                         return false;
41944                     }
41945                     cm.setHidden(index, item.checked);
41946                 }
41947         }
41948         return true;
41949     },
41950
41951     beforeColMenuShow : function(){
41952         var cm = this.cm,  colCount = cm.getColumnCount();
41953         this.colMenu.removeAll();
41954         
41955         var items = [];
41956         for(var i = 0; i < colCount; i++){
41957             items.push({
41958                 id: "col-"+cm.getColumnId(i),
41959                 text: cm.getColumnHeader(i),
41960                 checked: !cm.isHidden(i),
41961                 hideOnClick:false
41962             });
41963         }
41964         
41965         if (this.grid.sortColMenu) {
41966             items.sort(function(a,b) {
41967                 if (a.text == b.text) {
41968                     return 0;
41969                 }
41970                 return a.text.toUpperCase() > b.text.toUpperCase() ? 1 : -1;
41971             });
41972         }
41973         
41974         for(var i = 0; i < colCount; i++){
41975             this.colMenu.add(new Roo.menu.CheckItem(items[i]));
41976         }
41977     },
41978
41979     handleHdCtx : function(g, index, e){
41980         e.stopEvent();
41981         var hd = this.getHeaderCell(index);
41982         this.hdCtxIndex = index;
41983         var ms = this.hmenu.items, cm = this.cm;
41984         ms.get("asc").setDisabled(!cm.isSortable(index));
41985         ms.get("desc").setDisabled(!cm.isSortable(index));
41986         if(this.grid.enableColLock !== false){
41987             ms.get("lock").setDisabled(cm.isLocked(index));
41988             ms.get("unlock").setDisabled(!cm.isLocked(index));
41989         }
41990         this.hmenu.show(hd, "tl-bl");
41991     },
41992
41993     handleHdOver : function(e){
41994         var hd = this.findHeaderCell(e.getTarget());
41995         if(hd && !this.headersDisabled){
41996             if(this.grid.colModel.isSortable(this.getCellIndex(hd))){
41997                this.fly(hd).addClass("x-grid-hd-over");
41998             }
41999         }
42000     },
42001
42002     handleHdOut : function(e){
42003         var hd = this.findHeaderCell(e.getTarget());
42004         if(hd){
42005             this.fly(hd).removeClass("x-grid-hd-over");
42006         }
42007     },
42008
42009     handleSplitDblClick : function(e, t){
42010         var i = this.getCellIndex(t);
42011         if(this.grid.enableColumnResize !== false && this.cm.isResizable(i) && !this.cm.isFixed(i)){
42012             this.autoSizeColumn(i, true);
42013             this.layout();
42014         }
42015     },
42016
42017     render : function(){
42018
42019         var cm = this.cm;
42020         var colCount = cm.getColumnCount();
42021
42022         if(this.grid.monitorWindowResize === true){
42023             Roo.EventManager.onWindowResize(this.onWindowResize, this, true);
42024         }
42025         var header = this.renderHeaders();
42026         var body = this.templates.body.apply({rows:""});
42027         var html = this.templates.master.apply({
42028             lockedBody: body,
42029             body: body,
42030             lockedHeader: header[0],
42031             header: header[1]
42032         });
42033
42034         //this.updateColumns();
42035
42036         this.grid.getGridEl().dom.innerHTML = html;
42037
42038         this.initElements();
42039         
42040         // a kludge to fix the random scolling effect in webkit
42041         this.el.on("scroll", function() {
42042             this.el.dom.scrollTop=0; // hopefully not recursive..
42043         },this);
42044
42045         this.scroller.on("scroll", this.handleScroll, this);
42046         this.lockedBody.on("mousewheel", this.handleWheel, this);
42047         this.mainBody.on("mousewheel", this.handleWheel, this);
42048
42049         this.mainHd.on("mouseover", this.handleHdOver, this);
42050         this.mainHd.on("mouseout", this.handleHdOut, this);
42051         this.mainHd.on("dblclick", this.handleSplitDblClick, this,
42052                 {delegate: "."+this.splitClass});
42053
42054         this.lockedHd.on("mouseover", this.handleHdOver, this);
42055         this.lockedHd.on("mouseout", this.handleHdOut, this);
42056         this.lockedHd.on("dblclick", this.handleSplitDblClick, this,
42057                 {delegate: "."+this.splitClass});
42058
42059         if(this.grid.enableColumnResize !== false && Roo.grid.SplitDragZone){
42060             new Roo.grid.SplitDragZone(this.grid, this.lockedHd.dom, this.mainHd.dom);
42061         }
42062
42063         this.updateSplitters();
42064
42065         if(this.grid.enableColumnMove && Roo.grid.HeaderDragZone){
42066             new Roo.grid.HeaderDragZone(this.grid, this.lockedHd.dom, this.mainHd.dom);
42067             new Roo.grid.HeaderDropZone(this.grid, this.lockedHd.dom, this.mainHd.dom);
42068         }
42069
42070         if(this.grid.enableCtxMenu !== false && Roo.menu.Menu){
42071             this.hmenu = new Roo.menu.Menu({id: this.grid.id + "-hctx"});
42072             this.hmenu.add(
42073                 {id:"asc", text: this.sortAscText, cls: "xg-hmenu-sort-asc"},
42074                 {id:"desc", text: this.sortDescText, cls: "xg-hmenu-sort-desc"}
42075             );
42076             if(this.grid.enableColLock !== false){
42077                 this.hmenu.add('-',
42078                     {id:"lock", text: this.lockText, cls: "xg-hmenu-lock"},
42079                     {id:"unlock", text: this.unlockText, cls: "xg-hmenu-unlock"}
42080                 );
42081             }
42082             if (Roo.isTouch) {
42083                  this.hmenu.add('-',
42084                     {id:"wider", text: this.columnsWiderText},
42085                     {id:"narrow", text: this.columnsNarrowText }
42086                 );
42087                 
42088                  
42089             }
42090             
42091             if(this.grid.enableColumnHide !== false){
42092
42093                 this.colMenu = new Roo.menu.Menu({id:this.grid.id + "-hcols-menu"});
42094                 this.colMenu.on("beforeshow", this.beforeColMenuShow, this);
42095                 this.colMenu.on("itemclick", this.handleHdMenuClick, this);
42096
42097                 this.hmenu.add('-',
42098                     {id:"columns", text: this.columnsText, menu: this.colMenu}
42099                 );
42100             }
42101             this.hmenu.on("itemclick", this.handleHdMenuClick, this);
42102
42103             this.grid.on("headercontextmenu", this.handleHdCtx, this);
42104         }
42105
42106         if((this.grid.enableDragDrop || this.grid.enableDrag) && Roo.grid.GridDragZone){
42107             this.dd = new Roo.grid.GridDragZone(this.grid, {
42108                 ddGroup : this.grid.ddGroup || 'GridDD'
42109             });
42110             
42111         }
42112
42113         /*
42114         for(var i = 0; i < colCount; i++){
42115             if(cm.isHidden(i)){
42116                 this.hideColumn(i);
42117             }
42118             if(cm.config[i].align){
42119                 this.css.updateRule(this.colSelector + i, "textAlign", cm.config[i].align);
42120                 this.css.updateRule(this.hdSelector + i, "textAlign", cm.config[i].align);
42121             }
42122         }*/
42123         
42124         this.updateHeaderSortState();
42125
42126         this.beforeInitialResize();
42127         this.layout(true);
42128
42129         // two part rendering gives faster view to the user
42130         this.renderPhase2.defer(1, this);
42131     },
42132
42133     renderPhase2 : function(){
42134         // render the rows now
42135         this.refresh();
42136         if(this.grid.autoSizeColumns){
42137             this.autoSizeColumns();
42138         }
42139     },
42140
42141     beforeInitialResize : function(){
42142
42143     },
42144
42145     onColumnSplitterMoved : function(i, w){
42146         this.userResized = true;
42147         var cm = this.grid.colModel;
42148         cm.setColumnWidth(i, w, true);
42149         var cid = cm.getColumnId(i);
42150         this.css.updateRule(this.colSelector + this.idToCssName(cid), "width", (w-this.borderWidth) + "px");
42151         this.css.updateRule(this.hdSelector + this.idToCssName(cid), "width", (w-this.borderWidth) + "px");
42152         this.updateSplitters();
42153         this.layout();
42154         this.grid.fireEvent("columnresize", i, w);
42155     },
42156
42157     syncRowHeights : function(startIndex, endIndex){
42158         if(this.grid.enableRowHeightSync === true && this.cm.getLockedCount() > 0){
42159             startIndex = startIndex || 0;
42160             var mrows = this.getBodyTable().rows;
42161             var lrows = this.getLockedTable().rows;
42162             var len = mrows.length-1;
42163             endIndex = Math.min(endIndex || len, len);
42164             for(var i = startIndex; i <= endIndex; i++){
42165                 var m = mrows[i], l = lrows[i];
42166                 var h = Math.max(m.offsetHeight, l.offsetHeight);
42167                 m.style.height = l.style.height = h + "px";
42168             }
42169         }
42170     },
42171
42172     layout : function(initialRender, is2ndPass)
42173     {
42174         var g = this.grid;
42175         var auto = g.autoHeight;
42176         var scrollOffset = 16;
42177         var c = g.getGridEl(), cm = this.cm,
42178                 expandCol = g.autoExpandColumn,
42179                 gv = this;
42180         //c.beginMeasure();
42181
42182         if(!c.dom.offsetWidth){ // display:none?
42183             if(initialRender){
42184                 this.lockedWrap.show();
42185                 this.mainWrap.show();
42186             }
42187             return;
42188         }
42189
42190         var hasLock = this.cm.isLocked(0);
42191
42192         var tbh = this.headerPanel.getHeight();
42193         var bbh = this.footerPanel.getHeight();
42194
42195         if(auto){
42196             var ch = this.getBodyTable().offsetHeight + tbh + bbh + this.mainHd.getHeight();
42197             var newHeight = ch + c.getBorderWidth("tb");
42198             if(g.maxHeight){
42199                 newHeight = Math.min(g.maxHeight, newHeight);
42200             }
42201             c.setHeight(newHeight);
42202         }
42203
42204         if(g.autoWidth){
42205             c.setWidth(cm.getTotalWidth()+c.getBorderWidth('lr'));
42206         }
42207
42208         var s = this.scroller;
42209
42210         var csize = c.getSize(true);
42211
42212         this.el.setSize(csize.width, csize.height);
42213
42214         this.headerPanel.setWidth(csize.width);
42215         this.footerPanel.setWidth(csize.width);
42216
42217         var hdHeight = this.mainHd.getHeight();
42218         var vw = csize.width;
42219         var vh = csize.height - (tbh + bbh);
42220
42221         s.setSize(vw, vh);
42222
42223         var bt = this.getBodyTable();
42224         
42225         if(cm.getLockedCount() == cm.config.length){
42226             bt = this.getLockedTable();
42227         }
42228         
42229         var ltWidth = hasLock ?
42230                       Math.max(this.getLockedTable().offsetWidth, this.lockedHd.dom.firstChild.offsetWidth) : 0;
42231
42232         var scrollHeight = bt.offsetHeight;
42233         var scrollWidth = ltWidth + bt.offsetWidth;
42234         var vscroll = false, hscroll = false;
42235
42236         this.scrollSizer.setSize(scrollWidth, scrollHeight+hdHeight);
42237
42238         var lw = this.lockedWrap, mw = this.mainWrap;
42239         var lb = this.lockedBody, mb = this.mainBody;
42240
42241         setTimeout(function(){
42242             var t = s.dom.offsetTop;
42243             var w = s.dom.clientWidth,
42244                 h = s.dom.clientHeight;
42245
42246             lw.setTop(t);
42247             lw.setSize(ltWidth, h);
42248
42249             mw.setLeftTop(ltWidth, t);
42250             mw.setSize(w-ltWidth, h);
42251
42252             lb.setHeight(h-hdHeight);
42253             mb.setHeight(h-hdHeight);
42254
42255             if(is2ndPass !== true && !gv.userResized && expandCol){
42256                 // high speed resize without full column calculation
42257                 
42258                 var ci = cm.getIndexById(expandCol);
42259                 if (ci < 0) {
42260                     ci = cm.findColumnIndex(expandCol);
42261                 }
42262                 ci = Math.max(0, ci); // make sure it's got at least the first col.
42263                 var expandId = cm.getColumnId(ci);
42264                 var  tw = cm.getTotalWidth(false);
42265                 var currentWidth = cm.getColumnWidth(ci);
42266                 var cw = Math.min(Math.max(((w-tw)+currentWidth-2)-/*scrollbar*/(w <= s.dom.offsetWidth ? 0 : 18), g.autoExpandMin), g.autoExpandMax);
42267                 if(currentWidth != cw){
42268                     cm.setColumnWidth(ci, cw, true);
42269                     gv.css.updateRule(gv.colSelector+gv.idToCssName(expandId), "width", (cw - gv.borderWidth) + "px");
42270                     gv.css.updateRule(gv.hdSelector+gv.idToCssName(expandId), "width", (cw - gv.borderWidth) + "px");
42271                     gv.updateSplitters();
42272                     gv.layout(false, true);
42273                 }
42274             }
42275
42276             if(initialRender){
42277                 lw.show();
42278                 mw.show();
42279             }
42280             //c.endMeasure();
42281         }, 10);
42282     },
42283
42284     onWindowResize : function(){
42285         if(!this.grid.monitorWindowResize || this.grid.autoHeight){
42286             return;
42287         }
42288         this.layout();
42289     },
42290
42291     appendFooter : function(parentEl){
42292         return null;
42293     },
42294
42295     sortAscText : "Sort Ascending",
42296     sortDescText : "Sort Descending",
42297     lockText : "Lock Column",
42298     unlockText : "Unlock Column",
42299     columnsText : "Columns",
42300  
42301     columnsWiderText : "Wider",
42302     columnsNarrowText : "Thinner"
42303 });
42304
42305
42306 Roo.grid.GridView.ColumnDragZone = function(grid, hd){
42307     Roo.grid.GridView.ColumnDragZone.superclass.constructor.call(this, grid, hd, null);
42308     this.proxy.el.addClass('x-grid3-col-dd');
42309 };
42310
42311 Roo.extend(Roo.grid.GridView.ColumnDragZone, Roo.grid.HeaderDragZone, {
42312     handleMouseDown : function(e){
42313
42314     },
42315
42316     callHandleMouseDown : function(e){
42317         Roo.grid.GridView.ColumnDragZone.superclass.handleMouseDown.call(this, e);
42318     }
42319 });
42320 /*
42321  * Based on:
42322  * Ext JS Library 1.1.1
42323  * Copyright(c) 2006-2007, Ext JS, LLC.
42324  *
42325  * Originally Released Under LGPL - original licence link has changed is not relivant.
42326  *
42327  * Fork - LGPL
42328  * <script type="text/javascript">
42329  */
42330  /**
42331  * @extends Roo.dd.DDProxy
42332  * @class Roo.grid.SplitDragZone
42333  * Support for Column Header resizing
42334  * @constructor
42335  * @param {Object} config
42336  */
42337 // private
42338 // This is a support class used internally by the Grid components
42339 Roo.grid.SplitDragZone = function(grid, hd, hd2){
42340     this.grid = grid;
42341     this.view = grid.getView();
42342     this.proxy = this.view.resizeProxy;
42343     Roo.grid.SplitDragZone.superclass.constructor.call(
42344         this,
42345         hd, // ID
42346         "gridSplitters" + this.grid.getGridEl().id, // SGROUP
42347         {  // CONFIG
42348             dragElId : Roo.id(this.proxy.dom),
42349             resizeFrame:false
42350         }
42351     );
42352     
42353     this.setHandleElId(Roo.id(hd));
42354     if (hd2 !== false) {
42355         this.setOuterHandleElId(Roo.id(hd2));
42356     }
42357     
42358     this.scroll = false;
42359 };
42360 Roo.extend(Roo.grid.SplitDragZone, Roo.dd.DDProxy, {
42361     fly: Roo.Element.fly,
42362
42363     b4StartDrag : function(x, y){
42364         this.view.headersDisabled = true;
42365         var h = this.view.mainWrap ? this.view.mainWrap.getHeight() : (
42366                     this.view.headEl.getHeight() + this.view.bodyEl.getHeight()
42367         );
42368         this.proxy.setHeight(h);
42369         
42370         // for old system colWidth really stored the actual width?
42371         // in bootstrap we tried using xs/ms/etc.. to do % sizing?
42372         // which in reality did not work.. - it worked only for fixed sizes
42373         // for resizable we need to use actual sizes.
42374         var w = this.cm.getColumnWidth(this.cellIndex);
42375         if (!this.view.mainWrap) {
42376             // bootstrap.
42377             w = this.view.getHeaderIndex(this.cellIndex).getWidth();
42378         }
42379         
42380         
42381         
42382         // this was w-this.grid.minColumnWidth;
42383         // doesnt really make sense? - w = thie curren width or the rendered one?
42384         var minw = Math.max(w-this.grid.minColumnWidth, 0);
42385         this.resetConstraints();
42386         this.setXConstraint(minw, 1000);
42387         this.setYConstraint(0, 0);
42388         this.minX = x - minw;
42389         this.maxX = x + 1000;
42390         this.startPos = x;
42391         if (!this.view.mainWrap) { // this is Bootstrap code..
42392             this.getDragEl().style.display='block';
42393         }
42394         
42395         Roo.dd.DDProxy.prototype.b4StartDrag.call(this, x, y);
42396     },
42397
42398
42399     handleMouseDown : function(e){
42400         ev = Roo.EventObject.setEvent(e);
42401         var t = this.fly(ev.getTarget());
42402         if(t.hasClass("x-grid-split")){
42403             this.cellIndex = this.view.getCellIndex(t.dom);
42404             this.split = t.dom;
42405             this.cm = this.grid.colModel;
42406             if(this.cm.isResizable(this.cellIndex) && !this.cm.isFixed(this.cellIndex)){
42407                 Roo.grid.SplitDragZone.superclass.handleMouseDown.apply(this, arguments);
42408             }
42409         }
42410     },
42411
42412     endDrag : function(e){
42413         this.view.headersDisabled = false;
42414         var endX = Math.max(this.minX, Roo.lib.Event.getPageX(e));
42415         var diff = endX - this.startPos;
42416         // 
42417         var w = this.cm.getColumnWidth(this.cellIndex);
42418         if (!this.view.mainWrap) {
42419             w = 0;
42420         }
42421         this.view.onColumnSplitterMoved(this.cellIndex, w+diff);
42422     },
42423
42424     autoOffset : function(){
42425         this.setDelta(0,0);
42426     }
42427 });/*
42428  * Based on:
42429  * Ext JS Library 1.1.1
42430  * Copyright(c) 2006-2007, Ext JS, LLC.
42431  *
42432  * Originally Released Under LGPL - original licence link has changed is not relivant.
42433  *
42434  * Fork - LGPL
42435  * <script type="text/javascript">
42436  */
42437  
42438 // private
42439 // This is a support class used internally by the Grid components
42440 Roo.grid.GridDragZone = function(grid, config){
42441     this.view = grid.getView();
42442     Roo.grid.GridDragZone.superclass.constructor.call(this, this.view.mainBody.dom, config);
42443     if(this.view.lockedBody){
42444         this.setHandleElId(Roo.id(this.view.mainBody.dom));
42445         this.setOuterHandleElId(Roo.id(this.view.lockedBody.dom));
42446     }
42447     this.scroll = false;
42448     this.grid = grid;
42449     this.ddel = document.createElement('div');
42450     this.ddel.className = 'x-grid-dd-wrap';
42451 };
42452
42453 Roo.extend(Roo.grid.GridDragZone, Roo.dd.DragZone, {
42454     ddGroup : "GridDD",
42455
42456     getDragData : function(e){
42457         var t = Roo.lib.Event.getTarget(e);
42458         var rowIndex = this.view.findRowIndex(t);
42459         var sm = this.grid.selModel;
42460             
42461         //Roo.log(rowIndex);
42462         
42463         if (sm.getSelectedCell) {
42464             // cell selection..
42465             if (!sm.getSelectedCell()) {
42466                 return false;
42467             }
42468             if (rowIndex != sm.getSelectedCell()[0]) {
42469                 return false;
42470             }
42471         
42472         }
42473         if (sm.getSelections && sm.getSelections().length < 1) {
42474             return false;
42475         }
42476         
42477         
42478         // before it used to all dragging of unseleted... - now we dont do that.
42479         if(rowIndex !== false){
42480             
42481             // if editorgrid.. 
42482             
42483             
42484             //Roo.log([ sm.getSelectedCell() ? sm.getSelectedCell()[0] : 'NO' , rowIndex ]);
42485                
42486             //if(!sm.isSelected(rowIndex) || e.hasModifier()){
42487               //  
42488             //}
42489             if (e.hasModifier()){
42490                 sm.handleMouseDown(e, t); // non modifier buttons are handled by row select.
42491             }
42492             
42493             Roo.log("getDragData");
42494             
42495             return {
42496                 grid: this.grid,
42497                 ddel: this.ddel,
42498                 rowIndex: rowIndex,
42499                 selections: sm.getSelections ? sm.getSelections() : (
42500                     sm.getSelectedCell() ? [ this.grid.ds.getAt(sm.getSelectedCell()[0]) ] : [])
42501             };
42502         }
42503         return false;
42504     },
42505     
42506     
42507     onInitDrag : function(e){
42508         var data = this.dragData;
42509         this.ddel.innerHTML = this.grid.getDragDropText();
42510         this.proxy.update(this.ddel);
42511         // fire start drag?
42512     },
42513
42514     afterRepair : function(){
42515         this.dragging = false;
42516     },
42517
42518     getRepairXY : function(e, data){
42519         return false;
42520     },
42521
42522     onEndDrag : function(data, e){
42523         // fire end drag?
42524     },
42525
42526     onValidDrop : function(dd, e, id){
42527         // fire drag drop?
42528         this.hideProxy();
42529     },
42530
42531     beforeInvalidDrop : function(e, id){
42532
42533     }
42534 });/*
42535  * Based on:
42536  * Ext JS Library 1.1.1
42537  * Copyright(c) 2006-2007, Ext JS, LLC.
42538  *
42539  * Originally Released Under LGPL - original licence link has changed is not relivant.
42540  *
42541  * Fork - LGPL
42542  * <script type="text/javascript">
42543  */
42544  
42545
42546 /**
42547  * @class Roo.grid.ColumnModel
42548  * @extends Roo.util.Observable
42549  * This is the default implementation of a ColumnModel used by the Grid. It defines
42550  * the columns in the grid.
42551  * <br>Usage:<br>
42552  <pre><code>
42553  var colModel = new Roo.grid.ColumnModel([
42554         {header: "Ticker", width: 60, sortable: true, locked: true},
42555         {header: "Company Name", width: 150, sortable: true},
42556         {header: "Market Cap.", width: 100, sortable: true},
42557         {header: "$ Sales", width: 100, sortable: true, renderer: money},
42558         {header: "Employees", width: 100, sortable: true, resizable: false}
42559  ]);
42560  </code></pre>
42561  * <p>
42562  
42563  * The config options listed for this class are options which may appear in each
42564  * individual column definition.
42565  * <br/>RooJS Fix - column id's are not sequential but use Roo.id() - fixes bugs with layouts.
42566  * @constructor
42567  * @param {Object} config An Array of column config objects. See this class's
42568  * config objects for details.
42569 */
42570 Roo.grid.ColumnModel = function(config){
42571         /**
42572      * The config passed into the constructor
42573      */
42574     this.config = []; //config;
42575     this.lookup = {};
42576
42577     // if no id, create one
42578     // if the column does not have a dataIndex mapping,
42579     // map it to the order it is in the config
42580     for(var i = 0, len = config.length; i < len; i++){
42581         this.addColumn(config[i]);
42582         
42583     }
42584
42585     /**
42586      * The width of columns which have no width specified (defaults to 100)
42587      * @type Number
42588      */
42589     this.defaultWidth = 100;
42590
42591     /**
42592      * Default sortable of columns which have no sortable specified (defaults to false)
42593      * @type Boolean
42594      */
42595     this.defaultSortable = false;
42596
42597     this.addEvents({
42598         /**
42599              * @event widthchange
42600              * Fires when the width of a column changes.
42601              * @param {ColumnModel} this
42602              * @param {Number} columnIndex The column index
42603              * @param {Number} newWidth The new width
42604              */
42605             "widthchange": true,
42606         /**
42607              * @event headerchange
42608              * Fires when the text of a header changes.
42609              * @param {ColumnModel} this
42610              * @param {Number} columnIndex The column index
42611              * @param {Number} newText The new header text
42612              */
42613             "headerchange": true,
42614         /**
42615              * @event hiddenchange
42616              * Fires when a column is hidden or "unhidden".
42617              * @param {ColumnModel} this
42618              * @param {Number} columnIndex The column index
42619              * @param {Boolean} hidden true if hidden, false otherwise
42620              */
42621             "hiddenchange": true,
42622             /**
42623          * @event columnmoved
42624          * Fires when a column is moved.
42625          * @param {ColumnModel} this
42626          * @param {Number} oldIndex
42627          * @param {Number} newIndex
42628          */
42629         "columnmoved" : true,
42630         /**
42631          * @event columlockchange
42632          * Fires when a column's locked state is changed
42633          * @param {ColumnModel} this
42634          * @param {Number} colIndex
42635          * @param {Boolean} locked true if locked
42636          */
42637         "columnlockchange" : true
42638     });
42639     Roo.grid.ColumnModel.superclass.constructor.call(this);
42640 };
42641 Roo.extend(Roo.grid.ColumnModel, Roo.util.Observable, {
42642     /**
42643      * @cfg {String} header [required] The header text to display in the Grid view.
42644      */
42645         /**
42646      * @cfg {String} xsHeader Header at Bootsrap Extra Small width (default for all)
42647      */
42648         /**
42649      * @cfg {String} smHeader Header at Bootsrap Small width
42650      */
42651         /**
42652      * @cfg {String} mdHeader Header at Bootsrap Medium width
42653      */
42654         /**
42655      * @cfg {String} lgHeader Header at Bootsrap Large width
42656      */
42657         /**
42658      * @cfg {String} xlHeader Header at Bootsrap extra Large width
42659      */
42660     /**
42661      * @cfg {String} dataIndex  The name of the field in the grid's {@link Roo.data.Store}'s
42662      * {@link Roo.data.Record} definition from which to draw the column's value. If not
42663      * specified, the column's index is used as an index into the Record's data Array.
42664      */
42665     /**
42666      * @cfg {Number} width  The initial width in pixels of the column. Using this
42667      * instead of {@link Roo.grid.Grid#autoSizeColumns} is more efficient.
42668      */
42669     /**
42670      * @cfg {Boolean} sortable True if sorting is to be allowed on this column.
42671      * Defaults to the value of the {@link #defaultSortable} property.
42672      * Whether local/remote sorting is used is specified in {@link Roo.data.Store#remoteSort}.
42673      */
42674     /**
42675      * @cfg {Boolean} locked  True to lock the column in place while scrolling the Grid.  Defaults to false.
42676      */
42677     /**
42678      * @cfg {Boolean} fixed  True if the column width cannot be changed.  Defaults to false.
42679      */
42680     /**
42681      * @cfg {Boolean} resizable  False to disable column resizing. Defaults to true.
42682      */
42683     /**
42684      * @cfg {Boolean} hidden  True to hide the column. Defaults to false.
42685      */
42686     /**
42687      * @cfg {Function} renderer A function used to generate HTML markup for a cell
42688      * given the cell's data value. See {@link #setRenderer}. If not specified, the
42689      * default renderer returns the escaped data value. If an object is returned (bootstrap only)
42690      * then it is treated as a Roo Component object instance, and it is rendered after the initial row is rendered
42691      */
42692        /**
42693      * @cfg {Roo.grid.GridEditor} editor  For grid editors - returns the grid editor 
42694      */
42695     /**
42696      * @cfg {String} align (left|right) Set the CSS text-align property of the column.  Defaults to undefined (left).
42697      */
42698     /**
42699      * @cfg {String} valign (top|bottom|middle) Set the CSS vertical-align property of the column (eg. middle, top, bottom etc).  Defaults to undefined (middle)
42700      */
42701     /**
42702      * @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)
42703      */
42704     /**
42705      * @cfg {String} tooltip mouse over tooltip text
42706      */
42707     /**
42708      * @cfg {Number} xs  can be '0' for hidden at this size (number less than 12)
42709      */
42710     /**
42711      * @cfg {Number} sm can be '0' for hidden at this size (number less than 12)
42712      */
42713     /**
42714      * @cfg {Number} md can be '0' for hidden at this size (number less than 12)
42715      */
42716     /**
42717      * @cfg {Number} lg   can be '0' for hidden at this size (number less than 12)
42718      */
42719         /**
42720      * @cfg {Number} xl   can be '0' for hidden at this size (number less than 12)
42721      */
42722     /**
42723      * Returns the id of the column at the specified index.
42724      * @param {Number} index The column index
42725      * @return {String} the id
42726      */
42727     getColumnId : function(index){
42728         return this.config[index].id;
42729     },
42730
42731     /**
42732      * Returns the column for a specified id.
42733      * @param {String} id The column id
42734      * @return {Object} the column
42735      */
42736     getColumnById : function(id){
42737         return this.lookup[id];
42738     },
42739
42740     
42741     /**
42742      * Returns the column Object for a specified dataIndex.
42743      * @param {String} dataIndex The column dataIndex
42744      * @return {Object|Boolean} the column or false if not found
42745      */
42746     getColumnByDataIndex: function(dataIndex){
42747         var index = this.findColumnIndex(dataIndex);
42748         return index > -1 ? this.config[index] : false;
42749     },
42750     
42751     /**
42752      * Returns the index for a specified column id.
42753      * @param {String} id The column id
42754      * @return {Number} the index, or -1 if not found
42755      */
42756     getIndexById : function(id){
42757         for(var i = 0, len = this.config.length; i < len; i++){
42758             if(this.config[i].id == id){
42759                 return i;
42760             }
42761         }
42762         return -1;
42763     },
42764     
42765     /**
42766      * Returns the index for a specified column dataIndex.
42767      * @param {String} dataIndex The column dataIndex
42768      * @return {Number} the index, or -1 if not found
42769      */
42770     
42771     findColumnIndex : function(dataIndex){
42772         for(var i = 0, len = this.config.length; i < len; i++){
42773             if(this.config[i].dataIndex == dataIndex){
42774                 return i;
42775             }
42776         }
42777         return -1;
42778     },
42779     
42780     
42781     moveColumn : function(oldIndex, newIndex){
42782         var c = this.config[oldIndex];
42783         this.config.splice(oldIndex, 1);
42784         this.config.splice(newIndex, 0, c);
42785         this.dataMap = null;
42786         this.fireEvent("columnmoved", this, oldIndex, newIndex);
42787     },
42788
42789     isLocked : function(colIndex){
42790         return this.config[colIndex].locked === true;
42791     },
42792
42793     setLocked : function(colIndex, value, suppressEvent){
42794         if(this.isLocked(colIndex) == value){
42795             return;
42796         }
42797         this.config[colIndex].locked = value;
42798         if(!suppressEvent){
42799             this.fireEvent("columnlockchange", this, colIndex, value);
42800         }
42801     },
42802
42803     getTotalLockedWidth : function(){
42804         var totalWidth = 0;
42805         for(var i = 0; i < this.config.length; i++){
42806             if(this.isLocked(i) && !this.isHidden(i)){
42807                 this.totalWidth += this.getColumnWidth(i);
42808             }
42809         }
42810         return totalWidth;
42811     },
42812
42813     getLockedCount : function(){
42814         for(var i = 0, len = this.config.length; i < len; i++){
42815             if(!this.isLocked(i)){
42816                 return i;
42817             }
42818         }
42819         
42820         return this.config.length;
42821     },
42822
42823     /**
42824      * Returns the number of columns.
42825      * @return {Number}
42826      */
42827     getColumnCount : function(visibleOnly){
42828         if(visibleOnly === true){
42829             var c = 0;
42830             for(var i = 0, len = this.config.length; i < len; i++){
42831                 if(!this.isHidden(i)){
42832                     c++;
42833                 }
42834             }
42835             return c;
42836         }
42837         return this.config.length;
42838     },
42839
42840     /**
42841      * Returns the column configs that return true by the passed function that is called with (columnConfig, index)
42842      * @param {Function} fn
42843      * @param {Object} scope (optional)
42844      * @return {Array} result
42845      */
42846     getColumnsBy : function(fn, scope){
42847         var r = [];
42848         for(var i = 0, len = this.config.length; i < len; i++){
42849             var c = this.config[i];
42850             if(fn.call(scope||this, c, i) === true){
42851                 r[r.length] = c;
42852             }
42853         }
42854         return r;
42855     },
42856
42857     /**
42858      * Returns true if the specified column is sortable.
42859      * @param {Number} col The column index
42860      * @return {Boolean}
42861      */
42862     isSortable : function(col){
42863         if(typeof this.config[col].sortable == "undefined"){
42864             return this.defaultSortable;
42865         }
42866         return this.config[col].sortable;
42867     },
42868
42869     /**
42870      * Returns the rendering (formatting) function defined for the column.
42871      * @param {Number} col The column index.
42872      * @return {Function} The function used to render the cell. See {@link #setRenderer}.
42873      */
42874     getRenderer : function(col){
42875         if(!this.config[col].renderer){
42876             return Roo.grid.ColumnModel.defaultRenderer;
42877         }
42878         return this.config[col].renderer;
42879     },
42880
42881     /**
42882      * Sets the rendering (formatting) function for a column.
42883      * @param {Number} col The column index
42884      * @param {Function} fn The function to use to process the cell's raw data
42885      * to return HTML markup for the grid view. The render function is called with
42886      * the following parameters:<ul>
42887      * <li>Data value.</li>
42888      * <li>Cell metadata. An object in which you may set the following attributes:<ul>
42889      * <li>css A CSS style string to apply to the table cell.</li>
42890      * <li>attr An HTML attribute definition string to apply to the data container element <i>within</i> the table cell.</li></ul>
42891      * <li>The {@link Roo.data.Record} from which the data was extracted.</li>
42892      * <li>Row index</li>
42893      * <li>Column index</li>
42894      * <li>The {@link Roo.data.Store} object from which the Record was extracted</li></ul>
42895      */
42896     setRenderer : function(col, fn){
42897         this.config[col].renderer = fn;
42898     },
42899
42900     /**
42901      * Returns the width for the specified column.
42902      * @param {Number} col The column index
42903      * @param (optional) {String} gridSize bootstrap width size.
42904      * @return {Number}
42905      */
42906     getColumnWidth : function(col, gridSize)
42907         {
42908                 var cfg = this.config[col];
42909                 
42910                 if (typeof(gridSize) == 'undefined') {
42911                         return cfg.width * 1 || this.defaultWidth;
42912                 }
42913                 if (gridSize === false) { // if we set it..
42914                         return cfg.width || false;
42915                 }
42916                 var sizes = ['xl', 'lg', 'md', 'sm', 'xs'];
42917                 
42918                 for(var i = sizes.indexOf(gridSize); i < sizes.length; i++) {
42919                         if (typeof(cfg[ sizes[i] ] ) == 'undefined') {
42920                                 continue;
42921                         }
42922                         return cfg[ sizes[i] ];
42923                 }
42924                 return 1;
42925                 
42926     },
42927
42928     /**
42929      * Sets the width for a column.
42930      * @param {Number} col The column index
42931      * @param {Number} width The new width
42932      */
42933     setColumnWidth : function(col, width, suppressEvent){
42934         this.config[col].width = width;
42935         this.totalWidth = null;
42936         if(!suppressEvent){
42937              this.fireEvent("widthchange", this, col, width);
42938         }
42939     },
42940
42941     /**
42942      * Returns the total width of all columns.
42943      * @param {Boolean} includeHidden True to include hidden column widths
42944      * @return {Number}
42945      */
42946     getTotalWidth : function(includeHidden){
42947         if(!this.totalWidth){
42948             this.totalWidth = 0;
42949             for(var i = 0, len = this.config.length; i < len; i++){
42950                 if(includeHidden || !this.isHidden(i)){
42951                     this.totalWidth += this.getColumnWidth(i);
42952                 }
42953             }
42954         }
42955         return this.totalWidth;
42956     },
42957
42958     /**
42959      * Returns the header for the specified column.
42960      * @param {Number} col The column index
42961      * @return {String}
42962      */
42963     getColumnHeader : function(col){
42964         return this.config[col].header;
42965     },
42966
42967     /**
42968      * Sets the header for a column.
42969      * @param {Number} col The column index
42970      * @param {String} header The new header
42971      */
42972     setColumnHeader : function(col, header){
42973         this.config[col].header = header;
42974         this.fireEvent("headerchange", this, col, header);
42975     },
42976
42977     /**
42978      * Returns the tooltip for the specified column.
42979      * @param {Number} col The column index
42980      * @return {String}
42981      */
42982     getColumnTooltip : function(col){
42983             return this.config[col].tooltip;
42984     },
42985     /**
42986      * Sets the tooltip for a column.
42987      * @param {Number} col The column index
42988      * @param {String} tooltip The new tooltip
42989      */
42990     setColumnTooltip : function(col, tooltip){
42991             this.config[col].tooltip = tooltip;
42992     },
42993
42994     /**
42995      * Returns the dataIndex for the specified column.
42996      * @param {Number} col The column index
42997      * @return {Number}
42998      */
42999     getDataIndex : function(col){
43000         return this.config[col].dataIndex;
43001     },
43002
43003     /**
43004      * Sets the dataIndex for a column.
43005      * @param {Number} col The column index
43006      * @param {Number} dataIndex The new dataIndex
43007      */
43008     setDataIndex : function(col, dataIndex){
43009         this.config[col].dataIndex = dataIndex;
43010     },
43011
43012     
43013     
43014     /**
43015      * Returns true if the cell is editable.
43016      * @param {Number} colIndex The column index
43017      * @param {Number} rowIndex The row index - this is nto actually used..?
43018      * @return {Boolean}
43019      */
43020     isCellEditable : function(colIndex, rowIndex){
43021         return (this.config[colIndex].editable || (typeof this.config[colIndex].editable == "undefined" && this.config[colIndex].editor)) ? true : false;
43022     },
43023
43024     /**
43025      * Returns the editor defined for the cell/column.
43026      * return false or null to disable editing.
43027      * @param {Number} colIndex The column index
43028      * @param {Number} rowIndex The row index
43029      * @return {Object}
43030      */
43031     getCellEditor : function(colIndex, rowIndex){
43032         return this.config[colIndex].editor;
43033     },
43034
43035     /**
43036      * Sets if a column is editable.
43037      * @param {Number} col The column index
43038      * @param {Boolean} editable True if the column is editable
43039      */
43040     setEditable : function(col, editable){
43041         this.config[col].editable = editable;
43042     },
43043
43044
43045     /**
43046      * Returns true if the column is hidden.
43047      * @param {Number} colIndex The column index
43048      * @return {Boolean}
43049      */
43050     isHidden : function(colIndex){
43051         return this.config[colIndex].hidden;
43052     },
43053
43054
43055     /**
43056      * Returns true if the column width cannot be changed
43057      */
43058     isFixed : function(colIndex){
43059         return this.config[colIndex].fixed;
43060     },
43061
43062     /**
43063      * Returns true if the column can be resized
43064      * @return {Boolean}
43065      */
43066     isResizable : function(colIndex){
43067         return colIndex >= 0 && this.config[colIndex].resizable !== false && this.config[colIndex].fixed !== true;
43068     },
43069     /**
43070      * Sets if a column is hidden.
43071      * @param {Number} colIndex The column index
43072      * @param {Boolean} hidden True if the column is hidden
43073      */
43074     setHidden : function(colIndex, hidden){
43075         this.config[colIndex].hidden = hidden;
43076         this.totalWidth = null;
43077         this.fireEvent("hiddenchange", this, colIndex, hidden);
43078     },
43079
43080     /**
43081      * Sets the editor for a column.
43082      * @param {Number} col The column index
43083      * @param {Object} editor The editor object
43084      */
43085     setEditor : function(col, editor){
43086         this.config[col].editor = editor;
43087     },
43088     /**
43089      * Add a column (experimental...) - defaults to adding to the end..
43090      * @param {Object} config 
43091     */
43092     addColumn : function(c)
43093     {
43094     
43095         var i = this.config.length;
43096         this.config[i] = c;
43097         
43098         if(typeof c.dataIndex == "undefined"){
43099             c.dataIndex = i;
43100         }
43101         if(typeof c.renderer == "string"){
43102             c.renderer = Roo.util.Format[c.renderer];
43103         }
43104         if(typeof c.id == "undefined"){
43105             c.id = Roo.id();
43106         }
43107         if(c.editor && c.editor.xtype){
43108             c.editor  = Roo.factory(c.editor, Roo.grid);
43109         }
43110         if(c.editor && c.editor.isFormField){
43111             c.editor = new Roo.grid.GridEditor(c.editor);
43112         }
43113         this.lookup[c.id] = c;
43114     }
43115     
43116 });
43117
43118 Roo.grid.ColumnModel.defaultRenderer = function(value)
43119 {
43120     if(typeof value == "object") {
43121         return value;
43122     }
43123         if(typeof value == "string" && value.length < 1){
43124             return "&#160;";
43125         }
43126     
43127         return String.format("{0}", value);
43128 };
43129
43130 // Alias for backwards compatibility
43131 Roo.grid.DefaultColumnModel = Roo.grid.ColumnModel;
43132 /*
43133  * Based on:
43134  * Ext JS Library 1.1.1
43135  * Copyright(c) 2006-2007, Ext JS, LLC.
43136  *
43137  * Originally Released Under LGPL - original licence link has changed is not relivant.
43138  *
43139  * Fork - LGPL
43140  * <script type="text/javascript">
43141  */
43142
43143 /**
43144  * @class Roo.grid.AbstractSelectionModel
43145  * @extends Roo.util.Observable
43146  * @abstract
43147  * Abstract base class for grid SelectionModels.  It provides the interface that should be
43148  * implemented by descendant classes.  This class should not be directly instantiated.
43149  * @constructor
43150  */
43151 Roo.grid.AbstractSelectionModel = function(){
43152     this.locked = false;
43153     Roo.grid.AbstractSelectionModel.superclass.constructor.call(this);
43154 };
43155
43156 Roo.extend(Roo.grid.AbstractSelectionModel, Roo.util.Observable,  {
43157     /** @ignore Called by the grid automatically. Do not call directly. */
43158     init : function(grid){
43159         this.grid = grid;
43160         this.initEvents();
43161     },
43162
43163     /**
43164      * Locks the selections.
43165      */
43166     lock : function(){
43167         this.locked = true;
43168     },
43169
43170     /**
43171      * Unlocks the selections.
43172      */
43173     unlock : function(){
43174         this.locked = false;
43175     },
43176
43177     /**
43178      * Returns true if the selections are locked.
43179      * @return {Boolean}
43180      */
43181     isLocked : function(){
43182         return this.locked;
43183     }
43184 });/*
43185  * Based on:
43186  * Ext JS Library 1.1.1
43187  * Copyright(c) 2006-2007, Ext JS, LLC.
43188  *
43189  * Originally Released Under LGPL - original licence link has changed is not relivant.
43190  *
43191  * Fork - LGPL
43192  * <script type="text/javascript">
43193  */
43194 /**
43195  * @extends Roo.grid.AbstractSelectionModel
43196  * @class Roo.grid.RowSelectionModel
43197  * The default SelectionModel used by {@link Roo.grid.Grid}.
43198  * It supports multiple selections and keyboard selection/navigation. 
43199  * @constructor
43200  * @param {Object} config
43201  */
43202 Roo.grid.RowSelectionModel = function(config){
43203     Roo.apply(this, config);
43204     this.selections = new Roo.util.MixedCollection(false, function(o){
43205         return o.id;
43206     });
43207
43208     this.last = false;
43209     this.lastActive = false;
43210
43211     this.addEvents({
43212         /**
43213         * @event selectionchange
43214         * Fires when the selection changes
43215         * @param {SelectionModel} this
43216         */
43217        "selectionchange" : true,
43218        /**
43219         * @event afterselectionchange
43220         * Fires after the selection changes (eg. by key press or clicking)
43221         * @param {SelectionModel} this
43222         */
43223        "afterselectionchange" : true,
43224        /**
43225         * @event beforerowselect
43226         * Fires when a row is selected being selected, return false to cancel.
43227         * @param {SelectionModel} this
43228         * @param {Number} rowIndex The selected index
43229         * @param {Boolean} keepExisting False if other selections will be cleared
43230         */
43231        "beforerowselect" : true,
43232        /**
43233         * @event rowselect
43234         * Fires when a row is selected.
43235         * @param {SelectionModel} this
43236         * @param {Number} rowIndex The selected index
43237         * @param {Roo.data.Record} r The record
43238         */
43239        "rowselect" : true,
43240        /**
43241         * @event rowdeselect
43242         * Fires when a row is deselected.
43243         * @param {SelectionModel} this
43244         * @param {Number} rowIndex The selected index
43245         */
43246         "rowdeselect" : true
43247     });
43248     Roo.grid.RowSelectionModel.superclass.constructor.call(this);
43249     this.locked = false;
43250 };
43251
43252 Roo.extend(Roo.grid.RowSelectionModel, Roo.grid.AbstractSelectionModel,  {
43253     /**
43254      * @cfg {Boolean} singleSelect
43255      * True to allow selection of only one row at a time (defaults to false)
43256      */
43257     singleSelect : false,
43258
43259     // private
43260     initEvents : function(){
43261
43262         if(!this.grid.enableDragDrop && !this.grid.enableDrag){
43263             this.grid.on("mousedown", this.handleMouseDown, this);
43264         }else{ // allow click to work like normal
43265             this.grid.on("rowclick", this.handleDragableRowClick, this);
43266         }
43267         // bootstrap does not have a view..
43268         var view = this.grid.view ? this.grid.view : this.grid;
43269         this.rowNav = new Roo.KeyNav(this.grid.getGridEl(), {
43270             "up" : function(e){
43271                 if(!e.shiftKey){
43272                     this.selectPrevious(e.shiftKey);
43273                 }else if(this.last !== false && this.lastActive !== false){
43274                     var last = this.last;
43275                     this.selectRange(this.last,  this.lastActive-1);
43276                     view.focusRow(this.lastActive);
43277                     if(last !== false){
43278                         this.last = last;
43279                     }
43280                 }else{
43281                     this.selectFirstRow();
43282                 }
43283                 this.fireEvent("afterselectionchange", this);
43284             },
43285             "down" : function(e){
43286                 if(!e.shiftKey){
43287                     this.selectNext(e.shiftKey);
43288                 }else if(this.last !== false && this.lastActive !== false){
43289                     var last = this.last;
43290                     this.selectRange(this.last,  this.lastActive+1);
43291                     view.focusRow(this.lastActive);
43292                     if(last !== false){
43293                         this.last = last;
43294                     }
43295                 }else{
43296                     this.selectFirstRow();
43297                 }
43298                 this.fireEvent("afterselectionchange", this);
43299             },
43300             scope: this
43301         });
43302
43303          
43304         view.on("refresh", this.onRefresh, this);
43305         view.on("rowupdated", this.onRowUpdated, this);
43306         view.on("rowremoved", this.onRemove, this);
43307     },
43308
43309     // private
43310     onRefresh : function(){
43311         var ds = this.grid.ds, i, v = this.grid.view;
43312         var s = this.selections;
43313         s.each(function(r){
43314             if((i = ds.indexOfId(r.id)) != -1){
43315                 v.onRowSelect(i);
43316                 s.add(ds.getAt(i)); // updating the selection relate data
43317             }else{
43318                 s.remove(r);
43319             }
43320         });
43321     },
43322
43323     // private
43324     onRemove : function(v, index, r){
43325         this.selections.remove(r);
43326     },
43327
43328     // private
43329     onRowUpdated : function(v, index, r){
43330         if(this.isSelected(r)){
43331             v.onRowSelect(index);
43332         }
43333     },
43334
43335     /**
43336      * Select records.
43337      * @param {Array} records The records to select
43338      * @param {Boolean} keepExisting (optional) True to keep existing selections
43339      */
43340     selectRecords : function(records, keepExisting){
43341         if(!keepExisting){
43342             this.clearSelections();
43343         }
43344         var ds = this.grid.ds;
43345         for(var i = 0, len = records.length; i < len; i++){
43346             this.selectRow(ds.indexOf(records[i]), true);
43347         }
43348     },
43349
43350     /**
43351      * Gets the number of selected rows.
43352      * @return {Number}
43353      */
43354     getCount : function(){
43355         return this.selections.length;
43356     },
43357
43358     /**
43359      * Selects the first row in the grid.
43360      */
43361     selectFirstRow : function(){
43362         this.selectRow(0);
43363     },
43364
43365     /**
43366      * Select the last row.
43367      * @param {Boolean} keepExisting (optional) True to keep existing selections
43368      */
43369     selectLastRow : function(keepExisting){
43370         this.selectRow(this.grid.ds.getCount() - 1, keepExisting);
43371     },
43372
43373     /**
43374      * Selects the row immediately following the last selected row.
43375      * @param {Boolean} keepExisting (optional) True to keep existing selections
43376      */
43377     selectNext : function(keepExisting){
43378         if(this.last !== false && (this.last+1) < this.grid.ds.getCount()){
43379             this.selectRow(this.last+1, keepExisting);
43380             var view = this.grid.view ? this.grid.view : this.grid;
43381             view.focusRow(this.last);
43382         }
43383     },
43384
43385     /**
43386      * Selects the row that precedes the last selected row.
43387      * @param {Boolean} keepExisting (optional) True to keep existing selections
43388      */
43389     selectPrevious : function(keepExisting){
43390         if(this.last){
43391             this.selectRow(this.last-1, keepExisting);
43392             var view = this.grid.view ? this.grid.view : this.grid;
43393             view.focusRow(this.last);
43394         }
43395     },
43396
43397     /**
43398      * Returns the selected records
43399      * @return {Array} Array of selected records
43400      */
43401     getSelections : function(){
43402         return [].concat(this.selections.items);
43403     },
43404
43405     /**
43406      * Returns the first selected record.
43407      * @return {Record}
43408      */
43409     getSelected : function(){
43410         return this.selections.itemAt(0);
43411     },
43412
43413
43414     /**
43415      * Clears all selections.
43416      */
43417     clearSelections : function(fast){
43418         if(this.locked) {
43419             return;
43420         }
43421         if(fast !== true){
43422             var ds = this.grid.ds;
43423             var s = this.selections;
43424             s.each(function(r){
43425                 this.deselectRow(ds.indexOfId(r.id));
43426             }, this);
43427             s.clear();
43428         }else{
43429             this.selections.clear();
43430         }
43431         this.last = false;
43432     },
43433
43434
43435     /**
43436      * Selects all rows.
43437      */
43438     selectAll : function(){
43439         if(this.locked) {
43440             return;
43441         }
43442         this.selections.clear();
43443         for(var i = 0, len = this.grid.ds.getCount(); i < len; i++){
43444             this.selectRow(i, true);
43445         }
43446     },
43447
43448     /**
43449      * Returns True if there is a selection.
43450      * @return {Boolean}
43451      */
43452     hasSelection : function(){
43453         return this.selections.length > 0;
43454     },
43455
43456     /**
43457      * Returns True if the specified row is selected.
43458      * @param {Number/Record} record The record or index of the record to check
43459      * @return {Boolean}
43460      */
43461     isSelected : function(index){
43462         var r = typeof index == "number" ? this.grid.ds.getAt(index) : index;
43463         return (r && this.selections.key(r.id) ? true : false);
43464     },
43465
43466     /**
43467      * Returns True if the specified record id is selected.
43468      * @param {String} id The id of record to check
43469      * @return {Boolean}
43470      */
43471     isIdSelected : function(id){
43472         return (this.selections.key(id) ? true : false);
43473     },
43474
43475     // private
43476     handleMouseDown : function(e, t)
43477     {
43478         var view = this.grid.view ? this.grid.view : this.grid;
43479         var rowIndex;
43480         if(this.isLocked() || (rowIndex = view.findRowIndex(t)) === false){
43481             return;
43482         };
43483         if(e.shiftKey && this.last !== false){
43484             var last = this.last;
43485             this.selectRange(last, rowIndex, e.ctrlKey);
43486             this.last = last; // reset the last
43487             view.focusRow(rowIndex);
43488         }else{
43489             var isSelected = this.isSelected(rowIndex);
43490             if(e.button !== 0 && isSelected){
43491                 view.focusRow(rowIndex);
43492             }else if(e.ctrlKey && isSelected){
43493                 this.deselectRow(rowIndex);
43494             }else if(!isSelected){
43495                 this.selectRow(rowIndex, e.button === 0 && (e.ctrlKey || e.shiftKey));
43496                 view.focusRow(rowIndex);
43497             }
43498         }
43499         this.fireEvent("afterselectionchange", this);
43500     },
43501     // private
43502     handleDragableRowClick :  function(grid, rowIndex, e) 
43503     {
43504         if(e.button === 0 && !e.shiftKey && !e.ctrlKey) {
43505             this.selectRow(rowIndex, false);
43506             var view = this.grid.view ? this.grid.view : this.grid;
43507             view.focusRow(rowIndex);
43508              this.fireEvent("afterselectionchange", this);
43509         }
43510     },
43511     
43512     /**
43513      * Selects multiple rows.
43514      * @param {Array} rows Array of the indexes of the row to select
43515      * @param {Boolean} keepExisting (optional) True to keep existing selections
43516      */
43517     selectRows : function(rows, keepExisting){
43518         if(!keepExisting){
43519             this.clearSelections();
43520         }
43521         for(var i = 0, len = rows.length; i < len; i++){
43522             this.selectRow(rows[i], true);
43523         }
43524     },
43525
43526     /**
43527      * Selects a range of rows. All rows in between startRow and endRow are also selected.
43528      * @param {Number} startRow The index of the first row in the range
43529      * @param {Number} endRow The index of the last row in the range
43530      * @param {Boolean} keepExisting (optional) True to retain existing selections
43531      */
43532     selectRange : function(startRow, endRow, keepExisting){
43533         if(this.locked) {
43534             return;
43535         }
43536         if(!keepExisting){
43537             this.clearSelections();
43538         }
43539         if(startRow <= endRow){
43540             for(var i = startRow; i <= endRow; i++){
43541                 this.selectRow(i, true);
43542             }
43543         }else{
43544             for(var i = startRow; i >= endRow; i--){
43545                 this.selectRow(i, true);
43546             }
43547         }
43548     },
43549
43550     /**
43551      * Deselects a range of rows. All rows in between startRow and endRow are also deselected.
43552      * @param {Number} startRow The index of the first row in the range
43553      * @param {Number} endRow The index of the last row in the range
43554      */
43555     deselectRange : function(startRow, endRow, preventViewNotify){
43556         if(this.locked) {
43557             return;
43558         }
43559         for(var i = startRow; i <= endRow; i++){
43560             this.deselectRow(i, preventViewNotify);
43561         }
43562     },
43563
43564     /**
43565      * Selects a row.
43566      * @param {Number} row The index of the row to select
43567      * @param {Boolean} keepExisting (optional) True to keep existing selections
43568      */
43569     selectRow : function(index, keepExisting, preventViewNotify){
43570         if(this.locked || (index < 0 || index >= this.grid.ds.getCount())) {
43571             return;
43572         }
43573         if(this.fireEvent("beforerowselect", this, index, keepExisting) !== false){
43574             if(!keepExisting || this.singleSelect){
43575                 this.clearSelections();
43576             }
43577             var r = this.grid.ds.getAt(index);
43578             this.selections.add(r);
43579             this.last = this.lastActive = index;
43580             if(!preventViewNotify){
43581                 var view = this.grid.view ? this.grid.view : this.grid;
43582                 view.onRowSelect(index);
43583             }
43584             this.fireEvent("rowselect", this, index, r);
43585             this.fireEvent("selectionchange", this);
43586         }
43587     },
43588
43589     /**
43590      * Deselects a row.
43591      * @param {Number} row The index of the row to deselect
43592      */
43593     deselectRow : function(index, preventViewNotify){
43594         if(this.locked) {
43595             return;
43596         }
43597         if(this.last == index){
43598             this.last = false;
43599         }
43600         if(this.lastActive == index){
43601             this.lastActive = false;
43602         }
43603         var r = this.grid.ds.getAt(index);
43604         this.selections.remove(r);
43605         if(!preventViewNotify){
43606             var view = this.grid.view ? this.grid.view : this.grid;
43607             view.onRowDeselect(index);
43608         }
43609         this.fireEvent("rowdeselect", this, index);
43610         this.fireEvent("selectionchange", this);
43611     },
43612
43613     // private
43614     restoreLast : function(){
43615         if(this._last){
43616             this.last = this._last;
43617         }
43618     },
43619
43620     // private
43621     acceptsNav : function(row, col, cm){
43622         return !cm.isHidden(col) && cm.isCellEditable(col, row);
43623     },
43624
43625     // private
43626     onEditorKey : function(field, e){
43627         var k = e.getKey(), newCell, g = this.grid, ed = g.activeEditor;
43628         if(k == e.TAB){
43629             e.stopEvent();
43630             ed.completeEdit();
43631             if(e.shiftKey){
43632                 newCell = g.walkCells(ed.row, ed.col-1, -1, this.acceptsNav, this);
43633             }else{
43634                 newCell = g.walkCells(ed.row, ed.col+1, 1, this.acceptsNav, this);
43635             }
43636         }else if(k == e.ENTER && !e.ctrlKey){
43637             e.stopEvent();
43638             ed.completeEdit();
43639             if(e.shiftKey){
43640                 newCell = g.walkCells(ed.row-1, ed.col, -1, this.acceptsNav, this);
43641             }else{
43642                 newCell = g.walkCells(ed.row+1, ed.col, 1, this.acceptsNav, this);
43643             }
43644         }else if(k == e.ESC){
43645             ed.cancelEdit();
43646         }
43647         if(newCell){
43648             g.startEditing(newCell[0], newCell[1]);
43649         }
43650     }
43651 });/*
43652  * Based on:
43653  * Ext JS Library 1.1.1
43654  * Copyright(c) 2006-2007, Ext JS, LLC.
43655  *
43656  * Originally Released Under LGPL - original licence link has changed is not relivant.
43657  *
43658  * Fork - LGPL
43659  * <script type="text/javascript">
43660  */
43661 /**
43662  * @class Roo.grid.CellSelectionModel
43663  * @extends Roo.grid.AbstractSelectionModel
43664  * This class provides the basic implementation for cell selection in a grid.
43665  * @constructor
43666  * @param {Object} config The object containing the configuration of this model.
43667  * @cfg {Boolean} enter_is_tab Enter behaves the same as tab. (eg. goes to next cell) default: false
43668  */
43669 Roo.grid.CellSelectionModel = function(config){
43670     Roo.apply(this, config);
43671
43672     this.selection = null;
43673
43674     this.addEvents({
43675         /**
43676              * @event beforerowselect
43677              * Fires before a cell is selected.
43678              * @param {SelectionModel} this
43679              * @param {Number} rowIndex The selected row index
43680              * @param {Number} colIndex The selected cell index
43681              */
43682             "beforecellselect" : true,
43683         /**
43684              * @event cellselect
43685              * Fires when a cell is selected.
43686              * @param {SelectionModel} this
43687              * @param {Number} rowIndex The selected row index
43688              * @param {Number} colIndex The selected cell index
43689              */
43690             "cellselect" : true,
43691         /**
43692              * @event selectionchange
43693              * Fires when the active selection changes.
43694              * @param {SelectionModel} this
43695              * @param {Object} selection null for no selection or an object (o) with two properties
43696                 <ul>
43697                 <li>o.record: the record object for the row the selection is in</li>
43698                 <li>o.cell: An array of [rowIndex, columnIndex]</li>
43699                 </ul>
43700              */
43701             "selectionchange" : true,
43702         /**
43703              * @event tabend
43704              * Fires when the tab (or enter) was pressed on the last editable cell
43705              * You can use this to trigger add new row.
43706              * @param {SelectionModel} this
43707              */
43708             "tabend" : true,
43709          /**
43710              * @event beforeeditnext
43711              * Fires before the next editable sell is made active
43712              * You can use this to skip to another cell or fire the tabend
43713              *    if you set cell to false
43714              * @param {Object} eventdata object : { cell : [ row, col ] } 
43715              */
43716             "beforeeditnext" : true
43717     });
43718     Roo.grid.CellSelectionModel.superclass.constructor.call(this);
43719 };
43720
43721 Roo.extend(Roo.grid.CellSelectionModel, Roo.grid.AbstractSelectionModel,  {
43722     
43723     enter_is_tab: false,
43724
43725     /** @ignore */
43726     initEvents : function(){
43727         this.grid.on("mousedown", this.handleMouseDown, this);
43728         this.grid.getGridEl().on(Roo.isIE ? "keydown" : "keypress", this.handleKeyDown, this);
43729         var view = this.grid.view;
43730         view.on("refresh", this.onViewChange, this);
43731         view.on("rowupdated", this.onRowUpdated, this);
43732         view.on("beforerowremoved", this.clearSelections, this);
43733         view.on("beforerowsinserted", this.clearSelections, this);
43734         if(this.grid.isEditor){
43735             this.grid.on("beforeedit", this.beforeEdit,  this);
43736         }
43737     },
43738
43739         //private
43740     beforeEdit : function(e){
43741         this.select(e.row, e.column, false, true, e.record);
43742     },
43743
43744         //private
43745     onRowUpdated : function(v, index, r){
43746         if(this.selection && this.selection.record == r){
43747             v.onCellSelect(index, this.selection.cell[1]);
43748         }
43749     },
43750
43751         //private
43752     onViewChange : function(){
43753         this.clearSelections(true);
43754     },
43755
43756         /**
43757          * Returns the currently selected cell,.
43758          * @return {Array} The selected cell (row, column) or null if none selected.
43759          */
43760     getSelectedCell : function(){
43761         return this.selection ? this.selection.cell : null;
43762     },
43763
43764     /**
43765      * Clears all selections.
43766      * @param {Boolean} true to prevent the gridview from being notified about the change.
43767      */
43768     clearSelections : function(preventNotify){
43769         var s = this.selection;
43770         if(s){
43771             if(preventNotify !== true){
43772                 this.grid.view.onCellDeselect(s.cell[0], s.cell[1]);
43773             }
43774             this.selection = null;
43775             this.fireEvent("selectionchange", this, null);
43776         }
43777     },
43778
43779     /**
43780      * Returns true if there is a selection.
43781      * @return {Boolean}
43782      */
43783     hasSelection : function(){
43784         return this.selection ? true : false;
43785     },
43786
43787     /** @ignore */
43788     handleMouseDown : function(e, t){
43789         var v = this.grid.getView();
43790         if(this.isLocked()){
43791             return;
43792         };
43793         var row = v.findRowIndex(t);
43794         var cell = v.findCellIndex(t);
43795         if(row !== false && cell !== false){
43796             this.select(row, cell);
43797         }
43798     },
43799
43800     /**
43801      * Selects a cell.
43802      * @param {Number} rowIndex
43803      * @param {Number} collIndex
43804      */
43805     select : function(rowIndex, colIndex, preventViewNotify, preventFocus, /*internal*/ r){
43806         if(this.fireEvent("beforecellselect", this, rowIndex, colIndex) !== false){
43807             this.clearSelections();
43808             r = r || this.grid.dataSource.getAt(rowIndex);
43809             this.selection = {
43810                 record : r,
43811                 cell : [rowIndex, colIndex]
43812             };
43813             if(!preventViewNotify){
43814                 var v = this.grid.getView();
43815                 v.onCellSelect(rowIndex, colIndex);
43816                 if(preventFocus !== true){
43817                     v.focusCell(rowIndex, colIndex);
43818                 }
43819             }
43820             this.fireEvent("cellselect", this, rowIndex, colIndex);
43821             this.fireEvent("selectionchange", this, this.selection);
43822         }
43823     },
43824
43825         //private
43826     isSelectable : function(rowIndex, colIndex, cm){
43827         return !cm.isHidden(colIndex);
43828     },
43829
43830     /** @ignore */
43831     handleKeyDown : function(e){
43832         //Roo.log('Cell Sel Model handleKeyDown');
43833         if(!e.isNavKeyPress()){
43834             return;
43835         }
43836         var g = this.grid, s = this.selection;
43837         if(!s){
43838             e.stopEvent();
43839             var cell = g.walkCells(0, 0, 1, this.isSelectable,  this);
43840             if(cell){
43841                 this.select(cell[0], cell[1]);
43842             }
43843             return;
43844         }
43845         var sm = this;
43846         var walk = function(row, col, step){
43847             return g.walkCells(row, col, step, sm.isSelectable,  sm);
43848         };
43849         var k = e.getKey(), r = s.cell[0], c = s.cell[1];
43850         var newCell;
43851
43852       
43853
43854         switch(k){
43855             case e.TAB:
43856                 // handled by onEditorKey
43857                 if (g.isEditor && g.editing) {
43858                     return;
43859                 }
43860                 if(e.shiftKey) {
43861                     newCell = walk(r, c-1, -1);
43862                 } else {
43863                     newCell = walk(r, c+1, 1);
43864                 }
43865                 break;
43866             
43867             case e.DOWN:
43868                newCell = walk(r+1, c, 1);
43869                 break;
43870             
43871             case e.UP:
43872                 newCell = walk(r-1, c, -1);
43873                 break;
43874             
43875             case e.RIGHT:
43876                 newCell = walk(r, c+1, 1);
43877                 break;
43878             
43879             case e.LEFT:
43880                 newCell = walk(r, c-1, -1);
43881                 break;
43882             
43883             case e.ENTER:
43884                 
43885                 if(g.isEditor && !g.editing){
43886                    g.startEditing(r, c);
43887                    e.stopEvent();
43888                    return;
43889                 }
43890                 
43891                 
43892              break;
43893         };
43894         if(newCell){
43895             this.select(newCell[0], newCell[1]);
43896             e.stopEvent();
43897             
43898         }
43899     },
43900
43901     acceptsNav : function(row, col, cm){
43902         return !cm.isHidden(col) && cm.isCellEditable(col, row);
43903     },
43904     /**
43905      * Selects a cell.
43906      * @param {Number} field (not used) - as it's normally used as a listener
43907      * @param {Number} e - event - fake it by using
43908      *
43909      * var e = Roo.EventObjectImpl.prototype;
43910      * e.keyCode = e.TAB
43911      *
43912      * 
43913      */
43914     onEditorKey : function(field, e){
43915         
43916         var k = e.getKey(),
43917             newCell,
43918             g = this.grid,
43919             ed = g.activeEditor,
43920             forward = false;
43921         ///Roo.log('onEditorKey' + k);
43922         
43923         
43924         if (this.enter_is_tab && k == e.ENTER) {
43925             k = e.TAB;
43926         }
43927         
43928         if(k == e.TAB){
43929             if(e.shiftKey){
43930                 newCell = g.walkCells(ed.row, ed.col-1, -1, this.acceptsNav, this);
43931             }else{
43932                 newCell = g.walkCells(ed.row, ed.col+1, 1, this.acceptsNav, this);
43933                 forward = true;
43934             }
43935             
43936             e.stopEvent();
43937             
43938         } else if(k == e.ENTER &&  !e.ctrlKey){
43939             ed.completeEdit();
43940             e.stopEvent();
43941             newCell = g.walkCells(ed.row, ed.col+1, 1, this.acceptsNav, this);
43942         
43943                 } else if(k == e.ESC){
43944             ed.cancelEdit();
43945         }
43946                 
43947         if (newCell) {
43948             var ecall = { cell : newCell, forward : forward };
43949             this.fireEvent('beforeeditnext', ecall );
43950             newCell = ecall.cell;
43951                         forward = ecall.forward;
43952         }
43953                 
43954         if(newCell){
43955             //Roo.log('next cell after edit');
43956             g.startEditing.defer(100, g, [newCell[0], newCell[1]]);
43957         } else if (forward) {
43958             // tabbed past last
43959             this.fireEvent.defer(100, this, ['tabend',this]);
43960         }
43961     }
43962 });/*
43963  * Based on:
43964  * Ext JS Library 1.1.1
43965  * Copyright(c) 2006-2007, Ext JS, LLC.
43966  *
43967  * Originally Released Under LGPL - original licence link has changed is not relivant.
43968  *
43969  * Fork - LGPL
43970  * <script type="text/javascript">
43971  */
43972  
43973 /**
43974  * @class Roo.grid.EditorGrid
43975  * @extends Roo.grid.Grid
43976  * Class for creating and editable grid.
43977  * @param {String/HTMLElement/Roo.Element} container The element into which this grid will be rendered - 
43978  * The container MUST have some type of size defined for the grid to fill. The container will be 
43979  * automatically set to position relative if it isn't already.
43980  * @param {Object} dataSource The data model to bind to
43981  * @param {Object} colModel The column model with info about this grid's columns
43982  */
43983 Roo.grid.EditorGrid = function(container, config){
43984     Roo.grid.EditorGrid.superclass.constructor.call(this, container, config);
43985     this.getGridEl().addClass("xedit-grid");
43986
43987     if(!this.selModel){
43988         this.selModel = new Roo.grid.CellSelectionModel();
43989     }
43990
43991     this.activeEditor = null;
43992
43993         this.addEvents({
43994             /**
43995              * @event beforeedit
43996              * Fires before cell editing is triggered. The edit event object has the following properties <br />
43997              * <ul style="padding:5px;padding-left:16px;">
43998              * <li>grid - This grid</li>
43999              * <li>record - The record being edited</li>
44000              * <li>field - The field name being edited</li>
44001              * <li>value - The value for the field being edited.</li>
44002              * <li>row - The grid row index</li>
44003              * <li>column - The grid column index</li>
44004              * <li>cancel - Set this to true to cancel the edit or return false from your handler.</li>
44005              * </ul>
44006              * @param {Object} e An edit event (see above for description)
44007              */
44008             "beforeedit" : true,
44009             /**
44010              * @event afteredit
44011              * Fires after a cell is edited. <br />
44012              * <ul style="padding:5px;padding-left:16px;">
44013              * <li>grid - This grid</li>
44014              * <li>record - The record being edited</li>
44015              * <li>field - The field name being edited</li>
44016              * <li>value - The value being set</li>
44017              * <li>originalValue - The original value for the field, before the edit.</li>
44018              * <li>row - The grid row index</li>
44019              * <li>column - The grid column index</li>
44020              * </ul>
44021              * @param {Object} e An edit event (see above for description)
44022              */
44023             "afteredit" : true,
44024             /**
44025              * @event validateedit
44026              * Fires after a cell is edited, but before the value is set in the record. 
44027          * You can use this to modify the value being set in the field, Return false
44028              * to cancel the change. The edit event object has the following properties <br />
44029              * <ul style="padding:5px;padding-left:16px;">
44030          * <li>editor - This editor</li>
44031              * <li>grid - This grid</li>
44032              * <li>record - The record being edited</li>
44033              * <li>field - The field name being edited</li>
44034              * <li>value - The value being set</li>
44035              * <li>originalValue - The original value for the field, before the edit.</li>
44036              * <li>row - The grid row index</li>
44037              * <li>column - The grid column index</li>
44038              * <li>cancel - Set this to true to cancel the edit or return false from your handler.</li>
44039              * </ul>
44040              * @param {Object} e An edit event (see above for description)
44041              */
44042             "validateedit" : true
44043         });
44044     this.on("bodyscroll", this.stopEditing,  this);
44045     this.on(this.clicksToEdit == 1 ? "cellclick" : "celldblclick", this.onCellDblClick,  this);
44046 };
44047
44048 Roo.extend(Roo.grid.EditorGrid, Roo.grid.Grid, {
44049     /**
44050      * @cfg {Number} clicksToEdit
44051      * The number of clicks on a cell required to display the cell's editor (defaults to 2)
44052      */
44053     clicksToEdit: 2,
44054
44055     // private
44056     isEditor : true,
44057     // private
44058     trackMouseOver: false, // causes very odd FF errors
44059
44060     onCellDblClick : function(g, row, col){
44061         this.startEditing(row, col);
44062     },
44063
44064     onEditComplete : function(ed, value, startValue){
44065         this.editing = false;
44066         this.activeEditor = null;
44067         ed.un("specialkey", this.selModel.onEditorKey, this.selModel);
44068         var r = ed.record;
44069         var field = this.colModel.getDataIndex(ed.col);
44070         var e = {
44071             grid: this,
44072             record: r,
44073             field: field,
44074             originalValue: startValue,
44075             value: value,
44076             row: ed.row,
44077             column: ed.col,
44078             cancel:false,
44079             editor: ed
44080         };
44081         var cell = Roo.get(this.view.getCell(ed.row,ed.col));
44082         cell.show();
44083           
44084         if(String(value) !== String(startValue)){
44085             
44086             if(this.fireEvent("validateedit", e) !== false && !e.cancel){
44087                 r.set(field, e.value);
44088                 // if we are dealing with a combo box..
44089                 // then we also set the 'name' colum to be the displayField
44090                 if (ed.field.displayField && ed.field.name) {
44091                     r.set(ed.field.name, ed.field.el.dom.value);
44092                 }
44093                 
44094                 delete e.cancel; //?? why!!!
44095                 this.fireEvent("afteredit", e);
44096             }
44097         } else {
44098             this.fireEvent("afteredit", e); // always fire it!
44099         }
44100         this.view.focusCell(ed.row, ed.col);
44101     },
44102
44103     /**
44104      * Starts editing the specified for the specified row/column
44105      * @param {Number} rowIndex
44106      * @param {Number} colIndex
44107      */
44108     startEditing : function(row, col){
44109         this.stopEditing();
44110         if(this.colModel.isCellEditable(col, row)){
44111             this.view.ensureVisible(row, col, true);
44112           
44113             var r = this.dataSource.getAt(row);
44114             var field = this.colModel.getDataIndex(col);
44115             var cell = Roo.get(this.view.getCell(row,col));
44116             var e = {
44117                 grid: this,
44118                 record: r,
44119                 field: field,
44120                 value: r.data[field],
44121                 row: row,
44122                 column: col,
44123                 cancel:false 
44124             };
44125             if(this.fireEvent("beforeedit", e) !== false && !e.cancel){
44126                 this.editing = true;
44127                 var ed = this.colModel.getCellEditor(col, row);
44128                 
44129                 if (!ed) {
44130                     return;
44131                 }
44132                 if(!ed.rendered){
44133                     ed.render(ed.parentEl || document.body);
44134                 }
44135                 ed.field.reset();
44136                
44137                 cell.hide();
44138                 
44139                 (function(){ // complex but required for focus issues in safari, ie and opera
44140                     ed.row = row;
44141                     ed.col = col;
44142                     ed.record = r;
44143                     ed.on("complete",   this.onEditComplete,        this,       {single: true});
44144                     ed.on("specialkey", this.selModel.onEditorKey,  this.selModel);
44145                     this.activeEditor = ed;
44146                     var v = r.data[field];
44147                     ed.startEdit(this.view.getCell(row, col), v);
44148                     // combo's with 'displayField and name set
44149                     if (ed.field.displayField && ed.field.name) {
44150                         ed.field.el.dom.value = r.data[ed.field.name];
44151                     }
44152                     
44153                     
44154                 }).defer(50, this);
44155             }
44156         }
44157     },
44158         
44159     /**
44160      * Stops any active editing
44161      */
44162     stopEditing : function(){
44163         if(this.activeEditor){
44164             this.activeEditor.completeEdit();
44165         }
44166         this.activeEditor = null;
44167     },
44168         
44169          /**
44170      * Called to get grid's drag proxy text, by default returns this.ddText.
44171      * @return {String}
44172      */
44173     getDragDropText : function(){
44174         var count = this.selModel.getSelectedCell() ? 1 : 0;
44175         return String.format(this.ddText, count, count == 1 ? '' : 's');
44176     }
44177         
44178 });/*
44179  * Based on:
44180  * Ext JS Library 1.1.1
44181  * Copyright(c) 2006-2007, Ext JS, LLC.
44182  *
44183  * Originally Released Under LGPL - original licence link has changed is not relivant.
44184  *
44185  * Fork - LGPL
44186  * <script type="text/javascript">
44187  */
44188
44189 // private - not really -- you end up using it !
44190 // This is a support class used internally by the Grid components
44191
44192 /**
44193  * @class Roo.grid.GridEditor
44194  * @extends Roo.Editor
44195  * Class for creating and editable grid elements.
44196  * @param {Object} config any settings (must include field)
44197  */
44198 Roo.grid.GridEditor = function(field, config){
44199     if (!config && field.field) {
44200         config = field;
44201         field = Roo.factory(config.field, Roo.form);
44202     }
44203     Roo.grid.GridEditor.superclass.constructor.call(this, field, config);
44204     field.monitorTab = false;
44205 };
44206
44207 Roo.extend(Roo.grid.GridEditor, Roo.Editor, {
44208     
44209     /**
44210      * @cfg {Roo.form.Field} field Field to wrap (or xtyped)
44211      */
44212     
44213     alignment: "tl-tl",
44214     autoSize: "width",
44215     hideEl : false,
44216     cls: "x-small-editor x-grid-editor",
44217     shim:false,
44218     shadow:"frame"
44219 });/*
44220  * Based on:
44221  * Ext JS Library 1.1.1
44222  * Copyright(c) 2006-2007, Ext JS, LLC.
44223  *
44224  * Originally Released Under LGPL - original licence link has changed is not relivant.
44225  *
44226  * Fork - LGPL
44227  * <script type="text/javascript">
44228  */
44229   
44230
44231   
44232 Roo.grid.PropertyRecord = Roo.data.Record.create([
44233     {name:'name',type:'string'},  'value'
44234 ]);
44235
44236
44237 Roo.grid.PropertyStore = function(grid, source){
44238     this.grid = grid;
44239     this.store = new Roo.data.Store({
44240         recordType : Roo.grid.PropertyRecord
44241     });
44242     this.store.on('update', this.onUpdate,  this);
44243     if(source){
44244         this.setSource(source);
44245     }
44246     Roo.grid.PropertyStore.superclass.constructor.call(this);
44247 };
44248
44249
44250
44251 Roo.extend(Roo.grid.PropertyStore, Roo.util.Observable, {
44252     setSource : function(o){
44253         this.source = o;
44254         this.store.removeAll();
44255         var data = [];
44256         for(var k in o){
44257             if(this.isEditableValue(o[k])){
44258                 data.push(new Roo.grid.PropertyRecord({name: k, value: o[k]}, k));
44259             }
44260         }
44261         this.store.loadRecords({records: data}, {}, true);
44262     },
44263
44264     onUpdate : function(ds, record, type){
44265         if(type == Roo.data.Record.EDIT){
44266             var v = record.data['value'];
44267             var oldValue = record.modified['value'];
44268             if(this.grid.fireEvent('beforepropertychange', this.source, record.id, v, oldValue) !== false){
44269                 this.source[record.id] = v;
44270                 record.commit();
44271                 this.grid.fireEvent('propertychange', this.source, record.id, v, oldValue);
44272             }else{
44273                 record.reject();
44274             }
44275         }
44276     },
44277
44278     getProperty : function(row){
44279        return this.store.getAt(row);
44280     },
44281
44282     isEditableValue: function(val){
44283         if(val && val instanceof Date){
44284             return true;
44285         }else if(typeof val == 'object' || typeof val == 'function'){
44286             return false;
44287         }
44288         return true;
44289     },
44290
44291     setValue : function(prop, value){
44292         this.source[prop] = value;
44293         this.store.getById(prop).set('value', value);
44294     },
44295
44296     getSource : function(){
44297         return this.source;
44298     }
44299 });
44300
44301 Roo.grid.PropertyColumnModel = function(grid, store){
44302     this.grid = grid;
44303     var g = Roo.grid;
44304     g.PropertyColumnModel.superclass.constructor.call(this, [
44305         {header: this.nameText, sortable: true, dataIndex:'name', id: 'name'},
44306         {header: this.valueText, resizable:false, dataIndex: 'value', id: 'value'}
44307     ]);
44308     this.store = store;
44309     this.bselect = Roo.DomHelper.append(document.body, {
44310         tag: 'select', style:'display:none', cls: 'x-grid-editor', children: [
44311             {tag: 'option', value: 'true', html: 'true'},
44312             {tag: 'option', value: 'false', html: 'false'}
44313         ]
44314     });
44315     Roo.id(this.bselect);
44316     var f = Roo.form;
44317     this.editors = {
44318         'date' : new g.GridEditor(new f.DateField({selectOnFocus:true})),
44319         'string' : new g.GridEditor(new f.TextField({selectOnFocus:true})),
44320         'number' : new g.GridEditor(new f.NumberField({selectOnFocus:true, style:'text-align:left;'})),
44321         'int' : new g.GridEditor(new f.NumberField({selectOnFocus:true, allowDecimals:false, style:'text-align:left;'})),
44322         'boolean' : new g.GridEditor(new f.Field({el:this.bselect,selectOnFocus:true}))
44323     };
44324     this.renderCellDelegate = this.renderCell.createDelegate(this);
44325     this.renderPropDelegate = this.renderProp.createDelegate(this);
44326 };
44327
44328 Roo.extend(Roo.grid.PropertyColumnModel, Roo.grid.ColumnModel, {
44329     
44330     
44331     nameText : 'Name',
44332     valueText : 'Value',
44333     
44334     dateFormat : 'm/j/Y',
44335     
44336     
44337     renderDate : function(dateVal){
44338         return dateVal.dateFormat(this.dateFormat);
44339     },
44340
44341     renderBool : function(bVal){
44342         return bVal ? 'true' : 'false';
44343     },
44344
44345     isCellEditable : function(colIndex, rowIndex){
44346         return colIndex == 1;
44347     },
44348
44349     getRenderer : function(col){
44350         return col == 1 ?
44351             this.renderCellDelegate : this.renderPropDelegate;
44352     },
44353
44354     renderProp : function(v){
44355         return this.getPropertyName(v);
44356     },
44357
44358     renderCell : function(val){
44359         var rv = val;
44360         if(val instanceof Date){
44361             rv = this.renderDate(val);
44362         }else if(typeof val == 'boolean'){
44363             rv = this.renderBool(val);
44364         }
44365         return Roo.util.Format.htmlEncode(rv);
44366     },
44367
44368     getPropertyName : function(name){
44369         var pn = this.grid.propertyNames;
44370         return pn && pn[name] ? pn[name] : name;
44371     },
44372
44373     getCellEditor : function(colIndex, rowIndex){
44374         var p = this.store.getProperty(rowIndex);
44375         var n = p.data['name'], val = p.data['value'];
44376         
44377         if(typeof(this.grid.customEditors[n]) == 'string'){
44378             return this.editors[this.grid.customEditors[n]];
44379         }
44380         if(typeof(this.grid.customEditors[n]) != 'undefined'){
44381             return this.grid.customEditors[n];
44382         }
44383         if(val instanceof Date){
44384             return this.editors['date'];
44385         }else if(typeof val == 'number'){
44386             return this.editors['number'];
44387         }else if(typeof val == 'boolean'){
44388             return this.editors['boolean'];
44389         }else{
44390             return this.editors['string'];
44391         }
44392     }
44393 });
44394
44395 /**
44396  * @class Roo.grid.PropertyGrid
44397  * @extends Roo.grid.EditorGrid
44398  * This class represents the  interface of a component based property grid control.
44399  * <br><br>Usage:<pre><code>
44400  var grid = new Roo.grid.PropertyGrid("my-container-id", {
44401       
44402  });
44403  // set any options
44404  grid.render();
44405  * </code></pre>
44406   
44407  * @constructor
44408  * @param {String/HTMLElement/Roo.Element} container The element into which this grid will be rendered -
44409  * The container MUST have some type of size defined for the grid to fill. The container will be
44410  * automatically set to position relative if it isn't already.
44411  * @param {Object} config A config object that sets properties on this grid.
44412  */
44413 Roo.grid.PropertyGrid = function(container, config){
44414     config = config || {};
44415     var store = new Roo.grid.PropertyStore(this);
44416     this.store = store;
44417     var cm = new Roo.grid.PropertyColumnModel(this, store);
44418     store.store.sort('name', 'ASC');
44419     Roo.grid.PropertyGrid.superclass.constructor.call(this, container, Roo.apply({
44420         ds: store.store,
44421         cm: cm,
44422         enableColLock:false,
44423         enableColumnMove:false,
44424         stripeRows:false,
44425         trackMouseOver: false,
44426         clicksToEdit:1
44427     }, config));
44428     this.getGridEl().addClass('x-props-grid');
44429     this.lastEditRow = null;
44430     this.on('columnresize', this.onColumnResize, this);
44431     this.addEvents({
44432          /**
44433              * @event beforepropertychange
44434              * Fires before a property changes (return false to stop?)
44435              * @param {Roo.grid.PropertyGrid} grid property grid? (check could be store)
44436              * @param {String} id Record Id
44437              * @param {String} newval New Value
44438          * @param {String} oldval Old Value
44439              */
44440         "beforepropertychange": true,
44441         /**
44442              * @event propertychange
44443              * Fires after a property changes
44444              * @param {Roo.grid.PropertyGrid} grid property grid? (check could be store)
44445              * @param {String} id Record Id
44446              * @param {String} newval New Value
44447          * @param {String} oldval Old Value
44448              */
44449         "propertychange": true
44450     });
44451     this.customEditors = this.customEditors || {};
44452 };
44453 Roo.extend(Roo.grid.PropertyGrid, Roo.grid.EditorGrid, {
44454     
44455      /**
44456      * @cfg {Object} customEditors map of colnames=> custom editors.
44457      * the custom editor can be one of the standard ones (date|string|number|int|boolean), or a
44458      * grid editor eg. Roo.grid.GridEditor(new Roo.form.TextArea({selectOnFocus:true})),
44459      * false disables editing of the field.
44460          */
44461     
44462       /**
44463      * @cfg {Object} propertyNames map of property Names to their displayed value
44464          */
44465     
44466     render : function(){
44467         Roo.grid.PropertyGrid.superclass.render.call(this);
44468         this.autoSize.defer(100, this);
44469     },
44470
44471     autoSize : function(){
44472         Roo.grid.PropertyGrid.superclass.autoSize.call(this);
44473         if(this.view){
44474             this.view.fitColumns();
44475         }
44476     },
44477
44478     onColumnResize : function(){
44479         this.colModel.setColumnWidth(1, this.container.getWidth(true)-this.colModel.getColumnWidth(0));
44480         this.autoSize();
44481     },
44482     /**
44483      * Sets the data for the Grid
44484      * accepts a Key => Value object of all the elements avaiable.
44485      * @param {Object} data  to appear in grid.
44486      */
44487     setSource : function(source){
44488         this.store.setSource(source);
44489         //this.autoSize();
44490     },
44491     /**
44492      * Gets all the data from the grid.
44493      * @return {Object} data  data stored in grid
44494      */
44495     getSource : function(){
44496         return this.store.getSource();
44497     }
44498 });/*
44499   
44500  * Licence LGPL
44501  
44502  */
44503  
44504 /**
44505  * @class Roo.grid.Calendar
44506  * @extends Roo.grid.Grid
44507  * This class extends the Grid to provide a calendar widget
44508  * <br><br>Usage:<pre><code>
44509  var grid = new Roo.grid.Calendar("my-container-id", {
44510      ds: myDataStore,
44511      cm: myColModel,
44512      selModel: mySelectionModel,
44513      autoSizeColumns: true,
44514      monitorWindowResize: false,
44515      trackMouseOver: true
44516      eventstore : real data store..
44517  });
44518  // set any options
44519  grid.render();
44520   
44521   * @constructor
44522  * @param {String/HTMLElement/Roo.Element} container The element into which this grid will be rendered -
44523  * The container MUST have some type of size defined for the grid to fill. The container will be
44524  * automatically set to position relative if it isn't already.
44525  * @param {Object} config A config object that sets properties on this grid.
44526  */
44527 Roo.grid.Calendar = function(container, config){
44528         // initialize the container
44529         this.container = Roo.get(container);
44530         this.container.update("");
44531         this.container.setStyle("overflow", "hidden");
44532     this.container.addClass('x-grid-container');
44533
44534     this.id = this.container.id;
44535
44536     Roo.apply(this, config);
44537     // check and correct shorthanded configs
44538     
44539     var rows = [];
44540     var d =1;
44541     for (var r = 0;r < 6;r++) {
44542         
44543         rows[r]=[];
44544         for (var c =0;c < 7;c++) {
44545             rows[r][c]= '';
44546         }
44547     }
44548     if (this.eventStore) {
44549         this.eventStore= Roo.factory(this.eventStore, Roo.data);
44550         this.eventStore.on('load',this.onLoad, this);
44551         this.eventStore.on('beforeload',this.clearEvents, this);
44552          
44553     }
44554     
44555     this.dataSource = new Roo.data.Store({
44556             proxy: new Roo.data.MemoryProxy(rows),
44557             reader: new Roo.data.ArrayReader({}, [
44558                    'weekday0', 'weekday1', 'weekday2', 'weekday3', 'weekday4', 'weekday5', 'weekday6' ])
44559     });
44560
44561     this.dataSource.load();
44562     this.ds = this.dataSource;
44563     this.ds.xmodule = this.xmodule || false;
44564     
44565     
44566     var cellRender = function(v,x,r)
44567     {
44568         return String.format(
44569             '<div class="fc-day  fc-widget-content"><div>' +
44570                 '<div class="fc-event-container"></div>' +
44571                 '<div class="fc-day-number">{0}</div>'+
44572                 
44573                 '<div class="fc-day-content"><div style="position:relative"></div></div>' +
44574             '</div></div>', v);
44575     
44576     }
44577     
44578     
44579     this.colModel = new Roo.grid.ColumnModel( [
44580         {
44581             xtype: 'ColumnModel',
44582             xns: Roo.grid,
44583             dataIndex : 'weekday0',
44584             header : 'Sunday',
44585             renderer : cellRender
44586         },
44587         {
44588             xtype: 'ColumnModel',
44589             xns: Roo.grid,
44590             dataIndex : 'weekday1',
44591             header : 'Monday',
44592             renderer : cellRender
44593         },
44594         {
44595             xtype: 'ColumnModel',
44596             xns: Roo.grid,
44597             dataIndex : 'weekday2',
44598             header : 'Tuesday',
44599             renderer : cellRender
44600         },
44601         {
44602             xtype: 'ColumnModel',
44603             xns: Roo.grid,
44604             dataIndex : 'weekday3',
44605             header : 'Wednesday',
44606             renderer : cellRender
44607         },
44608         {
44609             xtype: 'ColumnModel',
44610             xns: Roo.grid,
44611             dataIndex : 'weekday4',
44612             header : 'Thursday',
44613             renderer : cellRender
44614         },
44615         {
44616             xtype: 'ColumnModel',
44617             xns: Roo.grid,
44618             dataIndex : 'weekday5',
44619             header : 'Friday',
44620             renderer : cellRender
44621         },
44622         {
44623             xtype: 'ColumnModel',
44624             xns: Roo.grid,
44625             dataIndex : 'weekday6',
44626             header : 'Saturday',
44627             renderer : cellRender
44628         }
44629     ]);
44630     this.cm = this.colModel;
44631     this.cm.xmodule = this.xmodule || false;
44632  
44633         
44634           
44635     //this.selModel = new Roo.grid.CellSelectionModel();
44636     //this.sm = this.selModel;
44637     //this.selModel.init(this);
44638     
44639     
44640     if(this.width){
44641         this.container.setWidth(this.width);
44642     }
44643
44644     if(this.height){
44645         this.container.setHeight(this.height);
44646     }
44647     /** @private */
44648         this.addEvents({
44649         // raw events
44650         /**
44651          * @event click
44652          * The raw click event for the entire grid.
44653          * @param {Roo.EventObject} e
44654          */
44655         "click" : true,
44656         /**
44657          * @event dblclick
44658          * The raw dblclick event for the entire grid.
44659          * @param {Roo.EventObject} e
44660          */
44661         "dblclick" : true,
44662         /**
44663          * @event contextmenu
44664          * The raw contextmenu event for the entire grid.
44665          * @param {Roo.EventObject} e
44666          */
44667         "contextmenu" : true,
44668         /**
44669          * @event mousedown
44670          * The raw mousedown event for the entire grid.
44671          * @param {Roo.EventObject} e
44672          */
44673         "mousedown" : true,
44674         /**
44675          * @event mouseup
44676          * The raw mouseup event for the entire grid.
44677          * @param {Roo.EventObject} e
44678          */
44679         "mouseup" : true,
44680         /**
44681          * @event mouseover
44682          * The raw mouseover event for the entire grid.
44683          * @param {Roo.EventObject} e
44684          */
44685         "mouseover" : true,
44686         /**
44687          * @event mouseout
44688          * The raw mouseout event for the entire grid.
44689          * @param {Roo.EventObject} e
44690          */
44691         "mouseout" : true,
44692         /**
44693          * @event keypress
44694          * The raw keypress event for the entire grid.
44695          * @param {Roo.EventObject} e
44696          */
44697         "keypress" : true,
44698         /**
44699          * @event keydown
44700          * The raw keydown event for the entire grid.
44701          * @param {Roo.EventObject} e
44702          */
44703         "keydown" : true,
44704
44705         // custom events
44706
44707         /**
44708          * @event cellclick
44709          * Fires when a cell is clicked
44710          * @param {Grid} this
44711          * @param {Number} rowIndex
44712          * @param {Number} columnIndex
44713          * @param {Roo.EventObject} e
44714          */
44715         "cellclick" : true,
44716         /**
44717          * @event celldblclick
44718          * Fires when a cell is double clicked
44719          * @param {Grid} this
44720          * @param {Number} rowIndex
44721          * @param {Number} columnIndex
44722          * @param {Roo.EventObject} e
44723          */
44724         "celldblclick" : true,
44725         /**
44726          * @event rowclick
44727          * Fires when a row is clicked
44728          * @param {Grid} this
44729          * @param {Number} rowIndex
44730          * @param {Roo.EventObject} e
44731          */
44732         "rowclick" : true,
44733         /**
44734          * @event rowdblclick
44735          * Fires when a row is double clicked
44736          * @param {Grid} this
44737          * @param {Number} rowIndex
44738          * @param {Roo.EventObject} e
44739          */
44740         "rowdblclick" : true,
44741         /**
44742          * @event headerclick
44743          * Fires when a header is clicked
44744          * @param {Grid} this
44745          * @param {Number} columnIndex
44746          * @param {Roo.EventObject} e
44747          */
44748         "headerclick" : true,
44749         /**
44750          * @event headerdblclick
44751          * Fires when a header cell is double clicked
44752          * @param {Grid} this
44753          * @param {Number} columnIndex
44754          * @param {Roo.EventObject} e
44755          */
44756         "headerdblclick" : true,
44757         /**
44758          * @event rowcontextmenu
44759          * Fires when a row is right clicked
44760          * @param {Grid} this
44761          * @param {Number} rowIndex
44762          * @param {Roo.EventObject} e
44763          */
44764         "rowcontextmenu" : true,
44765         /**
44766          * @event cellcontextmenu
44767          * Fires when a cell is right clicked
44768          * @param {Grid} this
44769          * @param {Number} rowIndex
44770          * @param {Number} cellIndex
44771          * @param {Roo.EventObject} e
44772          */
44773          "cellcontextmenu" : true,
44774         /**
44775          * @event headercontextmenu
44776          * Fires when a header is right clicked
44777          * @param {Grid} this
44778          * @param {Number} columnIndex
44779          * @param {Roo.EventObject} e
44780          */
44781         "headercontextmenu" : true,
44782         /**
44783          * @event bodyscroll
44784          * Fires when the body element is scrolled
44785          * @param {Number} scrollLeft
44786          * @param {Number} scrollTop
44787          */
44788         "bodyscroll" : true,
44789         /**
44790          * @event columnresize
44791          * Fires when the user resizes a column
44792          * @param {Number} columnIndex
44793          * @param {Number} newSize
44794          */
44795         "columnresize" : true,
44796         /**
44797          * @event columnmove
44798          * Fires when the user moves a column
44799          * @param {Number} oldIndex
44800          * @param {Number} newIndex
44801          */
44802         "columnmove" : true,
44803         /**
44804          * @event startdrag
44805          * Fires when row(s) start being dragged
44806          * @param {Grid} this
44807          * @param {Roo.GridDD} dd The drag drop object
44808          * @param {event} e The raw browser event
44809          */
44810         "startdrag" : true,
44811         /**
44812          * @event enddrag
44813          * Fires when a drag operation is complete
44814          * @param {Grid} this
44815          * @param {Roo.GridDD} dd The drag drop object
44816          * @param {event} e The raw browser event
44817          */
44818         "enddrag" : true,
44819         /**
44820          * @event dragdrop
44821          * Fires when dragged row(s) are dropped on a valid DD target
44822          * @param {Grid} this
44823          * @param {Roo.GridDD} dd The drag drop object
44824          * @param {String} targetId The target drag drop object
44825          * @param {event} e The raw browser event
44826          */
44827         "dragdrop" : true,
44828         /**
44829          * @event dragover
44830          * Fires while row(s) are being dragged. "targetId" is the id of the Yahoo.util.DD object the selected rows are being dragged over.
44831          * @param {Grid} this
44832          * @param {Roo.GridDD} dd The drag drop object
44833          * @param {String} targetId The target drag drop object
44834          * @param {event} e The raw browser event
44835          */
44836         "dragover" : true,
44837         /**
44838          * @event dragenter
44839          *  Fires when the dragged row(s) first cross another DD target while being dragged
44840          * @param {Grid} this
44841          * @param {Roo.GridDD} dd The drag drop object
44842          * @param {String} targetId The target drag drop object
44843          * @param {event} e The raw browser event
44844          */
44845         "dragenter" : true,
44846         /**
44847          * @event dragout
44848          * Fires when the dragged row(s) leave another DD target while being dragged
44849          * @param {Grid} this
44850          * @param {Roo.GridDD} dd The drag drop object
44851          * @param {String} targetId The target drag drop object
44852          * @param {event} e The raw browser event
44853          */
44854         "dragout" : true,
44855         /**
44856          * @event rowclass
44857          * Fires when a row is rendered, so you can change add a style to it.
44858          * @param {GridView} gridview   The grid view
44859          * @param {Object} rowcfg   contains record  rowIndex and rowClass - set rowClass to add a style.
44860          */
44861         'rowclass' : true,
44862
44863         /**
44864          * @event render
44865          * Fires when the grid is rendered
44866          * @param {Grid} grid
44867          */
44868         'render' : true,
44869             /**
44870              * @event select
44871              * Fires when a date is selected
44872              * @param {DatePicker} this
44873              * @param {Date} date The selected date
44874              */
44875         'select': true,
44876         /**
44877              * @event monthchange
44878              * Fires when the displayed month changes 
44879              * @param {DatePicker} this
44880              * @param {Date} date The selected month
44881              */
44882         'monthchange': true,
44883         /**
44884              * @event evententer
44885              * Fires when mouse over an event
44886              * @param {Calendar} this
44887              * @param {event} Event
44888              */
44889         'evententer': true,
44890         /**
44891              * @event eventleave
44892              * Fires when the mouse leaves an
44893              * @param {Calendar} this
44894              * @param {event}
44895              */
44896         'eventleave': true,
44897         /**
44898              * @event eventclick
44899              * Fires when the mouse click an
44900              * @param {Calendar} this
44901              * @param {event}
44902              */
44903         'eventclick': true,
44904         /**
44905              * @event eventrender
44906              * Fires before each cell is rendered, so you can modify the contents, like cls / title / qtip
44907              * @param {Calendar} this
44908              * @param {data} data to be modified
44909              */
44910         'eventrender': true
44911         
44912     });
44913
44914     Roo.grid.Grid.superclass.constructor.call(this);
44915     this.on('render', function() {
44916         this.view.el.addClass('x-grid-cal'); 
44917         
44918         (function() { this.setDate(new Date()); }).defer(100,this); //default today..
44919
44920     },this);
44921     
44922     if (!Roo.grid.Calendar.style) {
44923         Roo.grid.Calendar.style = Roo.util.CSS.createStyleSheet({
44924             
44925             
44926             '.x-grid-cal .x-grid-col' :  {
44927                 height: 'auto !important',
44928                 'vertical-align': 'top'
44929             },
44930             '.x-grid-cal  .fc-event-hori' : {
44931                 height: '14px'
44932             }
44933              
44934             
44935         }, Roo.id());
44936     }
44937
44938     
44939     
44940 };
44941 Roo.extend(Roo.grid.Calendar, Roo.grid.Grid, {
44942     /**
44943      * @cfg {Store} eventStore The store that loads events.
44944      */
44945     eventStore : 25,
44946
44947      
44948     activeDate : false,
44949     startDay : 0,
44950     autoWidth : true,
44951     monitorWindowResize : false,
44952
44953     
44954     resizeColumns : function() {
44955         var col = (this.view.el.getWidth() / 7) - 3;
44956         // loop through cols, and setWidth
44957         for(var i =0 ; i < 7 ; i++){
44958             this.cm.setColumnWidth(i, col);
44959         }
44960     },
44961      setDate :function(date) {
44962         
44963         Roo.log('setDate?');
44964         
44965         this.resizeColumns();
44966         var vd = this.activeDate;
44967         this.activeDate = date;
44968 //        if(vd && this.el){
44969 //            var t = date.getTime();
44970 //            if(vd.getMonth() == date.getMonth() && vd.getFullYear() == date.getFullYear()){
44971 //                Roo.log('using add remove');
44972 //                
44973 //                this.fireEvent('monthchange', this, date);
44974 //                
44975 //                this.cells.removeClass("fc-state-highlight");
44976 //                this.cells.each(function(c){
44977 //                   if(c.dateValue == t){
44978 //                       c.addClass("fc-state-highlight");
44979 //                       setTimeout(function(){
44980 //                            try{c.dom.firstChild.focus();}catch(e){}
44981 //                       }, 50);
44982 //                       return false;
44983 //                   }
44984 //                   return true;
44985 //                });
44986 //                return;
44987 //            }
44988 //        }
44989         
44990         var days = date.getDaysInMonth();
44991         
44992         var firstOfMonth = date.getFirstDateOfMonth();
44993         var startingPos = firstOfMonth.getDay()-this.startDay;
44994         
44995         if(startingPos < this.startDay){
44996             startingPos += 7;
44997         }
44998         
44999         var pm = date.add(Date.MONTH, -1);
45000         var prevStart = pm.getDaysInMonth()-startingPos;
45001 //        
45002         
45003         
45004         this.cells = this.view.el.select('.x-grid-row .x-grid-col',true);
45005         
45006         this.textNodes = this.view.el.query('.x-grid-row .x-grid-col .x-grid-cell-text');
45007         //this.cells.addClassOnOver('fc-state-hover');
45008         
45009         var cells = this.cells.elements;
45010         var textEls = this.textNodes;
45011         
45012         //Roo.each(cells, function(cell){
45013         //    cell.removeClass([ 'fc-past', 'fc-other-month', 'fc-future', 'fc-state-highlight', 'fc-state-disabled']);
45014         //});
45015         
45016         days += startingPos;
45017
45018         // convert everything to numbers so it's fast
45019         var day = 86400000;
45020         var d = (new Date(pm.getFullYear(), pm.getMonth(), prevStart)).clearTime();
45021         //Roo.log(d);
45022         //Roo.log(pm);
45023         //Roo.log(prevStart);
45024         
45025         var today = new Date().clearTime().getTime();
45026         var sel = date.clearTime().getTime();
45027         var min = this.minDate ? this.minDate.clearTime() : Number.NEGATIVE_INFINITY;
45028         var max = this.maxDate ? this.maxDate.clearTime() : Number.POSITIVE_INFINITY;
45029         var ddMatch = this.disabledDatesRE;
45030         var ddText = this.disabledDatesText;
45031         var ddays = this.disabledDays ? this.disabledDays.join("") : false;
45032         var ddaysText = this.disabledDaysText;
45033         var format = this.format;
45034         
45035         var setCellClass = function(cal, cell){
45036             
45037             //Roo.log('set Cell Class');
45038             cell.title = "";
45039             var t = d.getTime();
45040             
45041             //Roo.log(d);
45042             
45043             
45044             cell.dateValue = t;
45045             if(t == today){
45046                 cell.className += " fc-today";
45047                 cell.className += " fc-state-highlight";
45048                 cell.title = cal.todayText;
45049             }
45050             if(t == sel){
45051                 // disable highlight in other month..
45052                 cell.className += " fc-state-highlight";
45053                 
45054             }
45055             // disabling
45056             if(t < min) {
45057                 //cell.className = " fc-state-disabled";
45058                 cell.title = cal.minText;
45059                 return;
45060             }
45061             if(t > max) {
45062                 //cell.className = " fc-state-disabled";
45063                 cell.title = cal.maxText;
45064                 return;
45065             }
45066             if(ddays){
45067                 if(ddays.indexOf(d.getDay()) != -1){
45068                     // cell.title = ddaysText;
45069                    // cell.className = " fc-state-disabled";
45070                 }
45071             }
45072             if(ddMatch && format){
45073                 var fvalue = d.dateFormat(format);
45074                 if(ddMatch.test(fvalue)){
45075                     cell.title = ddText.replace("%0", fvalue);
45076                    cell.className = " fc-state-disabled";
45077                 }
45078             }
45079             
45080             if (!cell.initialClassName) {
45081                 cell.initialClassName = cell.dom.className;
45082             }
45083             
45084             cell.dom.className = cell.initialClassName  + ' ' +  cell.className;
45085         };
45086
45087         var i = 0;
45088         
45089         for(; i < startingPos; i++) {
45090             cells[i].dayName =  (++prevStart);
45091             Roo.log(textEls[i]);
45092             d.setDate(d.getDate()+1);
45093             
45094             //cells[i].className = "fc-past fc-other-month";
45095             setCellClass(this, cells[i]);
45096         }
45097         
45098         var intDay = 0;
45099         
45100         for(; i < days; i++){
45101             intDay = i - startingPos + 1;
45102             cells[i].dayName =  (intDay);
45103             d.setDate(d.getDate()+1);
45104             
45105             cells[i].className = ''; // "x-date-active";
45106             setCellClass(this, cells[i]);
45107         }
45108         var extraDays = 0;
45109         
45110         for(; i < 42; i++) {
45111             //textEls[i].innerHTML = (++extraDays);
45112             
45113             d.setDate(d.getDate()+1);
45114             cells[i].dayName = (++extraDays);
45115             cells[i].className = "fc-future fc-other-month";
45116             setCellClass(this, cells[i]);
45117         }
45118         
45119         //this.el.select('.fc-header-title h2',true).update(Date.monthNames[date.getMonth()] + " " + date.getFullYear());
45120         
45121         var totalRows = Math.ceil((date.getDaysInMonth() + date.getFirstDateOfMonth().getDay()) / 7);
45122         
45123         // this will cause all the cells to mis
45124         var rows= [];
45125         var i =0;
45126         for (var r = 0;r < 6;r++) {
45127             for (var c =0;c < 7;c++) {
45128                 this.ds.getAt(r).set('weekday' + c ,cells[i++].dayName );
45129             }    
45130         }
45131         
45132         this.cells = this.view.el.select('.x-grid-row .x-grid-col',true);
45133         for(i=0;i<cells.length;i++) {
45134             
45135             this.cells.elements[i].dayName = cells[i].dayName ;
45136             this.cells.elements[i].className = cells[i].className;
45137             this.cells.elements[i].initialClassName = cells[i].initialClassName ;
45138             this.cells.elements[i].title = cells[i].title ;
45139             this.cells.elements[i].dateValue = cells[i].dateValue ;
45140         }
45141         
45142         
45143         
45144         
45145         //this.el.select('tr.fc-week.fc-prev-last',true).removeClass('fc-last');
45146         //this.el.select('tr.fc-week.fc-next-last',true).addClass('fc-last').show();
45147         
45148         ////if(totalRows != 6){
45149             //this.el.select('tr.fc-week.fc-last',true).removeClass('fc-last').addClass('fc-next-last').hide();
45150            // this.el.select('tr.fc-week.fc-prev-last',true).addClass('fc-last');
45151        // }
45152         
45153         this.fireEvent('monthchange', this, date);
45154         
45155         
45156     },
45157  /**
45158      * Returns the grid's SelectionModel.
45159      * @return {SelectionModel}
45160      */
45161     getSelectionModel : function(){
45162         if(!this.selModel){
45163             this.selModel = new Roo.grid.CellSelectionModel();
45164         }
45165         return this.selModel;
45166     },
45167
45168     load: function() {
45169         this.eventStore.load()
45170         
45171         
45172         
45173     },
45174     
45175     findCell : function(dt) {
45176         dt = dt.clearTime().getTime();
45177         var ret = false;
45178         this.cells.each(function(c){
45179             //Roo.log("check " +c.dateValue + '?=' + dt);
45180             if(c.dateValue == dt){
45181                 ret = c;
45182                 return false;
45183             }
45184             return true;
45185         });
45186         
45187         return ret;
45188     },
45189     
45190     findCells : function(rec) {
45191         var s = rec.data.start_dt.clone().clearTime().getTime();
45192        // Roo.log(s);
45193         var e= rec.data.end_dt.clone().clearTime().getTime();
45194        // Roo.log(e);
45195         var ret = [];
45196         this.cells.each(function(c){
45197              ////Roo.log("check " +c.dateValue + '<' + e + ' > ' + s);
45198             
45199             if(c.dateValue > e){
45200                 return ;
45201             }
45202             if(c.dateValue < s){
45203                 return ;
45204             }
45205             ret.push(c);
45206         });
45207         
45208         return ret;    
45209     },
45210     
45211     findBestRow: function(cells)
45212     {
45213         var ret = 0;
45214         
45215         for (var i =0 ; i < cells.length;i++) {
45216             ret  = Math.max(cells[i].rows || 0,ret);
45217         }
45218         return ret;
45219         
45220     },
45221     
45222     
45223     addItem : function(rec)
45224     {
45225         // look for vertical location slot in
45226         var cells = this.findCells(rec);
45227         
45228         rec.row = this.findBestRow(cells);
45229         
45230         // work out the location.
45231         
45232         var crow = false;
45233         var rows = [];
45234         for(var i =0; i < cells.length; i++) {
45235             if (!crow) {
45236                 crow = {
45237                     start : cells[i],
45238                     end :  cells[i]
45239                 };
45240                 continue;
45241             }
45242             if (crow.start.getY() == cells[i].getY()) {
45243                 // on same row.
45244                 crow.end = cells[i];
45245                 continue;
45246             }
45247             // different row.
45248             rows.push(crow);
45249             crow = {
45250                 start: cells[i],
45251                 end : cells[i]
45252             };
45253             
45254         }
45255         
45256         rows.push(crow);
45257         rec.els = [];
45258         rec.rows = rows;
45259         rec.cells = cells;
45260         for (var i = 0; i < cells.length;i++) {
45261             cells[i].rows = Math.max(cells[i].rows || 0 , rec.row + 1 );
45262             
45263         }
45264         
45265         
45266     },
45267     
45268     clearEvents: function() {
45269         
45270         if (!this.eventStore.getCount()) {
45271             return;
45272         }
45273         // reset number of rows in cells.
45274         Roo.each(this.cells.elements, function(c){
45275             c.rows = 0;
45276         });
45277         
45278         this.eventStore.each(function(e) {
45279             this.clearEvent(e);
45280         },this);
45281         
45282     },
45283     
45284     clearEvent : function(ev)
45285     {
45286         if (ev.els) {
45287             Roo.each(ev.els, function(el) {
45288                 el.un('mouseenter' ,this.onEventEnter, this);
45289                 el.un('mouseleave' ,this.onEventLeave, this);
45290                 el.remove();
45291             },this);
45292             ev.els = [];
45293         }
45294     },
45295     
45296     
45297     renderEvent : function(ev,ctr) {
45298         if (!ctr) {
45299              ctr = this.view.el.select('.fc-event-container',true).first();
45300         }
45301         
45302          
45303         this.clearEvent(ev);
45304             //code
45305        
45306         
45307         
45308         ev.els = [];
45309         var cells = ev.cells;
45310         var rows = ev.rows;
45311         this.fireEvent('eventrender', this, ev);
45312         
45313         for(var i =0; i < rows.length; i++) {
45314             
45315             cls = '';
45316             if (i == 0) {
45317                 cls += ' fc-event-start';
45318             }
45319             if ((i+1) == rows.length) {
45320                 cls += ' fc-event-end';
45321             }
45322             
45323             //Roo.log(ev.data);
45324             // how many rows should it span..
45325             var cg = this.eventTmpl.append(ctr,Roo.apply({
45326                 fccls : cls
45327                 
45328             }, ev.data) , true);
45329             
45330             
45331             cg.on('mouseenter' ,this.onEventEnter, this, ev);
45332             cg.on('mouseleave' ,this.onEventLeave, this, ev);
45333             cg.on('click', this.onEventClick, this, ev);
45334             
45335             ev.els.push(cg);
45336             
45337             var sbox = rows[i].start.select('.fc-day-content',true).first().getBox();
45338             var ebox = rows[i].end.select('.fc-day-content',true).first().getBox();
45339             //Roo.log(cg);
45340              
45341             cg.setXY([sbox.x +2, sbox.y +(ev.row * 20)]);    
45342             cg.setWidth(ebox.right - sbox.x -2);
45343         }
45344     },
45345     
45346     renderEvents: function()
45347     {   
45348         // first make sure there is enough space..
45349         
45350         if (!this.eventTmpl) {
45351             this.eventTmpl = new Roo.Template(
45352                 '<div class="roo-dynamic fc-event fc-event-hori fc-event-draggable ui-draggable {fccls} {cls}"  style="position: absolute" unselectable="on">' +
45353                     '<div class="fc-event-inner">' +
45354                         '<span class="fc-event-time">{time}</span>' +
45355                         '<span class="fc-event-title" qtip="{qtip}">{title}</span>' +
45356                     '</div>' +
45357                     '<div class="ui-resizable-heandle ui-resizable-e">&nbsp;&nbsp;&nbsp;</div>' +
45358                 '</div>'
45359             );
45360                 
45361         }
45362                
45363         
45364         
45365         this.cells.each(function(c) {
45366             //Roo.log(c.select('.fc-day-content div',true).first());
45367             c.select('.fc-day-content div',true).first().setHeight(Math.max(34, (c.rows || 1) * 20));
45368         });
45369         
45370         var ctr = this.view.el.select('.fc-event-container',true).first();
45371         
45372         var cls;
45373         this.eventStore.each(function(ev){
45374             
45375             this.renderEvent(ev);
45376              
45377              
45378         }, this);
45379         this.view.layout();
45380         
45381     },
45382     
45383     onEventEnter: function (e, el,event,d) {
45384         this.fireEvent('evententer', this, el, event);
45385     },
45386     
45387     onEventLeave: function (e, el,event,d) {
45388         this.fireEvent('eventleave', this, el, event);
45389     },
45390     
45391     onEventClick: function (e, el,event,d) {
45392         this.fireEvent('eventclick', this, el, event);
45393     },
45394     
45395     onMonthChange: function () {
45396         this.store.load();
45397     },
45398     
45399     onLoad: function () {
45400         
45401         //Roo.log('calendar onload');
45402 //         
45403         if(this.eventStore.getCount() > 0){
45404             
45405            
45406             
45407             this.eventStore.each(function(d){
45408                 
45409                 
45410                 // FIXME..
45411                 var add =   d.data;
45412                 if (typeof(add.end_dt) == 'undefined')  {
45413                     Roo.log("Missing End time in calendar data: ");
45414                     Roo.log(d);
45415                     return;
45416                 }
45417                 if (typeof(add.start_dt) == 'undefined')  {
45418                     Roo.log("Missing Start time in calendar data: ");
45419                     Roo.log(d);
45420                     return;
45421                 }
45422                 add.start_dt = typeof(add.start_dt) == 'string' ? Date.parseDate(add.start_dt,'Y-m-d H:i:s') : add.start_dt,
45423                 add.end_dt = typeof(add.end_dt) == 'string' ? Date.parseDate(add.end_dt,'Y-m-d H:i:s') : add.end_dt,
45424                 add.id = add.id || d.id;
45425                 add.title = add.title || '??';
45426                 
45427                 this.addItem(d);
45428                 
45429              
45430             },this);
45431         }
45432         
45433         this.renderEvents();
45434     }
45435     
45436
45437 });
45438 /*
45439  grid : {
45440                 xtype: 'Grid',
45441                 xns: Roo.grid,
45442                 listeners : {
45443                     render : function ()
45444                     {
45445                         _this.grid = this;
45446                         
45447                         if (!this.view.el.hasClass('course-timesheet')) {
45448                             this.view.el.addClass('course-timesheet');
45449                         }
45450                         if (this.tsStyle) {
45451                             this.ds.load({});
45452                             return; 
45453                         }
45454                         Roo.log('width');
45455                         Roo.log(_this.grid.view.el.getWidth());
45456                         
45457                         
45458                         this.tsStyle =  Roo.util.CSS.createStyleSheet({
45459                             '.course-timesheet .x-grid-row' : {
45460                                 height: '80px'
45461                             },
45462                             '.x-grid-row td' : {
45463                                 'vertical-align' : 0
45464                             },
45465                             '.course-edit-link' : {
45466                                 'color' : 'blue',
45467                                 'text-overflow' : 'ellipsis',
45468                                 'overflow' : 'hidden',
45469                                 'white-space' : 'nowrap',
45470                                 'cursor' : 'pointer'
45471                             },
45472                             '.sub-link' : {
45473                                 'color' : 'green'
45474                             },
45475                             '.de-act-sup-link' : {
45476                                 'color' : 'purple',
45477                                 'text-decoration' : 'line-through'
45478                             },
45479                             '.de-act-link' : {
45480                                 'color' : 'red',
45481                                 'text-decoration' : 'line-through'
45482                             },
45483                             '.course-timesheet .course-highlight' : {
45484                                 'border-top-style': 'dashed !important',
45485                                 'border-bottom-bottom': 'dashed !important'
45486                             },
45487                             '.course-timesheet .course-item' : {
45488                                 'font-family'   : 'tahoma, arial, helvetica',
45489                                 'font-size'     : '11px',
45490                                 'overflow'      : 'hidden',
45491                                 'padding-left'  : '10px',
45492                                 'padding-right' : '10px',
45493                                 'padding-top' : '10px' 
45494                             }
45495                             
45496                         }, Roo.id());
45497                                 this.ds.load({});
45498                     }
45499                 },
45500                 autoWidth : true,
45501                 monitorWindowResize : false,
45502                 cellrenderer : function(v,x,r)
45503                 {
45504                     return v;
45505                 },
45506                 sm : {
45507                     xtype: 'CellSelectionModel',
45508                     xns: Roo.grid
45509                 },
45510                 dataSource : {
45511                     xtype: 'Store',
45512                     xns: Roo.data,
45513                     listeners : {
45514                         beforeload : function (_self, options)
45515                         {
45516                             options.params = options.params || {};
45517                             options.params._month = _this.monthField.getValue();
45518                             options.params.limit = 9999;
45519                             options.params['sort'] = 'when_dt';    
45520                             options.params['dir'] = 'ASC';    
45521                             this.proxy.loadResponse = this.loadResponse;
45522                             Roo.log("load?");
45523                             //this.addColumns();
45524                         },
45525                         load : function (_self, records, options)
45526                         {
45527                             _this.grid.view.el.select('.course-edit-link', true).on('click', function() {
45528                                 // if you click on the translation.. you can edit it...
45529                                 var el = Roo.get(this);
45530                                 var id = el.dom.getAttribute('data-id');
45531                                 var d = el.dom.getAttribute('data-date');
45532                                 var t = el.dom.getAttribute('data-time');
45533                                 //var id = this.child('span').dom.textContent;
45534                                 
45535                                 //Roo.log(this);
45536                                 Pman.Dialog.CourseCalendar.show({
45537                                     id : id,
45538                                     when_d : d,
45539                                     when_t : t,
45540                                     productitem_active : id ? 1 : 0
45541                                 }, function() {
45542                                     _this.grid.ds.load({});
45543                                 });
45544                            
45545                            });
45546                            
45547                            _this.panel.fireEvent('resize', [ '', '' ]);
45548                         }
45549                     },
45550                     loadResponse : function(o, success, response){
45551                             // this is overridden on before load..
45552                             
45553                             Roo.log("our code?");       
45554                             //Roo.log(success);
45555                             //Roo.log(response)
45556                             delete this.activeRequest;
45557                             if(!success){
45558                                 this.fireEvent("loadexception", this, o, response);
45559                                 o.request.callback.call(o.request.scope, null, o.request.arg, false);
45560                                 return;
45561                             }
45562                             var result;
45563                             try {
45564                                 result = o.reader.read(response);
45565                             }catch(e){
45566                                 Roo.log("load exception?");
45567                                 this.fireEvent("loadexception", this, o, response, e);
45568                                 o.request.callback.call(o.request.scope, null, o.request.arg, false);
45569                                 return;
45570                             }
45571                             Roo.log("ready...");        
45572                             // loop through result.records;
45573                             // and set this.tdate[date] = [] << array of records..
45574                             _this.tdata  = {};
45575                             Roo.each(result.records, function(r){
45576                                 //Roo.log(r.data);
45577                                 if(typeof(_this.tdata[r.data.when_dt.format('j')]) == 'undefined'){
45578                                     _this.tdata[r.data.when_dt.format('j')] = [];
45579                                 }
45580                                 _this.tdata[r.data.when_dt.format('j')].push(r.data);
45581                             });
45582                             
45583                             //Roo.log(_this.tdata);
45584                             
45585                             result.records = [];
45586                             result.totalRecords = 6;
45587                     
45588                             // let's generate some duumy records for the rows.
45589                             //var st = _this.dateField.getValue();
45590                             
45591                             // work out monday..
45592                             //st = st.add(Date.DAY, -1 * st.format('w'));
45593                             
45594                             var date = Date.parseDate(_this.monthField.getValue(), "Y-m-d");
45595                             
45596                             var firstOfMonth = date.getFirstDayOfMonth();
45597                             var days = date.getDaysInMonth();
45598                             var d = 1;
45599                             var firstAdded = false;
45600                             for (var i = 0; i < result.totalRecords ; i++) {
45601                                 //var d= st.add(Date.DAY, i);
45602                                 var row = {};
45603                                 var added = 0;
45604                                 for(var w = 0 ; w < 7 ; w++){
45605                                     if(!firstAdded && firstOfMonth != w){
45606                                         continue;
45607                                     }
45608                                     if(d > days){
45609                                         continue;
45610                                     }
45611                                     firstAdded = true;
45612                                     var dd = (d > 0 && d < 10) ? "0"+d : d;
45613                                     row['weekday'+w] = String.format(
45614                                                     '<span style="font-size: 16px;"><b>{0}</b></span>'+
45615                                                     '<span class="course-edit-link" style="color:blue;" data-id="0" data-date="{1}"> Add New</span>',
45616                                                     d,
45617                                                     date.format('Y-m-')+dd
45618                                                 );
45619                                     added++;
45620                                     if(typeof(_this.tdata[d]) != 'undefined'){
45621                                         Roo.each(_this.tdata[d], function(r){
45622                                             var is_sub = '';
45623                                             var deactive = '';
45624                                             var id = r.id;
45625                                             var desc = (r.productitem_id_descrip) ? r.productitem_id_descrip : '';
45626                                             if(r.parent_id*1>0){
45627                                                 is_sub = (r.productitem_id_visible*1 < 1) ? 'de-act-sup-link' :'sub-link';
45628                                                 id = r.parent_id;
45629                                             }
45630                                             if(r.productitem_id_visible*1 < 1 && r.parent_id*1 < 1){
45631                                                 deactive = 'de-act-link';
45632                                             }
45633                                             
45634                                             row['weekday'+w] += String.format(
45635                                                     '<br /><span class="course-edit-link {3} {4}" qtip="{5}" data-id="{0}">{2} - {1}</span>',
45636                                                     id, //0
45637                                                     r.product_id_name, //1
45638                                                     r.when_dt.format('h:ia'), //2
45639                                                     is_sub, //3
45640                                                     deactive, //4
45641                                                     desc // 5
45642                                             );
45643                                         });
45644                                     }
45645                                     d++;
45646                                 }
45647                                 
45648                                 // only do this if something added..
45649                                 if(added > 0){ 
45650                                     result.records.push(_this.grid.dataSource.reader.newRow(row));
45651                                 }
45652                                 
45653                                 
45654                                 // push it twice. (second one with an hour..
45655                                 
45656                             }
45657                             //Roo.log(result);
45658                             this.fireEvent("load", this, o, o.request.arg);
45659                             o.request.callback.call(o.request.scope, result, o.request.arg, true);
45660                         },
45661                     sortInfo : {field: 'when_dt', direction : 'ASC' },
45662                     proxy : {
45663                         xtype: 'HttpProxy',
45664                         xns: Roo.data,
45665                         method : 'GET',
45666                         url : baseURL + '/Roo/Shop_course.php'
45667                     },
45668                     reader : {
45669                         xtype: 'JsonReader',
45670                         xns: Roo.data,
45671                         id : 'id',
45672                         fields : [
45673                             {
45674                                 'name': 'id',
45675                                 'type': 'int'
45676                             },
45677                             {
45678                                 'name': 'when_dt',
45679                                 'type': 'string'
45680                             },
45681                             {
45682                                 'name': 'end_dt',
45683                                 'type': 'string'
45684                             },
45685                             {
45686                                 'name': 'parent_id',
45687                                 'type': 'int'
45688                             },
45689                             {
45690                                 'name': 'product_id',
45691                                 'type': 'int'
45692                             },
45693                             {
45694                                 'name': 'productitem_id',
45695                                 'type': 'int'
45696                             },
45697                             {
45698                                 'name': 'guid',
45699                                 'type': 'int'
45700                             }
45701                         ]
45702                     }
45703                 },
45704                 toolbar : {
45705                     xtype: 'Toolbar',
45706                     xns: Roo,
45707                     items : [
45708                         {
45709                             xtype: 'Button',
45710                             xns: Roo.Toolbar,
45711                             listeners : {
45712                                 click : function (_self, e)
45713                                 {
45714                                     var sd = Date.parseDate(_this.monthField.getValue(), "Y-m-d");
45715                                     sd.setMonth(sd.getMonth()-1);
45716                                     _this.monthField.setValue(sd.format('Y-m-d'));
45717                                     _this.grid.ds.load({});
45718                                 }
45719                             },
45720                             text : "Back"
45721                         },
45722                         {
45723                             xtype: 'Separator',
45724                             xns: Roo.Toolbar
45725                         },
45726                         {
45727                             xtype: 'MonthField',
45728                             xns: Roo.form,
45729                             listeners : {
45730                                 render : function (_self)
45731                                 {
45732                                     _this.monthField = _self;
45733                                    // _this.monthField.set  today
45734                                 },
45735                                 select : function (combo, date)
45736                                 {
45737                                     _this.grid.ds.load({});
45738                                 }
45739                             },
45740                             value : (function() { return new Date(); })()
45741                         },
45742                         {
45743                             xtype: 'Separator',
45744                             xns: Roo.Toolbar
45745                         },
45746                         {
45747                             xtype: 'TextItem',
45748                             xns: Roo.Toolbar,
45749                             text : "Blue: in-active, green: in-active sup-event, red: de-active, purple: de-active sup-event"
45750                         },
45751                         {
45752                             xtype: 'Fill',
45753                             xns: Roo.Toolbar
45754                         },
45755                         {
45756                             xtype: 'Button',
45757                             xns: Roo.Toolbar,
45758                             listeners : {
45759                                 click : function (_self, e)
45760                                 {
45761                                     var sd = Date.parseDate(_this.monthField.getValue(), "Y-m-d");
45762                                     sd.setMonth(sd.getMonth()+1);
45763                                     _this.monthField.setValue(sd.format('Y-m-d'));
45764                                     _this.grid.ds.load({});
45765                                 }
45766                             },
45767                             text : "Next"
45768                         }
45769                     ]
45770                 },
45771                  
45772             }
45773         };
45774         
45775         *//*
45776  * Based on:
45777  * Ext JS Library 1.1.1
45778  * Copyright(c) 2006-2007, Ext JS, LLC.
45779  *
45780  * Originally Released Under LGPL - original licence link has changed is not relivant.
45781  *
45782  * Fork - LGPL
45783  * <script type="text/javascript">
45784  */
45785  
45786 /**
45787  * @class Roo.LoadMask
45788  * A simple utility class for generically masking elements while loading data.  If the element being masked has
45789  * an underlying {@link Roo.data.Store}, the masking will be automatically synchronized with the store's loading
45790  * process and the mask element will be cached for reuse.  For all other elements, this mask will replace the
45791  * element's UpdateManager load indicator and will be destroyed after the initial load.
45792  * @constructor
45793  * Create a new LoadMask
45794  * @param {String/HTMLElement/Roo.Element} el The element or DOM node, or its id
45795  * @param {Object} config The config object
45796  */
45797 Roo.LoadMask = function(el, config){
45798     this.el = Roo.get(el);
45799     Roo.apply(this, config);
45800     if(this.store){
45801         this.store.on('beforeload', this.onBeforeLoad, this);
45802         this.store.on('load', this.onLoad, this);
45803         this.store.on('loadexception', this.onLoadException, this);
45804         this.removeMask = false;
45805     }else{
45806         var um = this.el.getUpdateManager();
45807         um.showLoadIndicator = false; // disable the default indicator
45808         um.on('beforeupdate', this.onBeforeLoad, this);
45809         um.on('update', this.onLoad, this);
45810         um.on('failure', this.onLoad, this);
45811         this.removeMask = true;
45812     }
45813 };
45814
45815 Roo.LoadMask.prototype = {
45816     /**
45817      * @cfg {Boolean} removeMask
45818      * True to create a single-use mask that is automatically destroyed after loading (useful for page loads),
45819      * False to persist the mask element reference for multiple uses (e.g., for paged data widgets).  Defaults to false.
45820      */
45821     removeMask : false,
45822     /**
45823      * @cfg {String} msg
45824      * The text to display in a centered loading message box (defaults to 'Loading...')
45825      */
45826     msg : 'Loading...',
45827     /**
45828      * @cfg {String} msgCls
45829      * The CSS class to apply to the loading message element (defaults to "x-mask-loading")
45830      */
45831     msgCls : 'x-mask-loading',
45832
45833     /**
45834      * Read-only. True if the mask is currently disabled so that it will not be displayed (defaults to false)
45835      * @type Boolean
45836      */
45837     disabled: false,
45838
45839     /**
45840      * Disables the mask to prevent it from being displayed
45841      */
45842     disable : function(){
45843        this.disabled = true;
45844     },
45845
45846     /**
45847      * Enables the mask so that it can be displayed
45848      */
45849     enable : function(){
45850         this.disabled = false;
45851     },
45852     
45853     onLoadException : function()
45854     {
45855         Roo.log(arguments);
45856         
45857         if (typeof(arguments[3]) != 'undefined') {
45858             Roo.MessageBox.alert("Error loading",arguments[3]);
45859         } 
45860         /*
45861         try {
45862             if (this.store && typeof(this.store.reader.jsonData.errorMsg) != 'undefined') {
45863                 Roo.MessageBox.alert("Error loading",this.store.reader.jsonData.errorMsg);
45864             }   
45865         } catch(e) {
45866             
45867         }
45868         */
45869     
45870         (function() { this.el.unmask(this.removeMask); }).defer(50, this);
45871     },
45872     // private
45873     onLoad : function()
45874     {
45875         (function() { this.el.unmask(this.removeMask); }).defer(50, this);
45876     },
45877
45878     // private
45879     onBeforeLoad : function(){
45880         if(!this.disabled){
45881             (function() { this.el.mask(this.msg, this.msgCls); }).defer(50, this);
45882         }
45883     },
45884
45885     // private
45886     destroy : function(){
45887         if(this.store){
45888             this.store.un('beforeload', this.onBeforeLoad, this);
45889             this.store.un('load', this.onLoad, this);
45890             this.store.un('loadexception', this.onLoadException, this);
45891         }else{
45892             var um = this.el.getUpdateManager();
45893             um.un('beforeupdate', this.onBeforeLoad, this);
45894             um.un('update', this.onLoad, this);
45895             um.un('failure', this.onLoad, this);
45896         }
45897     }
45898 };/*
45899  * Based on:
45900  * Ext JS Library 1.1.1
45901  * Copyright(c) 2006-2007, Ext JS, LLC.
45902  *
45903  * Originally Released Under LGPL - original licence link has changed is not relivant.
45904  *
45905  * Fork - LGPL
45906  * <script type="text/javascript">
45907  */
45908
45909
45910 /**
45911  * @class Roo.XTemplate
45912  * @extends Roo.Template
45913  * Provides a template that can have nested templates for loops or conditionals. The syntax is:
45914 <pre><code>
45915 var t = new Roo.XTemplate(
45916         '&lt;select name="{name}"&gt;',
45917                 '&lt;tpl for="options"&gt;&lt;option value="{value:trim}"&gt;{text:ellipsis(10)}&lt;/option&gt;&lt;/tpl&gt;',
45918         '&lt;/select&gt;'
45919 );
45920  
45921 // then append, applying the master template values
45922  </code></pre>
45923  *
45924  * Supported features:
45925  *
45926  *  Tags:
45927
45928 <pre><code>
45929       {a_variable} - output encoded.
45930       {a_variable.format:("Y-m-d")} - call a method on the variable
45931       {a_variable:raw} - unencoded output
45932       {a_variable:toFixed(1,2)} - Roo.util.Format."toFixed"
45933       {a_variable:this.method_on_template(...)} - call a method on the template object.
45934  
45935 </code></pre>
45936  *  The tpl tag:
45937 <pre><code>
45938         &lt;tpl for="a_variable or condition.."&gt;&lt;/tpl&gt;
45939         &lt;tpl if="a_variable or condition"&gt;&lt;/tpl&gt;
45940         &lt;tpl exec="some javascript"&gt;&lt;/tpl&gt;
45941         &lt;tpl name="named_template"&gt;&lt;/tpl&gt; (experimental)
45942   
45943         &lt;tpl for="."&gt;&lt;/tpl&gt; - just iterate the property..
45944         &lt;tpl for=".."&gt;&lt;/tpl&gt; - iterates with the parent (probably the template) 
45945 </code></pre>
45946  *      
45947  */
45948 Roo.XTemplate = function()
45949 {
45950     Roo.XTemplate.superclass.constructor.apply(this, arguments);
45951     if (this.html) {
45952         this.compile();
45953     }
45954 };
45955
45956
45957 Roo.extend(Roo.XTemplate, Roo.Template, {
45958
45959     /**
45960      * The various sub templates
45961      */
45962     tpls : false,
45963     /**
45964      *
45965      * basic tag replacing syntax
45966      * WORD:WORD()
45967      *
45968      * // you can fake an object call by doing this
45969      *  x.t:(test,tesT) 
45970      * 
45971      */
45972     re : /\{([\w-\.]+)(?:\:([\w\.]*)(?:\((.*?)?\))?)?\}/g,
45973
45974     /**
45975      * compile the template
45976      *
45977      * This is not recursive, so I'm not sure how nested templates are really going to be handled..
45978      *
45979      */
45980     compile: function()
45981     {
45982         var s = this.html;
45983      
45984         s = ['<tpl>', s, '</tpl>'].join('');
45985     
45986         var re     = /<tpl\b[^>]*>((?:(?=([^<]+))\2|<(?!tpl\b[^>]*>))*?)<\/tpl>/,
45987             nameRe = /^<tpl\b[^>]*?for="(.*?)"/,
45988             ifRe   = /^<tpl\b[^>]*?if="(.*?)"/,
45989             execRe = /^<tpl\b[^>]*?exec="(.*?)"/,
45990             namedRe = /^<tpl\b[^>]*?name="(\w+)"/,  // named templates..
45991             m,
45992             id     = 0,
45993             tpls   = [];
45994     
45995         while(true == !!(m = s.match(re))){
45996             var forMatch   = m[0].match(nameRe),
45997                 ifMatch   = m[0].match(ifRe),
45998                 execMatch   = m[0].match(execRe),
45999                 namedMatch   = m[0].match(namedRe),
46000                 
46001                 exp  = null, 
46002                 fn   = null,
46003                 exec = null,
46004                 name = forMatch && forMatch[1] ? forMatch[1] : '';
46005                 
46006             if (ifMatch) {
46007                 // if - puts fn into test..
46008                 exp = ifMatch && ifMatch[1] ? ifMatch[1] : null;
46009                 if(exp){
46010                    fn = new Function('values', 'parent', 'with(values){ return '+(Roo.util.Format.htmlDecode(exp))+'; }');
46011                 }
46012             }
46013             
46014             if (execMatch) {
46015                 // exec - calls a function... returns empty if true is  returned.
46016                 exp = execMatch && execMatch[1] ? execMatch[1] : null;
46017                 if(exp){
46018                    exec = new Function('values', 'parent', 'with(values){ '+(Roo.util.Format.htmlDecode(exp))+'; }');
46019                 }
46020             }
46021             
46022             
46023             if (name) {
46024                 // for = 
46025                 switch(name){
46026                     case '.':  name = new Function('values', 'parent', 'with(values){ return values; }'); break;
46027                     case '..': name = new Function('values', 'parent', 'with(values){ return parent; }'); break;
46028                     default:   name = new Function('values', 'parent', 'with(values){ return '+name+'; }');
46029                 }
46030             }
46031             var uid = namedMatch ? namedMatch[1] : id;
46032             
46033             
46034             tpls.push({
46035                 id:     namedMatch ? namedMatch[1] : id,
46036                 target: name,
46037                 exec:   exec,
46038                 test:   fn,
46039                 body:   m[1] || ''
46040             });
46041             if (namedMatch) {
46042                 s = s.replace(m[0], '');
46043             } else { 
46044                 s = s.replace(m[0], '{xtpl'+ id + '}');
46045             }
46046             ++id;
46047         }
46048         this.tpls = [];
46049         for(var i = tpls.length-1; i >= 0; --i){
46050             this.compileTpl(tpls[i]);
46051             this.tpls[tpls[i].id] = tpls[i];
46052         }
46053         this.master = tpls[tpls.length-1];
46054         return this;
46055     },
46056     /**
46057      * same as applyTemplate, except it's done to one of the subTemplates
46058      * when using named templates, you can do:
46059      *
46060      * var str = pl.applySubTemplate('your-name', values);
46061      *
46062      * 
46063      * @param {Number} id of the template
46064      * @param {Object} values to apply to template
46065      * @param {Object} parent (normaly the instance of this object)
46066      */
46067     applySubTemplate : function(id, values, parent)
46068     {
46069         
46070         
46071         var t = this.tpls[id];
46072         
46073         
46074         try { 
46075             if(t.test && !t.test.call(this, values, parent)){
46076                 return '';
46077             }
46078         } catch(e) {
46079             Roo.log("Xtemplate.applySubTemplate 'test': Exception thrown");
46080             Roo.log(e.toString());
46081             Roo.log(t.test);
46082             return ''
46083         }
46084         try { 
46085             
46086             if(t.exec && t.exec.call(this, values, parent)){
46087                 return '';
46088             }
46089         } catch(e) {
46090             Roo.log("Xtemplate.applySubTemplate 'exec': Exception thrown");
46091             Roo.log(e.toString());
46092             Roo.log(t.exec);
46093             return ''
46094         }
46095         try {
46096             var vs = t.target ? t.target.call(this, values, parent) : values;
46097             parent = t.target ? values : parent;
46098             if(t.target && vs instanceof Array){
46099                 var buf = [];
46100                 for(var i = 0, len = vs.length; i < len; i++){
46101                     buf[buf.length] = t.compiled.call(this, vs[i], parent);
46102                 }
46103                 return buf.join('');
46104             }
46105             return t.compiled.call(this, vs, parent);
46106         } catch (e) {
46107             Roo.log("Xtemplate.applySubTemplate : Exception thrown");
46108             Roo.log(e.toString());
46109             Roo.log(t.compiled);
46110             return '';
46111         }
46112     },
46113
46114     compileTpl : function(tpl)
46115     {
46116         var fm = Roo.util.Format;
46117         var useF = this.disableFormats !== true;
46118         var sep = Roo.isGecko ? "+" : ",";
46119         var undef = function(str) {
46120             Roo.log("Property not found :"  + str);
46121             return '';
46122         };
46123         
46124         var fn = function(m, name, format, args)
46125         {
46126             //Roo.log(arguments);
46127             args = args ? args.replace(/\\'/g,"'") : args;
46128             //["{TEST:(a,b,c)}", "TEST", "", "a,b,c", 0, "{TEST:(a,b,c)}"]
46129             if (typeof(format) == 'undefined') {
46130                 format= 'htmlEncode';
46131             }
46132             if (format == 'raw' ) {
46133                 format = false;
46134             }
46135             
46136             if(name.substr(0, 4) == 'xtpl'){
46137                 return "'"+ sep +'this.applySubTemplate('+name.substr(4)+', values, parent)'+sep+"'";
46138             }
46139             
46140             // build an array of options to determine if value is undefined..
46141             
46142             // basically get 'xxxx.yyyy' then do
46143             // (typeof(xxxx) == 'undefined' || typeof(xxx.yyyy) == 'undefined') ?
46144             //    (function () { Roo.log("Property not found"); return ''; })() :
46145             //    ......
46146             
46147             var udef_ar = [];
46148             var lookfor = '';
46149             Roo.each(name.split('.'), function(st) {
46150                 lookfor += (lookfor.length ? '.': '') + st;
46151                 udef_ar.push(  "(typeof(" + lookfor + ") == 'undefined')"  );
46152             });
46153             
46154             var udef_st = '((' + udef_ar.join(" || ") +") ? undef('" + name + "') : "; // .. needs )
46155             
46156             
46157             if(format && useF){
46158                 
46159                 args = args ? ',' + args : "";
46160                  
46161                 if(format.substr(0, 5) != "this."){
46162                     format = "fm." + format + '(';
46163                 }else{
46164                     format = 'this.call("'+ format.substr(5) + '", ';
46165                     args = ", values";
46166                 }
46167                 
46168                 return "'"+ sep +   udef_st   +    format + name + args + "))"+sep+"'";
46169             }
46170              
46171             if (args.length) {
46172                 // called with xxyx.yuu:(test,test)
46173                 // change to ()
46174                 return "'"+ sep + udef_st  + name + '(' +  args + "))"+sep+"'";
46175             }
46176             // raw.. - :raw modifier..
46177             return "'"+ sep + udef_st  + name + ")"+sep+"'";
46178             
46179         };
46180         var body;
46181         // branched to use + in gecko and [].join() in others
46182         if(Roo.isGecko){
46183             body = "tpl.compiled = function(values, parent){  with(values) { return '" +
46184                    tpl.body.replace(/(\r\n|\n)/g, '\\n').replace(/'/g, "\\'").replace(this.re, fn) +
46185                     "';};};";
46186         }else{
46187             body = ["tpl.compiled = function(values, parent){  with (values) { return ['"];
46188             body.push(tpl.body.replace(/(\r\n|\n)/g,
46189                             '\\n').replace(/'/g, "\\'").replace(this.re, fn));
46190             body.push("'].join('');};};");
46191             body = body.join('');
46192         }
46193         
46194         Roo.debug && Roo.log(body.replace(/\\n/,'\n'));
46195        
46196         /** eval:var:tpl eval:var:fm eval:var:useF eval:var:undef  */
46197         eval(body);
46198         
46199         return this;
46200     },
46201
46202     applyTemplate : function(values){
46203         return this.master.compiled.call(this, values, {});
46204         //var s = this.subs;
46205     },
46206
46207     apply : function(){
46208         return this.applyTemplate.apply(this, arguments);
46209     }
46210
46211  });
46212
46213 Roo.XTemplate.from = function(el){
46214     el = Roo.getDom(el);
46215     return new Roo.XTemplate(el.value || el.innerHTML);
46216 };// old names for panel elements
46217 Roo.GridPanel = Roo.panel.Grid;
46218 Roo.CalendarPanel = Roo.panel.Calendar;
46219 Roo.ContentPanel = Roo.panel.Content;
46220 Roo.NestedLayoutPanel = Roo.panel.NestedLayout;
46221 Roo.TabPanel = Roo.panel.Tab;
46222 Roo.TabPanelItem = Roo.panel.TabItem;
46223 Roo.TreePanel = Roo.panel.Tree;
46224
46225
46226 // phase 2 update
46227 Roo.ScrollPanel = Roo.panel.Scroll;
46228
46229 Roo.BorderLayout = Roo.layout.Border;
46230 Roo.BasicLayoutRegion = Roo.layout.BasicRegion;
46231 Roo.LayoutRegion = Roo.layout.Region;
46232 Roo.SplitLayoutRegion = Roo.layout.SplitRegion;
46233 Roo.LayoutManager = Roo.layout.Manager;
46234
46235
46236 Roo.NorthLayoutRegion = Roo.layout.North;
46237 Roo.EastLayoutRegion = Roo.layout.East;
46238 Roo.WestLayoutRegion = Roo.layout.West;
46239 Roo.SouthLayoutRegion = Roo.layout.South;
46240 Roo.CenterLayoutRegion = Roo.layout.Center;
46241
46242
46243 Roo.LayoutStateManager  = Roo.layout.StateManager;
46244 Roo.ReaderLayout = Roo.layout.Reader;
46245